file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
list
attention_mask
list
labels
list
./full_match/4/0xD91EEB9c8Db7973aBaCE1cdD8C8508E1a045A24C/sources/contracts/IdVerify.sol
Data requested by the institution
mapping(address => idRequest[]) dataRequested;
687,348
[ 1, 751, 3764, 635, 326, 1804, 305, 1421, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2874, 12, 2867, 516, 612, 691, 63, 5717, 501, 11244, 31, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* Copyright 2018 CoinAlpha, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.4.21; import "./zeppelin/SafeMath.sol"; import "./zeppelin/StandardToken.sol"; import "./zeppelin/ERC20.sol"; import "./BasketRegistry.sol"; import "./KYC.sol"; contract IBasket { // Called by BasketEscrow function isWhitelistedHolder(address _address) public view returns (bool) {} } /// @title Basket -- Basket contract for bundling and debundling tokens /// @author CoinAlpha, Inc. <[email protected]> contract Basket is StandardToken { using SafeMath for uint; // Constants set at contract inception string public name; string public symbol; uint public decimals; address[] public tokens; uint[] public weights; address public arranger; address public arrangerFeeRecipient; uint public arrangerFee; bool public kycEnabled; // mapping of token addresses to mapping of account balances // ADDRESS USER || ADDRESS TOKEN || UINT BALANCE mapping(address => mapping(address => uint)) public outstandingBalance; // Modules IBasketRegistry public basketRegistry; IKYC public kyc; // Modifiers modifier onlyArranger { require(msg.sender == arranger); // Check: "Only the Arranger can call this function" _; } /// @dev For transactions resulting in token transfers, check that the token recipient is whitelisted modifier onlyWhitelistedHolder(address _to) { require(isWhitelistedHolder(_to)); _; } // Events event LogDepositAndBundle(address indexed holder, uint indexed quantity); event LogDebundleAndWithdraw(address indexed holder, uint indexed quantity); event LogPartialDebundle(address indexed holder, uint indexed quantity); event LogWithdraw(address indexed holder, address indexed token, uint indexed quantity); event LogArrangerFeeRecipientChange(address indexed oldRecipient, address indexed newRecipient); event LogArrangerFeeChange(uint indexed oldFee, uint indexed newFee); /// @dev Basket constructor /// @param _name Token name /// @param _symbol Token symbol /// @param _tokens Array of ERC20 token addresses /// @param _weights Array of ERC20 token quantities /// @param _basketRegistryAddress Address of basket registry /// @param _arranger Address of arranger /// @param _arrangerFeeRecipient Address to send arranger fees /// @param _arrangerFee Amount of fee in ETH for every basket minted function Basket( string _name, string _symbol, address[] _tokens, uint[] _weights, address _basketRegistryAddress, address _kycAddress, address _arranger, address _arrangerFeeRecipient, uint _arrangerFee // in wei, i.e. 1e18 = 1 ETH ) public { // Check: "Constructor: invalid number of tokens and weights" require(_tokens.length > 0 && _tokens.length == _weights.length); name = _name; symbol = _symbol; tokens = _tokens; weights = _weights; basketRegistry = IBasketRegistry(_basketRegistryAddress); kyc = IKYC(_kycAddress); if (_kycAddress != address(0)) { kycEnabled = true; } else { kycEnabled = false; } arranger = _arranger; arrangerFeeRecipient = _arrangerFeeRecipient; arrangerFee = _arrangerFee; decimals = 18; } /// @dev Combined deposit of all component tokens (not yet deposited) and bundle /// @param _quantity Quantity of basket tokens to mint /// @return success Operation successful function depositAndBundle(uint _quantity) public onlyWhitelistedHolder(msg.sender) payable returns (bool success) { for (uint i = 0; i < tokens.length; i++) { address t = tokens[i]; uint w = weights[i]; ERC20(t).transferFrom(msg.sender, this, w.mul(_quantity).div(10 ** decimals)); } // charging suppliers a fee for every new basket minted // skip fees if tokens are minted through swaps if (arrangerFee > 0) { // Check: "Insufficient ETH for arranger fee to bundle" require(msg.value >= arrangerFee.mul(_quantity).div(10 ** decimals)); arrangerFeeRecipient.transfer(msg.value); } else { // prevent transfers of unnecessary ether into the contract require(msg.value == 0); } balances[msg.sender] = balances[msg.sender].add(_quantity); totalSupply_ = totalSupply_.add(_quantity); basketRegistry.incrementBasketsMinted(_quantity, msg.sender); emit LogDepositAndBundle(msg.sender, _quantity); return true; } /// @dev Convert basketTokens back to original tokens and transfer to requester /// @param _quantity Quantity of basket tokens to convert back to original tokens /// @return success Operation successful function debundleAndWithdraw(uint _quantity) public returns (bool success) { require(debundle(_quantity, msg.sender, msg.sender)); emit LogDebundleAndWithdraw(msg.sender, _quantity); return true; } /// @dev Convert basketTokens back to original tokens and transfer to specified recipient /// @param _quantity Quantity of basket tokens to swap /// @param _sender Address of transaction sender /// @param _recipient Address of token recipient /// @return success Operation successful function debundle( uint _quantity, address _sender, address _recipient ) internal returns (bool success) { require(balances[_sender] >= _quantity); // Check: "Insufficient basket balance to debundle" // decrease holder balance and total supply by _quantity balances[_sender] = balances[_sender].sub(_quantity); totalSupply_ = totalSupply_.sub(_quantity); // transfer tokens back to _recipient for (uint i = 0; i < tokens.length; i++) { address t = tokens[i]; uint w = weights[i]; ERC20(t).transfer(_recipient, w.mul(_quantity).div(10 ** decimals)); } basketRegistry.incrementBasketsBurned(_quantity, _sender); return true; } /// @dev Allow holder to convert baskets to its underlying tokens and withdraw them individually /// @param _quantity quantity of tokens to burn /// @return success Operation successful function burn(uint _quantity) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(_quantity); totalSupply_ = totalSupply_.sub(_quantity); // increase outstanding balance of each of the tokens by their weights for (uint i = 0; i < tokens.length; i++) { address t = tokens[i]; uint w = weights[i]; outstandingBalance[msg.sender][t] = outstandingBalance[msg.sender][t].add(w.mul(_quantity).div(10 ** decimals)); } basketRegistry.incrementBasketsBurned(_quantity, msg.sender); return true; } /// @dev Allow holder to withdraw outstanding balances from contract (such as previously paused tokens) /// @param _token Address of token to withdraw /// @return success Operation successful function withdraw(address _token) public returns (bool success) { uint bal = outstandingBalance[msg.sender][_token]; require(bal > 0); outstandingBalance[msg.sender][_token] = 0; ERC20(_token).transfer(msg.sender, bal); emit LogWithdraw(msg.sender, _token, bal); return true; } /// @dev Change recipient of arranger fees /// @param _newRecipient New fee recipient /// @return success Operation successful function changeArrangerFeeRecipient(address _newRecipient) public onlyArranger returns (bool success) { // Check: "New receipient can not be 0x0 or the same as the current recipient" require(_newRecipient != address(0) && _newRecipient != arrangerFeeRecipient); address oldRecipient = arrangerFeeRecipient; arrangerFeeRecipient = _newRecipient; emit LogArrangerFeeRecipientChange(oldRecipient, arrangerFeeRecipient); return true; } /// @dev Change amount of fee charged for every basket minted /// @param _newFee New fee amount /// @return success Operation successful function changeArrangerFee(uint _newFee) public onlyArranger returns (bool success) { uint oldFee = arrangerFee; arrangerFee = _newFee; emit LogArrangerFeeChange(oldFee, arrangerFee); return true; } /// @dev ERC20 transfer with restrictions on receiver /// @param _to receiver /// @param _value value to be transferred /// @return success Operation successful function transfer(address _to, uint256 _value) public onlyWhitelistedHolder(_to) returns (bool) { super.transfer(_to, _value); return true; } /// @dev ERC20 transferFrom with restrictions on receiver /// @param _from sender /// @param _to receiver /// @param _value value to be transferred /// @return success Operation successful function transferFrom(address _from, address _to, uint256 _value) public onlyWhitelistedHolder(_to) returns (bool) { super.transferFrom(_from, _to, _value); return true; } /// @dev Check if the basket is kycEnabled and if _address is whitelisted /// @return isWhitelisted Return if holder is whitelisted function isWhitelistedHolder(address _address) public view returns (bool) { if (kycEnabled) { return kyc.isWhitelistedHolder(_address); } else { return true; } } /// @dev Fallback to reject any ether sent to contract // Check: "Baskets do not accept ETH transfers" function () public payable { revert(); } }
@dev ERC20 transfer with restrictions on receiver @param _to receiver @param _value value to be transferred @return success Operation successful
function transfer(address _to, uint256 _value) public onlyWhitelistedHolder(_to) returns (bool) { super.transfer(_to, _value); return true; }
12,591,547
[ 1, 654, 39, 3462, 7412, 598, 17499, 603, 5971, 282, 389, 869, 21394, 5971, 282, 389, 1132, 1171, 9079, 460, 358, 506, 906, 4193, 327, 2216, 17311, 4189, 6873, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 7412, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 1338, 18927, 329, 6064, 24899, 869, 13, 1135, 261, 6430, 13, 288, 203, 565, 2240, 18, 13866, 24899, 869, 16, 389, 1132, 1769, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Sources flattened with hardhat v2.8.2 https://hardhat.org // File contracts/lib/LibAppStorage.sol /** * SPDX-License-Identifier: MIT * * Copyright (c) 2021 YellowHeart * * 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 * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.8.9; enum AuthorizationState { Unused, Used, Canceled } struct AppStorage { address owner; address pauser; bool paused; address blacklister; mapping(address => bool) blacklisted; string name; string symbol; uint8 decimals; string currency; address masterMinter; bool initialized; bool initializing; bool initializedV2; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; uint256 totalSupply; mapping(address => bool) minters; mapping(address => uint256) minterAllowed; address rescuer; bytes32 domainSeparator; mapping(address => mapping(bytes32 => AuthorizationState)) authorizationStates; mapping(address => uint256) nonces; } library LibAppStorage { function diamondStorage() internal pure returns (AppStorage storage ds) { assembly { ds.slot := 0 } } } // File @openzeppelin/contracts/utils/math/[email protected] // // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File @openzeppelin/contracts/token/ERC20/[email protected] // // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) /** * @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/lib/LibContext.sol /** * * * Copyright (c) YellowHeart * * 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 * 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. */ /** * @title ECRecover * @notice A library that provides a safe ECDSA recovery function */ library LibContext { function _msgSender() internal view returns (address sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff) } } else { sender = msg.sender; } return sender; } } // File contracts/lib/LibOwnable.sol /** * * * Copyright (c) 2022 YellowHeart * * 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 * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ library LibOwnable { function _requireOnlyOwner() internal view { require( LibContext._msgSender() == LibAppStorage.diamondStorage().owner, "Ownable: caller is not the owner" ); } } // File contracts/common/Ownable.sol /** * * * Copyright (c) 2018 zOS Global Limited. * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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. */ /** * @notice The Ownable contract has an owner address, and provides basic * authorization control functions * @dev Forked from https://github.com/OpenZeppelin/openzeppelin-labs/blob/3887ab77b8adafba4a26ace002f3a684c1a3388b/upgradeability_ownership/contracts/ownership/Ownable.sol * Modifications: * 1. Consolidate OwnableStorage into this contract (7/13/18) * 2. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20) * 3. Make public functions external (5/27/20) */ contract Ownable { /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event OwnershipTransferred(address previousOwner, address newOwner); /** * @dev The constructor sets the original owner of the contract to the sender account. */ constructor() { setOwner(msg.sender); } /** * @dev Tells the address of the owner * @return the address of the owner */ function owner() external view returns (address) { return LibAppStorage.diamondStorage().owner; } /** * @dev Sets a new owner address */ function setOwner(address newOwner) internal { LibAppStorage.diamondStorage().owner = newOwner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { LibOwnable._requireOnlyOwner(); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) external onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(LibAppStorage.diamondStorage().owner, newOwner); setOwner(newOwner); } } // File contracts/lib/LibBlacklistable.sol /** * * * Copyright (c) 2022 YellowHeart * * 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 * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ library LibBlacklistable { function _requireBlacklister() internal view { require( msg.sender == LibAppStorage.diamondStorage().blacklister, "Blacklistable: caller is not the blacklister" ); } function _requireNotBlacklisted(address account) internal view { require( !LibAppStorage.diamondStorage().blacklisted[account], "Blacklistable: account is blacklisted" ); } } // File contracts/common/Blacklistable.sol /** * * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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. */ /** * @title Blacklistable Token * @dev Allows accounts to be blacklisted by a "blacklister" role */ contract Blacklistable is Ownable { event Blacklisted(address indexed account); event UnBlacklisted(address indexed account); event BlacklisterChanged(address indexed newBlacklister); /** * @dev Throws if called by any account other than the blacklister */ modifier onlyBlacklister() { LibBlacklistable._requireBlacklister(); _; } /** * @dev Throws if argument account is blacklisted * @param account The address to check */ modifier notBlacklisted(address account) { LibBlacklistable._requireNotBlacklisted(account); _; } function blacklister() external view returns (address) { return LibAppStorage.diamondStorage().blacklister; } /** * @dev Checks if account is blacklisted * @param account The address to check */ function isBlacklisted(address account) external view returns (bool) { return LibAppStorage.diamondStorage().blacklisted[account]; } /** * @dev Adds account to blacklist * @param account The address to blacklist */ function blacklist(address account) external onlyBlacklister { LibAppStorage.diamondStorage().blacklisted[account] = true; emit Blacklisted(account); } /** * @dev Removes account from blacklist * @param account The address to remove from the blacklist */ function unBlacklist(address account) external onlyBlacklister { LibAppStorage.diamondStorage().blacklisted[account] = false; emit UnBlacklisted(account); } function updateBlacklister(address newBlacklister) external onlyOwner { require(newBlacklister != address(0), "Blacklistable: new blacklister is the zero address"); AppStorage storage appStorage = LibAppStorage.diamondStorage(); appStorage.blacklister = newBlacklister; emit BlacklisterChanged(appStorage.blacklister); } } // File @openzeppelin/contracts/utils/introspection/[email protected] // // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/interfaces/[email protected] // // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) // File @openzeppelin/contracts/interfaces/[email protected] // // OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol) // File @openzeppelin/contracts/token/ERC20/extensions/[email protected] // // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.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); } // File @openzeppelin/contracts/interfaces/[email protected] // // OpenZeppelin Contracts v4.4.1 (interfaces/IERC20Metadata.sol) // File contracts/lib/LibERC20.sol /** * * * Copyright (c) 2022 YellowHeart * * 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 * 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. */ /** * @title ECRecover * @notice A library that provides a safe ECDSA recovery function */ library LibERC20 { using SafeMath for uint256; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Internal function to set allowance * @param owner_ Token owner's address * @param spender Spender's address * @param value Allowance amount */ 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"); AppStorage storage appStorage = LibAppStorage.diamondStorage(); appStorage.allowed[owner_][spender] = value; emit Approval(owner_, spender, value); } /** * @notice Internal function to increase the allowance by a given increment * @param owner Token owner's address * @param spender Spender's address * @param increment Amount of increase */ function _increaseAllowance( address owner, address spender, uint256 increment ) internal { AppStorage storage appStorage = LibAppStorage.diamondStorage(); uint256 currentAllowance = appStorage.allowed[owner][spender]; _approve(owner, spender, currentAllowance.add(increment)); } /** * @notice Internal function to decrease the allowance by a given decrement * @param owner Token owner's address * @param spender Spender's address * @param decrement Amount of decrease */ function _decreaseAllowance( address owner, address spender, uint256 decrement ) internal { AppStorage storage appStorage = LibAppStorage.diamondStorage(); _approve( owner, spender, appStorage.allowed[owner][spender].sub( decrement, "ERC20: decreased allowance below zero" ) ); } /** * @notice Internal function to process transfers * @param from Payer's address * @param to Payee's address * @param value Transfer amount */ function _transfer( address from, address to, uint256 value ) internal { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); AppStorage storage appStorage = LibAppStorage.diamondStorage(); require(value <= appStorage.balances[from], "ERC20: transfer amount exceeds balance"); appStorage.balances[from] = appStorage.balances[from].sub(value); appStorage.balances[to] = appStorage.balances[to].add(value); emit Transfer(from, to, value); } /** * @notice Transfer tokens by spending allowance * @param from Payer's address * @param to Payee's address * @param value Transfer amount * @return True if successful */ function _transferFrom( address from, address to, uint256 value ) internal returns (bool) { _transfer(from, to, value); AppStorage storage appStorage = LibAppStorage.diamondStorage(); address msgSender = LibContext._msgSender(); uint256 currentAllowance = appStorage.allowed[from][msgSender]; require(value <= currentAllowance, "ERC20: transfer amount exceeds allowance"); appStorage.allowed[from][msgSender] = currentAllowance.sub(value); return true; } } // File contracts/lib/LibPausable.sol /** * * * Copyright (c) 2022 YellowHeart * * 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 * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ library LibPausable { function _requireNotPaused() internal view { require(!LibAppStorage.diamondStorage().paused, "Pausable: paused"); } function _requireOnlyPauser() internal view { require( LibContext._msgSender() == LibAppStorage.diamondStorage().pauser, "Pausable: caller is not the pauser" ); } } // File contracts/common/Pausable.sol /** * * * Copyright (c) 2016 Smart Contract Solutions, Inc. * Copyright (c) 2018-2020 CENTRE SECZ0 * * 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 * 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. */ /** * @notice Base contract which allows children to implement an emergency stop * mechanism * @dev Forked from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/feb665136c0dae9912e08397c1a21c4af3651ef3/contracts/lifecycle/Pausable.sol * Modifications: * 1. Added pauser role, switched pause/unpause to be onlyPauser (6/14/2018) * 2. Removed whenNotPause/whenPaused from pause/unpause (6/14/2018) * 3. Removed whenPaused (6/14/2018) * 4. Switches ownable library to use ZeppelinOS (7/12/18) * 5. Remove constructor (7/13/18) * 6. Reformat, conform to Solidity 0.6 syntax and add error messages (5/13/20) * 7. Make public functions external (5/27/20) */ contract Pausable is Ownable { event Pause(); event Unpause(); event PauserChanged(address indexed newAddress); /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { LibPausable._requireNotPaused(); _; } /** * @dev throws if called by any account other than the pauser */ modifier onlyPauser() { LibPausable._requireOnlyPauser(); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() external onlyPauser { LibAppStorage.diamondStorage().paused = true; emit Pause(); } function paused() external view returns (bool) { return LibAppStorage.diamondStorage().paused; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() external onlyPauser { LibAppStorage.diamondStorage().paused = false; emit Unpause(); } function pauser() external view returns (address) { return LibAppStorage.diamondStorage().pauser; } /** * @dev update the pauser role */ function updatePauser(address newPauser) external onlyOwner { require(newPauser != address(0), "Pausable: new pauser is the zero address"); LibAppStorage.diamondStorage().pauser = newPauser; emit PauserChanged(LibAppStorage.diamondStorage().pauser); } } // File @openzeppelin/contracts/utils/[email protected] // // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{ value: value }(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/token/ERC20/utils/[email protected] // // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.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"); } } } // File contracts/common/Rescuable.sol /** * * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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 Rescuable is Ownable { using SafeERC20 for IERC20; event RescuerChanged(address indexed newRescuer); /** * @notice Returns current rescuer * @return Rescuer's address */ function rescuer() external view returns (address) { return LibAppStorage.diamondStorage().rescuer; } /** * @notice Revert if called by any account other than the rescuer. */ modifier onlyRescuer() { _requireOnlyRescuer(); _; } function _requireOnlyRescuer() internal view { require( msg.sender == LibAppStorage.diamondStorage().rescuer, "Rescuable: caller is not the rescuer" ); } /** * @notice Rescue ERC20 tokens locked up in this contract. * @param tokenContract ERC20 token contract address * @param to Recipient address * @param amount Amount to withdraw */ function rescueERC20( IERC20 tokenContract, address to, uint256 amount ) external onlyRescuer { tokenContract.safeTransfer(to, amount); } /** * @notice Assign the rescuer role to a given address. * @param newRescuer New rescuer's address */ function updateRescuer(address newRescuer) external onlyOwner { require(newRescuer != address(0), "Rescuable: new rescuer is the zero address"); LibAppStorage.diamondStorage().rescuer = newRescuer; emit RescuerChanged(newRescuer); } } // File @openzeppelin/contracts/proxy/beacon/[email protected] // // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // File @openzeppelin/contracts/utils/[email protected] // // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol) /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // File @openzeppelin/contracts/proxy/ERC1967/[email protected] // // OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Upgrade.sol) /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967Upgrade { // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require( Address.isContract(newImplementation), "ERC1967: new implementation is not a contract" ); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot( _ROLLBACK_SLOT ); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; Address.functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require( oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades" ); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlot.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } } } // File @openzeppelin/contracts/proxy/utils/[email protected] // // OpenZeppelin Contracts v4.4.1 (proxy/utils/UUPSUpgradeable.sol) /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is ERC1967Upgrade { /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; } // File contracts/common/BaseToken.sol /** * * * Copyright (c) 2022 YellowHeart * * 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 * 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. */ /** * @title BaseToken */ abstract contract BaseToken is UUPSUpgradeable, IERC165, IERC20, IERC20Metadata, Ownable, Pausable, Blacklistable, Rescuable { using SafeMath for uint256; AppStorage internal appStorage; event Mint(address indexed minter, address indexed to, uint256 amount); event Burn(address indexed burner, uint256 amount); event MinterConfigured(address indexed minter, uint256 minterAllowedAmount); event MinterRemoved(address indexed oldMinter); event MasterMinterChanged(address indexed newMasterMinter); function _msgSender() internal view virtual returns (address) { return LibContext._msgSender(); } /** * @dev Authorizes the contract owner to perform a contract upgrade. */ function _authorizeUpgrade(address) internal virtual override onlyOwner { this; } function implementation() external view returns (address) { return _getImplementation(); } function name() external view returns (string memory) { return appStorage.name; } function symbol() external view returns (string memory) { return appStorage.symbol; } function decimals() external view returns (uint8) { return appStorage.decimals; } /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC20).interfaceId || interfaceId == type(IERC20Metadata).interfaceId || interfaceId == type(IERC165).interfaceId; } /** * @dev Internal function to mint tokens. * @param to The address that will receive the minted tokens. * @param amount The amount of tokens to mint. Must be less than or equal * to the minterAllowance of the caller. * @return A boolean that indicates if the operation was successful. */ function _mint(address to, uint256 amount) internal returns (bool) { address msgSender = _msgSender(); appStorage.totalSupply = appStorage.totalSupply.add(amount); appStorage.balances[to] = appStorage.balances[to].add(amount); emit Mint(msgSender, to, amount); emit Transfer(address(0), to, amount); return true; } /** * @notice Amount of remaining tokens spender is allowed to transfer on * behalf of the token owner * @param tokenOwner Token owner's address * @param spender Spender's address * @return Allowance amount */ function allowance(address tokenOwner, address spender) external view override returns (uint256) { return appStorage.allowed[tokenOwner][spender]; } /** * @dev Get totalSupply of token */ function totalSupply() external view override returns (uint256) { return appStorage.totalSupply; } /** * @dev Get token balance of an account * @param account address The account */ function balanceOf(address account) external view override returns (uint256) { return appStorage.balances[account]; } /** * @notice Set spender's allowance over the caller's tokens to be a given * value. * @param spender Spender's address * @param value Allowance amount * @return True if successful */ function approve(address spender, uint256 value) external override whenNotPaused notBlacklisted(_msgSender()) notBlacklisted(spender) returns (bool) { LibERC20._approve(_msgSender(), spender, value); return true; } /** * @notice Transfer tokens by spending allowance * @param from Payer's address * @param to Payee's address * @param value Transfer amount * @return True if successful */ function transferFrom( address from, address to, uint256 value ) external override whenNotPaused notBlacklisted(_msgSender()) notBlacklisted(from) notBlacklisted(to) returns (bool) { return LibERC20._transferFrom(from, to, value); } /** * @notice Transfer tokens from the caller * @param to Payee's address * @param value Transfer amount * @return True if successful */ function transfer(address to, uint256 value) external override whenNotPaused notBlacklisted(_msgSender()) notBlacklisted(to) returns (bool) { LibERC20._transfer(_msgSender(), to, value); return true; } /** * @dev allows a user to burn some of its own tokens * Validates that amount is less than or equal to the caller's account balance * @param amount uint256 the amount of tokens to be burned */ function _burn(uint256 amount) internal virtual { address msgSender = _msgSender(); uint256 balance = appStorage.balances[msgSender]; require(amount > 0, "BaseToken: burn amount not greater than 0"); require(balance >= amount, "BaseToken: burn amount exceeds balance"); appStorage.totalSupply = appStorage.totalSupply.sub(amount); appStorage.balances[msgSender] = balance.sub(amount); } } // File contracts/lib/LibECRecover.sol /** * * * Copyright (c) 2016-2019 zOS Global Limited * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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. */ /** * @title ECRecover * @notice A library that provides a safe ECDSA recovery function */ library LibECRecover { /** * @notice Recover signer's address from a signed message * @dev Adapted from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/65e4ffde586ec89af3b7e9140bdc9235d1254853/contracts/cryptography/ECDSA.sol * Modifications: Accept v, r, and s as separate arguments * @param digest Keccak-256 hash digest of the signed message * @param v v of the signature * @param r r of the signature * @param s s of the signature * @return Signer address */ function recover( bytes32 digest, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECRecover: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECRecover: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(digest, v, r, s); require(signer != address(0), "ECRecover: invalid signature"); return signer; } } // File contracts/lib/LibEIP712.sol /** * * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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. */ /** * @title EIP712 * @notice A library that provides EIP712 helper functions */ library LibEIP712 { /** * @notice Make EIP712 domain separator * @param name Contract name * @param version Contract version * @return Domain separator */ function makeDomainSeparator(string memory name, string memory version) internal view returns (bytes32) { uint256 chainId; assembly { chainId := chainid() } return keccak256( abi.encode( 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, // = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)") keccak256(bytes(name)), keccak256(bytes(version)), chainId, address(this) ) ); } /** * @notice Recover signer's address from a EIP712 signature * @param domainSeparator Domain separator * @param v v of the signature * @param r r of the signature * @param s s of the signature * @param typeHashAndData Type hash concatenated with data * @return Signer's address */ function recover( bytes32 domainSeparator, uint8 v, bytes32 r, bytes32 s, bytes memory typeHashAndData ) internal pure returns (address) { bytes32 digest = keccak256( abi.encodePacked("\x19\x01", domainSeparator, keccak256(typeHashAndData)) ); return LibECRecover.recover(digest, v, r, s); } } // File @openzeppelin/contracts/interfaces/[email protected] // // OpenZeppelin Contracts v4.4.1 (interfaces/IERC1363.sol) interface IERC1363 is IERC165, IERC20 { /* * Note: the ERC-165 identifier for this interface is 0x4bbee2df. * 0x4bbee2df === * bytes4(keccak256('transferAndCall(address,uint256)')) ^ * bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) */ /* * Note: the ERC-165 identifier for this interface is 0xfb9ec8ce. * 0xfb9ec8ce === * bytes4(keccak256('approveAndCall(address,uint256)')) ^ * bytes4(keccak256('approveAndCall(address,uint256,bytes)')) */ /** * @dev Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver * @param to address The address which you want to transfer to * @param value uint256 The amount of tokens to be transferred * @return true unless throwing */ function transferAndCall(address to, uint256 value) external returns (bool); /** * @dev Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver * @param to address The address which you want to transfer to * @param value uint256 The amount of tokens to be transferred * @param data bytes Additional data with no specified format, sent in call to `to` * @return true unless throwing */ function transferAndCall( address to, uint256 value, bytes memory data ) external returns (bool); /** * @dev Transfer tokens from one address to another and then call `onTransferReceived` on receiver * @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 * @return true unless throwing */ function transferFromAndCall( address from, address to, uint256 value ) external returns (bool); /** * @dev Transfer tokens from one address to another and then call `onTransferReceived` on receiver * @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 * @param data bytes Additional data with no specified format, sent in call to `to` * @return true unless throwing */ function transferFromAndCall( address from, address to, uint256 value, bytes memory data ) external returns (bool); /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender * and then call `onApprovalReceived` on spender. * @param spender address The address which will spend the funds * @param value uint256 The amount of tokens to be spent */ function approveAndCall(address spender, uint256 value) external returns (bool); /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender * and then call `onApprovalReceived` on spender. * @param spender address The address which will spend the funds * @param value uint256 The amount of tokens to be spent * @param data bytes Additional data with no specified format, sent in call to `spender` */ function approveAndCall( address spender, uint256 value, bytes memory data ) external returns (bool); } // File @openzeppelin/contracts/interfaces/[email protected] // // OpenZeppelin Contracts v4.4.1 (interfaces/IERC1363Receiver.sol) interface IERC1363Receiver { /* * Note: the ERC-165 identifier for this interface is 0x88a7ca5c. * 0x88a7ca5c === bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)")) */ /** * @notice Handle the receipt of ERC1363 tokens * @dev Any ERC1363 smart contract calls this function on the recipient * after a `transfer` or a `transferFrom`. 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 token contract address is always the message sender. * @param operator address The address which called `transferAndCall` or `transferFromAndCall` function * @param from address The address which are token transferred from * @param value uint256 The amount of tokens transferred * @param data bytes Additional data with no specified format * @return `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))` * unless throwing */ function onTransferReceived( address operator, address from, uint256 value, bytes memory data ) external returns (bytes4); } // File @openzeppelin/contracts/interfaces/[email protected] // // OpenZeppelin Contracts v4.4.1 (interfaces/IERC1363Spender.sol) interface IERC1363Spender { /* * Note: the ERC-165 identifier for this interface is 0x7b04a2d0. * 0x7b04a2d0 === bytes4(keccak256("onApprovalReceived(address,uint256,bytes)")) */ /** * @notice Handle the approval of ERC1363 tokens * @dev Any ERC1363 smart contract calls this function on the recipient * after an `approve`. This function MAY throw to revert and reject the * approval. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the token contract address is always the message sender. * @param owner address The address which called `approveAndCall` function * @param value uint256 The amount of tokens to be spent * @param data bytes Additional data with no specified format * @return `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))` * unless throwing */ function onApprovalReceived( address owner, uint256 value, bytes memory data ) external returns (bytes4); } // File contracts/lib/LibERC1363.sol /** * * * Copyright (c) 2022 YellowHeart * * 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 * 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. */ /** * @title ECRecover * @notice A library that provides a safe ECDSA recovery function */ library LibERC1363 { using Address for address; using SafeMath for uint256; /* * Note: the ERC-165 identifier for this interface is 0x4bbee2df. * 0x4bbee2df === * bytes4(keccak256('transferAndCall(address,uint256)')) ^ * bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) */ bytes4 private constant INTERFACE_TRANSFER_AND_CALL = 0x4bbee2df; /* * Note: the ERC-165 identifier for this interface is 0xfb9ec8ce. * 0xfb9ec8ce === * bytes4(keccak256('approveAndCall(address,uint256)')) ^ * bytes4(keccak256('approveAndCall(address,uint256,bytes)')) */ bytes4 private constant INTERFACE_APPROVE_AND_CALL = 0xfb9ec8ce; function _supportsInterface(bytes4 interfaceId) internal pure returns (bool) { return interfaceId == INTERFACE_TRANSFER_AND_CALL || interfaceId == INTERFACE_APPROVE_AND_CALL || interfaceId == type(IERC1363).interfaceId; } /** * @dev Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver * @param to address The address which you want to transfer to * @param value uint256 The amount of tokens to be transferred * @param data bytes Additional data with no specified format, sent in call to `to` * @return true unless throwing */ function _transferAndCall( address to, uint256 value, bytes memory data ) internal returns (bool) { address msgSender = LibContext._msgSender(); LibERC20._transfer(msgSender, to, value); require( _checkAndCallTransfer(msgSender, to, value, data), "ERC1363: _checkAndCallTransfer reverts" ); return true; } /** * @dev Transfer tokens from one address to another and then call `onTransferReceived` on receiver * @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 * @param data bytes Additional data with no specified format, sent in call to `to` * @return true unless throwing */ function _transferFromAndCall( address from, address to, uint256 value, bytes memory data ) internal returns (bool) { LibERC20._transferFrom(from, to, value); require( _checkAndCallTransfer(from, to, value, data), "ERC1363: _checkAndCallTransfer reverts" ); return true; } /** * @dev Internal function to invoke `onTransferReceived` on a target address * The call is not executed if the target address is not a contract * @param sender address Representing the previous owner of the given token value * @param recipient address Target address that will receive the tokens * @param amount uint256 The amount mount of tokens 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 _checkAndCallTransfer( address sender, address recipient, uint256 amount, bytes memory data ) internal returns (bool) { if (!recipient.isContract()) { return false; } bytes4 retval = IERC1363Receiver(recipient).onTransferReceived( LibContext._msgSender(), sender, amount, data ); return (retval == IERC1363Receiver(recipient).onTransferReceived.selector); } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender * and then call `onApprovalReceived` on spender. * @param spender address The address which will spend the funds * @param value uint256 The amount of tokens to be spent * @param data bytes Additional data with no specified format, sent in call to `spender` */ function _approveAndCall( address spender, uint256 value, bytes memory data ) internal returns (bool) { LibERC20._approve(LibContext._msgSender(), spender, value); require( _checkAndCallApprove(spender, value, data), "ERC1363: _checkAndCallApprove reverts" ); return true; } /** * @dev Internal function to invoke `onApprovalReceived` on a target address * The call is not executed if the target address is not a contract * @param spender address The address which will spend the funds * @param amount uint256 The amount of tokens to be spent * @param data bytes Optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function _checkAndCallApprove( address spender, uint256 amount, bytes memory data ) internal returns (bool) { if (!spender.isContract()) { return false; } bytes4 retval = IERC1363Spender(spender).onApprovalReceived( LibContext._msgSender(), amount, data ); return (retval == IERC1363Spender(spender).onApprovalReceived.selector); } } // File contracts/common/ERC1363.sol /** * * * Copyright (c) 2022 YellowHeart * * 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 * 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. */ abstract contract ERC1363 is IERC1363, Pausable, Blacklistable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return LibERC1363._supportsInterface(interfaceId); } /** * @dev Transfer tokens from `msgSender` to another address and then call `onTransferReceived` on receiver * @param to address The address which you want to transfer to * @param value uint256 The amount of tokens to be transferred * @return true unless throwing */ function transferAndCall(address to, uint256 value) external whenNotPaused notBlacklisted(LibContext._msgSender()) notBlacklisted(to) returns (bool) { return LibERC1363._transferAndCall(to, value, ""); } /** * @dev Transfer tokens from `msgSender` to another address and then call `onTransferReceived` on receiver * @param to address The address which you want to transfer to * @param value uint256 The amount of tokens to be transferred * @param data bytes Additional data with no specified format, sent in call to `to` * @return true unless throwing */ function transferAndCall( address to, uint256 value, bytes memory data ) external whenNotPaused notBlacklisted(LibContext._msgSender()) notBlacklisted(to) returns (bool) { return LibERC1363._transferAndCall(to, value, data); } /** * @dev Transfer tokens from one address to another and then call `onTransferReceived` on receiver * @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 * @return true unless throwing */ function transferFromAndCall( address from, address to, uint256 value ) external whenNotPaused notBlacklisted(LibContext._msgSender()) notBlacklisted(from) notBlacklisted(to) returns (bool) { return LibERC1363._transferFromAndCall(from, to, value, ""); } /** * @dev Transfer tokens from one address to another and then call `onTransferReceived` on receiver * @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 * @param data bytes Additional data with no specified format, sent in call to `to` * @return true unless throwing */ function transferFromAndCall( address from, address to, uint256 value, bytes memory data ) external whenNotPaused notBlacklisted(LibContext._msgSender()) notBlacklisted(from) notBlacklisted(to) returns (bool) { return LibERC1363._transferFromAndCall(from, to, value, data); } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msgSender * and then call `onApprovalReceived` on spender. * @param spender address The address which will spend the funds * @param value uint256 The amount of tokens to be spent */ function approveAndCall(address spender, uint256 value) external whenNotPaused notBlacklisted(LibContext._msgSender()) notBlacklisted(spender) returns (bool) { return LibERC1363._approveAndCall(spender, value, ""); } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msgSender * and then call `onApprovalReceived` on spender. * @param spender address The address which will spend the funds * @param value uint256 The amount of tokens to be spent * @param data bytes Additional data with no specified format, sent in call to `spender` */ function approveAndCall( address spender, uint256 value, bytes memory data ) external whenNotPaused notBlacklisted(LibContext._msgSender()) notBlacklisted(spender) returns (bool) { return LibERC1363._approveAndCall(spender, value, data); } } // File contracts/lib/LibGasAbstraction.sol // // keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") bytes32 constant _TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267; // keccak256("ApproveWithAuthorization(address owner,address spender,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") bytes32 constant _APPROVE_WITH_AUTHORIZATION_TYPEHASH = 0x808c10407a796f3ef2c7ea38c0638ea9d2b8a1c63e3ca9e1f56ce84ae59df73c; // keccak256("IncreaseAllowanceWithAuthorization(address owner,address spender,uint256 increment,uint256 validAfter,uint256 validBefore,bytes32 nonce)") bytes32 constant _INCREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH = 0x424222bb050a1f7f14017232a5671f2680a2d3420f504bd565cf03035c53198a; // keccak256("DecreaseAllowanceWithAuthorization(address owner,address spender,uint256 decrement,uint256 validAfter,uint256 validBefore,bytes32 nonce)") bytes32 constant _DECREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH = 0xb70559e94cbda91958ebec07f9b65b3b490097c8d25c8dacd71105df1015b6d8; // keccak256("CancelAuthorization(address authorizer,bytes32 nonce)") bytes32 constant _CANCEL_AUTHORIZATION_TYPEHASH = 0x158b0a9edf7a828aad02f63cd515c68ef2f50ba807396f6d12842833a1597429; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)") bytes32 constant _PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; /** * @title Gas Abstraction * @notice Provide internal implementation for gas-abstracted transfers and * approvals * @dev Contracts that inherit from this must wrap these with publicly * accessible functions, optionally adding modifiers where necessary */ library LibGasAbstraction { event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce); event AuthorizationCanceled(address indexed authorizer, bytes32 indexed nonce); /** * @notice Verify a signed transfer authorization and execute if valid * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _transferWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { _requireValidAuthorization(from, nonce, validAfter, validBefore); bytes memory data = abi.encode( _TRANSFER_WITH_AUTHORIZATION_TYPEHASH, from, to, value, validAfter, validBefore, nonce ); require( LibEIP712.recover(LibAppStorage.diamondStorage().domainSeparator, v, r, s, data) == from, "GasAbstraction: invalid signature" ); _markAuthorizationAsUsed(from, nonce); LibERC20._transfer(from, to, value); } /** * @notice Verify a signed authorization for an increase in the allowance * granted to the spender and execute if valid * @param owner Token owner's address (Authorizer) * @param spender Spender's address * @param increment Amount of increase in allowance * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _increaseAllowanceWithAuthorization( address owner, address spender, uint256 increment, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { _requireValidAuthorization(owner, nonce, validAfter, validBefore); bytes memory data = abi.encode( _INCREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH, owner, spender, increment, validAfter, validBefore, nonce ); require( LibEIP712.recover(LibAppStorage.diamondStorage().domainSeparator, v, r, s, data) == owner, "GasAbstraction: invalid signature" ); _markAuthorizationAsUsed(owner, nonce); LibERC20._increaseAllowance(owner, spender, increment); } /** * @notice Verify a signed authorization for a decrease in the allowance * granted to the spender and execute if valid * @param owner Token owner's address (Authorizer) * @param spender Spender's address * @param decrement Amount of decrease in allowance * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _decreaseAllowanceWithAuthorization( address owner, address spender, uint256 decrement, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { _requireValidAuthorization(owner, nonce, validAfter, validBefore); bytes memory data = abi.encode( _DECREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH, owner, spender, decrement, validAfter, validBefore, nonce ); require( LibEIP712.recover(LibAppStorage.diamondStorage().domainSeparator, v, r, s, data) == owner, "GasAbstraction: invalid signature" ); _markAuthorizationAsUsed(owner, nonce); LibERC20._decreaseAllowance(owner, spender, decrement); } /** * @notice Verify a signed approval authorization and execute if valid * @param owner Token owner's address (Authorizer) * @param spender Spender's address * @param value Amount of allowance * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _approveWithAuthorization( address owner, address spender, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { _requireValidAuthorization(owner, nonce, validAfter, validBefore); bytes memory data = abi.encode( _APPROVE_WITH_AUTHORIZATION_TYPEHASH, owner, spender, value, validAfter, validBefore, nonce ); require( LibEIP712.recover(LibAppStorage.diamondStorage().domainSeparator, v, r, s, data) == owner, "GasAbstraction: invalid signature" ); _markAuthorizationAsUsed(owner, nonce); LibERC20._approve(owner, spender, value); } /** * @notice Attempt to cancel an authorization * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _cancelAuthorization( address authorizer, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { _requireUnusedAuthorization(authorizer, nonce); bytes memory data = abi.encode(_CANCEL_AUTHORIZATION_TYPEHASH, authorizer, nonce); require( LibEIP712.recover(LibAppStorage.diamondStorage().domainSeparator, v, r, s, data) == authorizer, "GasAbstraction: invalid signature" ); LibAppStorage.diamondStorage().authorizationStates[authorizer][nonce] = AuthorizationState .Canceled; emit AuthorizationCanceled(authorizer, nonce); } /** * @notice Check that an authorization is unused * @param authorizer Authorizer's address * @param nonce Nonce of the authorization */ function _requireUnusedAuthorization(address authorizer, bytes32 nonce) private view { require( LibAppStorage.diamondStorage().authorizationStates[authorizer][nonce] == AuthorizationState.Unused, "GasAbstraction: authorization is used or canceled" ); } /** * @notice Check that authorization is valid * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) */ function _requireValidAuthorization( address authorizer, bytes32 nonce, uint256 validAfter, uint256 validBefore ) private view { require(block.timestamp > validAfter, "GasAbstraction: authorization is not yet valid"); require(block.timestamp < validBefore, "GasAbstraction: authorization is expired"); _requireUnusedAuthorization(authorizer, nonce); } /** * @notice Mark an authorization as used * @param authorizer Authorizer's address * @param nonce Nonce of the authorization */ function _markAuthorizationAsUsed(address authorizer, bytes32 nonce) private { LibAppStorage.diamondStorage().authorizationStates[authorizer][nonce] = AuthorizationState .Used; emit AuthorizationUsed(authorizer, nonce); } /** * @notice Verify a signed approval permit and execute if valid * @param owner Token owner's address (Authorizer) * @param spender Spender's address * @param value Amount of allowance * @param deadline The time at which this expires (unix time) * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { require(deadline >= block.timestamp, "Permit: permit is expired"); AppStorage storage appStorage = LibAppStorage.diamondStorage(); bytes memory data = abi.encode( _PERMIT_TYPEHASH, owner, spender, value, appStorage.nonces[owner]++, deadline ); require( LibEIP712.recover(appStorage.domainSeparator, v, r, s, data) == owner, "Permit: invalid signature" ); LibERC20._approve(owner, spender, value); } } // File contracts/common/EIP712Domain.sol /** * * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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. */ /** * @title EIP712 Domain */ contract EIP712Domain { /** * @dev EIP712 Domain Separator */ // solhint-disable-next-line function DOMAIN_SEPARATOR() external view returns (bytes32) { return LibAppStorage.diamondStorage().domainSeparator; } } // File contracts/common/GasAbstraction.sol /** * * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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. */ /** * @title Gas Abstraction * @notice Provide internal implementation for gas-abstracted transfers and * approvals * @dev Contracts that inherit from this must wrap these with publicly * accessible functions, optionally adding modifiers where necessary */ abstract contract GasAbstraction is EIP712Domain { bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = _TRANSFER_WITH_AUTHORIZATION_TYPEHASH; bytes32 public constant APPROVE_WITH_AUTHORIZATION_TYPEHASH = _APPROVE_WITH_AUTHORIZATION_TYPEHASH; bytes32 public constant INCREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH = _INCREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH; bytes32 public constant DECREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH = _DECREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH; bytes32 public constant CANCEL_AUTHORIZATION_TYPEHASH = _CANCEL_AUTHORIZATION_TYPEHASH; event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce); event AuthorizationCanceled(address indexed authorizer, bytes32 indexed nonce); /** * @notice Returns the state of an authorization * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @return Authorization state */ function authorizationState(address authorizer, bytes32 nonce) external view returns (AuthorizationState) { return LibAppStorage.diamondStorage().authorizationStates[authorizer][nonce]; } /** * @notice Increase the allowance by a given increment * @param spender Spender's address * @param increment Amount of increase in allowance * @return True if successful */ function increaseAllowance(address spender, uint256 increment) external returns (bool) { LibPausable._requireNotPaused(); LibBlacklistable._requireNotBlacklisted(msg.sender); LibBlacklistable._requireNotBlacklisted(spender); LibERC20._increaseAllowance(msg.sender, spender, increment); return true; } /** * @notice Decrease the allowance by a given decrement * @param spender Spender's address * @param decrement Amount of decrease in allowance * @return True if successful */ function decreaseAllowance(address spender, uint256 decrement) external returns (bool) { LibPausable._requireNotPaused(); LibBlacklistable._requireNotBlacklisted(msg.sender); LibBlacklistable._requireNotBlacklisted(spender); LibERC20._decreaseAllowance(msg.sender, spender, decrement); return true; } /** * @notice Execute a transfer with a signed authorization * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function transferWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external { LibPausable._requireNotPaused(); LibBlacklistable._requireNotBlacklisted(from); LibBlacklistable._requireNotBlacklisted(to); LibGasAbstraction._transferWithAuthorization( from, to, value, validAfter, validBefore, nonce, v, r, s ); } /** * @notice Update allowance with a signed authorization * @param tokenOwner Token owner's address (Authorizer) * @param spender Spender's address * @param value Amount of allowance * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function approveWithAuthorization( address tokenOwner, address spender, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external { LibPausable._requireNotPaused(); LibBlacklistable._requireNotBlacklisted(tokenOwner); LibBlacklistable._requireNotBlacklisted(spender); LibGasAbstraction._approveWithAuthorization( tokenOwner, spender, value, validAfter, validBefore, nonce, v, r, s ); } /** * @notice Increase allowance with a signed authorization * @param tokenOwner Token owner's address (Authorizer) * @param spender Spender's address * @param increment Amount of increase in allowance * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function increaseAllowanceWithAuthorization( address tokenOwner, address spender, uint256 increment, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external { LibPausable._requireNotPaused(); LibBlacklistable._requireNotBlacklisted(tokenOwner); LibBlacklistable._requireNotBlacklisted(spender); LibGasAbstraction._increaseAllowanceWithAuthorization( tokenOwner, spender, increment, validAfter, validBefore, nonce, v, r, s ); } /** * @notice Decrease allowance with a signed authorization * @param tokenOwner Token owner's address (Authorizer) * @param spender Spender's address * @param decrement Amount of decrease in allowance * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function decreaseAllowanceWithAuthorization( address tokenOwner, address spender, uint256 decrement, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external { LibPausable._requireNotPaused(); LibBlacklistable._requireNotBlacklisted(tokenOwner); LibBlacklistable._requireNotBlacklisted(spender); LibGasAbstraction._decreaseAllowanceWithAuthorization( tokenOwner, spender, decrement, validAfter, validBefore, nonce, v, r, s ); } /** * @notice Attempt to cancel an authorization * @dev Works only if the authorization is not yet used. * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function cancelAuthorization( address authorizer, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external { LibPausable._requireNotPaused(); LibGasAbstraction._cancelAuthorization(authorizer, nonce, v, r, s); } } // File contracts/common/Permit.sol /** * * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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. */ /** * @title Permit * @notice An alternative to approveWithAuthorization, provided for * compatibility with the draft EIP2612 proposed by Uniswap. * @dev Differences: * - Uses sequential nonce, which restricts transaction submission to one at a * time, or else it will revert * - Has deadline (= validBefore - 1) but does not have validAfter * - Doesn't have a way to change allowance atomically to prevent ERC20 multiple * withdrawal attacks */ abstract contract Permit is EIP712Domain { bytes32 public constant PERMIT_TYPEHASH = _PERMIT_TYPEHASH; /** * @notice Nonces for permit (shared with meta transaction) * @dev Nonces is shared for permits and meta transaction nonces. The nonces and getNonce * methods both return the same nonce sequence, but are both kept for compatability * @param owner Token owner's address (Authorizer) * @return Next nonce */ function nonces(address owner) external view returns (uint256) { return LibAppStorage.diamondStorage().nonces[owner]; } /** * @notice Update allowance with a signed permit * @param tokenOwner Token owner's address (Authorizer) * @param spender Spender's address * @param value Amount of allowance * @param deadline Expiration time, seconds since the epoch * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function permit( address tokenOwner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { LibPausable._requireNotPaused(); LibBlacklistable._requireNotBlacklisted(tokenOwner); LibBlacklistable._requireNotBlacklisted(spender); LibGasAbstraction._permit(tokenOwner, spender, value, deadline, v, r, s); } } // File contracts/tokens/HeartToken.sol /** * * * Copyright (c) 2022 YellowHeart * * 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 * 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 HeartToken is BaseToken, GasAbstraction, Permit, ERC1363 { using SafeMath for uint256; uint256 public constant MAX_SUPPLY = 692000000 * 1e18; function initialize( string memory tokenName, string memory tokenSymbol, address newPauser, address newBlacklister, address newOwner, address tokenReceiver ) external { require(!appStorage.initialized, "HeartToken: contract is already initialized"); require(newPauser != address(0), "HeartToken: new pauser is the zero address"); require(newBlacklister != address(0), "HeartToken: new blacklister is the zero address"); require(newOwner != address(0), "HeartToken: new owner is the zero address"); require(tokenReceiver != address(0), "HeartToken: token receiver is the zero address"); appStorage.name = tokenName; appStorage.symbol = tokenSymbol; appStorage.decimals = 18; // appStorage.masterMinter = newMasterMinter; appStorage.pauser = newPauser; appStorage.blacklister = newBlacklister; setOwner(newOwner); appStorage.domainSeparator = LibEIP712.makeDomainSeparator(tokenName, "1"); _mint(tokenReceiver, MAX_SUPPLY); require( appStorage.totalSupply == MAX_SUPPLY, "HeartToken: totalSupply is not expected value" ); require( appStorage.balances[tokenReceiver] == MAX_SUPPLY, "HeartToken: tokenReceiver balance is not expected value" ); appStorage.initialized = true; } /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override(BaseToken, ERC1363) returns (bool) { return ERC1363.supportsInterface(interfaceId) || BaseToken.supportsInterface(interfaceId); } }
* @dev Transfer tokens from one address to another and then call `onTransferReceived` on receiver @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 @param data bytes Additional data with no specified format, sent in call to `to` @return true unless throwing/
function _transferFromAndCall( address from, address to, uint256 value, bytes memory data ) internal returns (bool) { LibERC20._transferFrom(from, to, value); require( _checkAndCallTransfer(from, to, value, data), "ERC1363: _checkAndCallTransfer reverts" ); return true; }
6,926,078
[ 1, 5912, 2430, 628, 1245, 1758, 358, 4042, 471, 1508, 745, 1375, 265, 5912, 8872, 68, 603, 5971, 225, 628, 1758, 1021, 1758, 1492, 1846, 2545, 358, 1366, 2430, 628, 225, 358, 1758, 1021, 1758, 1492, 1846, 2545, 358, 7412, 358, 225, 460, 2254, 5034, 1021, 3844, 434, 2430, 358, 506, 906, 4193, 225, 501, 1731, 15119, 501, 598, 1158, 1269, 740, 16, 3271, 316, 745, 358, 1375, 869, 68, 327, 638, 3308, 19440, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 1265, 1876, 1477, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 460, 16, 203, 3639, 1731, 3778, 501, 203, 565, 262, 2713, 1135, 261, 6430, 13, 288, 203, 3639, 10560, 654, 39, 3462, 6315, 13866, 1265, 12, 2080, 16, 358, 16, 460, 1769, 203, 3639, 2583, 12, 203, 5411, 389, 1893, 1876, 1477, 5912, 12, 2080, 16, 358, 16, 460, 16, 501, 3631, 203, 5411, 315, 654, 39, 3437, 4449, 30, 389, 1893, 1876, 1477, 5912, 15226, 87, 6, 203, 3639, 11272, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-05-06 */ /****************************************************************************** * * * ;'+: * ''''''` * '''''''; * ''''''''+. * +''''''''', * '''''''''+'. * '''''''''''' * ''''''''''''' * ,'''''''''''''. * ''''''''''''''' * ''''''''''''''' * :'''''''''''''''. * ''''''''''''''''; * .''''''''''''''''' * '''''''''''''''''' * ;'''''''''''''''''' * '''''''''''''''''+' * '''''''''''''''''''' * '''''''''''''''''''', * ,'''''''''''''''''''' * ''''''''''''''''''''' * ''''''''''''''''''''': * ''''''''''''''''''''+' * `''''''''''''''''''''': * '''''''''''''''''''''' * .'''''''''''''''''''''; * ''''''''''''''''''''''` * '''''''''''''''''''''' * '''''''''''''''''''''' * : '''''''''''''''''''''' * ,: '''''''''''''''''''''' * :::. ''+''''''''''''''''''': * ,:,,:` .:::::::,. :''''''''''''''''''''''. * ,,,::::,.,::::::::,:::,::,'''''''''''''''''''''''; * :::::::,::,::::::::,,,''''''''''''''''''''''''''''''` * :::::::::,::::::::;'''''''''''''''''''''''''''''''''+` * ,:,::::::::::::,;'''''''''''''''''''''''''''''''''''''; * :,,:::::::::::''''''''''''''''''''''''''''''''''''''''' * ::::::::::,'''''''''''''''''''''''''''''''''''''''''''' * :,,:,:,:''''''''''''''''''''''''''''''''''''''''''''''` * .;::;''''''''''''''''''''''''''''''''''''''''''''''''' * :'+''''''''''''''''''''''''''''''''''''''''''''''' * ``.::;'''''''''''''';;:::,..`````,'''''''''', * '''''''; * '''''' * .'''''''; ''''''''''''' '''''''' ''''' * '''''''''''` ''''''''''''' ;''''''''''; '''; * ''' '''` '' ''', ,''' '': * ''' : '' `'' ''` :'` * '' '' '': :'' ' * '' '''''''''' '' '' ' * `'' ''''''''' '''''''''' '' '' * '' '''''''': '' '' '' * '' '' '' ''' ''' * ''' ''' '' ''' ''' * '''. .''' '' '''. .''' * `'''''''''' '''''''''''''` `'''''''''' * ''''''' '''''''''''''` .''''''. * * *********************************************************************************************/ pragma solidity 0.8.4; // ------------------------------------------------------------------------------------------------------------------------- // 'iBlockchain Bank & Trust™' ERC20 Security Token (Common Share) // // Symbol : SCCs // Trademarks (tm) : SCCs™ , SCCsS™ , Sustainability Creative™ , Decentralised Autonomous Corporation™ , DAC™ // Name : Share/Common Stock/Security Token // Total supply : 10,000,000 (Million) // Decimals : 2 // Implementation : Decentralized Autonomous Corporation (DAC) // Website : https://sustainabilitycreative.com | https://sustainabilitycreative.solutions // Github : https://github.com/Geopay/iBlockchain-Bank-and-Trust-Security-Token // Beta Platform : https://myetherbanktrust.com/asset-class/primary-market/smart-securities/ // // (c) by A. Valamontes with Blockchain Ventures / iBlockchain Bank & Trust Technologies Co. 2013-2021. Affero GPLv3 Licence. // -------------------------------------------------------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // (c) by A. Valamontes with Blockchain Ventures / iBlockchain Bank & Trust Technologies Co. 2013-2021. Affero GPLv3 Licence. // ------------------------------------------------------------------------------------------------------------------------- contract Ownable { address public owner; constructor() { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function DissolveBusiness() public onlyOwner { // This function is called when the organization is no longer actively operating // The Management can decide to Terminate access to the Securities Token. // The Blockchain records remain, but the contract no longer can perform functions pertaining // to the operations of the Securities. // https://www.irs.gov/businesses/small-businesses-self-employed/closing-a-business-checklist selfdestruct(payable(msg.sender)); } } // (c) by A. Valamontes with Blockchain Ventures / iBlockchain Bank & Trust Technologies Co. 2013-2021. Affero GPLv3 Licence. // ------------------------------------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------------------------- interface ERC20Interface { function transfer(address to, uint tokens) external returns (bool success); } contract Regulated is Ownable { event ShareholderRegistered(address indexed shareholder); event CorpBlackBook(address indexed shareholder); // Consider this option as the Nevada Commission little black book, bad actors are blacklisted mapping(address => bool) regulationStatus; function RegisterShareholder(address shareholder) public onlyOwner { regulationStatus[shareholder] = true; emit ShareholderRegistered(shareholder); } function NevadaBlackBook(address shareholder) public onlyOwner { regulationStatus[shareholder] = false; emit CorpBlackBook(shareholder); } function ensureRegulated(address shareholder) view internal { require(regulationStatus[shareholder] == true); } function isRegulated(address shareholder) public view returns (bool approved) { return regulationStatus[shareholder]; } } // (c) by A. Valamontes with Blockchain Ventures / iBlockchain Bank & Trust Technologies Co. 2013-2021. Affero GPLv3 Licence. // -------------------------------------------------------------------------------------------------------------------------- contract AcceptEth is Regulated { //address public owner; //address newOwner; uint public price; mapping (address => uint) balance; constructor() { // set owner as the address of the one who created the contract owner = msg.sender; // set the price to 2 ether price = 0.00372805 ether; // Exclude Gas/Wei to transfer } /** * Price must be in WEI. which means, if you want to make price 2 ether, * then you must input 2 * 1e18 which will be: 2000000000000000000 */ function updatePrice(uint256 _priceInWEI) external onlyOwner returns(string memory){ require(_priceInWEI > 0, 'Invalid price amount'); price = _priceInWEI; return "Price updated successfully"; } function accept() public payable onlyOwner { // Error out if anything other than 2 ether is sent require(msg.value == price); //require(newOwner != address(0)); //require(newOwner != owner); RegisterShareholder(owner); //regulationStatus[owner] = true; //emit ShareholderRegistered(owner); // Track that calling account deposited ether balance[msg.sender] += msg.value; } function refund(uint amountRequested) public onlyOwner { //require(newOwner != address(0)); //require(newOwner != owner); RegisterShareholder(owner); //regulationStatus[owner] = true; //emit ShareholderRegistered(owner); require(amountRequested > 0 && amountRequested <= balance[msg.sender]); balance[msg.sender] -= amountRequested; payable(msg.sender).transfer(amountRequested); // contract transfers ether to msg.sender's address } event Accept(address from, address indexed to, uint amountRequested); event Refund(address to, address indexed from, uint amountRequested); } contract SCCs is Regulated, AcceptEth { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalShares; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); constructor() { // (c) by A. Valamontes with Blockchain Ventures / iBlockchain Bank & Trust Technologies Co. 2013-2021. Affero GPLv3 Licence. // -------------------------------------------------------------------------------------------------------------------------- symbol = "SCCs"; // Create the Security Token Symbol Here name = "Sustainability Creative eShare "; // Description of the Securetized Tokens // In our sample we have created securites tokens and fractional securities for the tokens upto 18 digits decimals = 2; // Number of Digits [0-18] If an organization wants to fractionalize the securities // The 0 can be any digit up to 18. Eighteen is the standard for cryptocurrencies _totalShares = 10000000 * 10**uint(decimals); // Total Number of Securities Issued (example 10,000,000 Shares of iBBTs) balances[owner] = _totalShares; emit Transfer(address(0), owner, _totalShares); // Owner or Company Representative (CFO/COO/CEO/CHAIRMAN) regulationStatus[owner] = true; emit ShareholderRegistered(owner); } // -------------------------------------------------------------------------------------------- // Don't accept ETH // -------------------------------------------------------------------------------------------- //fallback () external payable {revert();} function issue(address recipient, uint tokens) public onlyOwner returns (bool success) { require(recipient != address(0)); require(recipient != owner); RegisterShareholder(recipient); transfer(recipient, tokens); return true; } function transferOwnership(address newOwner) public onlyOwner { // Organization is Merged or Sold and Securities Management needs to transfer to new owners require(newOwner != address(0)); require(newOwner != owner); RegisterShareholder(newOwner); transfer(newOwner, balances[owner]); owner = newOwner; } function totalSupply() public view returns (uint supply) { return _totalShares - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { ensureRegulated(msg.sender); ensureRegulated(to); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { // Put a check for race condition issue with approval workflow of ERC20 require((tokens == 0) || (allowed[msg.sender][spender] == 0)); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { ensureRegulated(from); ensureRegulated(to); balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // -------------------------------------------------------------------------------------------------- // Corporation can issue more shares or revoke/cancel shares // https://github.com/ethereum/EIPs/pull/621 // -------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------------- // Owner can transfer out any accidentally sent ERC20 tokens // -------------------------------------------------------------------------------------------------- function transferOtherERC20Assets(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } } // ---------------------------------------------------------------------------------------------------- // SPDX-License-Identifier: Affero GPLv3 Licence. | https://ibbt.io // (c) by A. Valamontes with Blockchain Ventures / iBlockchain Bank & Trust Tecnhnologies Co. 2020-2021. // -----------------------------------------------------------------------------------------------------
Number of Digits [0-18] If an organization wants to fractionalize the securities
decimals = 2;
7,680,768
[ 1, 1854, 434, 11678, 1282, 306, 20, 17, 2643, 65, 971, 392, 6758, 14805, 358, 20462, 554, 326, 1428, 295, 1961, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 15105, 273, 576, 31, 4766, 1171, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* * Copyright (c) The Force Protocol Development Team * Submitted for verification at Etherscan.io on 2019-09-17 */ pragma solidity 0.5.13; // pragma experimental ABIEncoderV2; import "./ReentrancyGuard.sol"; /** * 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 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, "uint mul overflow"); 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, "uint div by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev 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, "uint sub overflow"); 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, "uint add overflow"); 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, "uint mod by zero"); return a % b; } } /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @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' require((value == 0) || (token.allowance(address(this), spender) == 0)); 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 ); 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. require(address(token).isContract()); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool))); } } } library addressMakePayable { function makePayable(address x) internal pure returns (address payable) { return address(uint160(x)); } } contract IOracle { function get(address token) external view returns (uint256, bool); } contract IInterestRateModel { function getLoanRate(int256 cash, int256 borrow) external view returns (int256 y); function getDepositRate(int256 cash, int256 borrow) external view returns (int256 y); function calculateBalance( int256 principal, int256 lastIndex, int256 newIndex ) external view returns (int256 y); function calculateInterestIndex( int256 Index, int256 r, int256 t ) external view returns (int256 y); function pert( int256 principal, int256 r, int256 t ) external view returns (int256 y); function getNewReserve( int256 oldReserve, int256 cash, int256 borrow, int256 blockDelta ) external view returns (int256 y); } contract PoolPawn is ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; using addressMakePayable for address; uint public constant int_max = 57896044618658097711785492504343953926634992332820282019728792003956564819967; address public admin; //the admin address address public proposedAdmin; //use pull over push pattern for admin // uint256 public constant interestRateDenomitor = 1e18; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ // Balance struct struct Balance { uint256 principal; uint256 interestIndex; uint256 totalPnl; //total profit and loss } struct Market { uint256 accrualBlockNumber; int256 supplyRate; //存款利率 int256 demondRate; //借款利率 IInterestRateModel irm; uint256 totalSupply; uint256 supplyIndex; uint256 totalBorrows; uint256 borrowIndex; uint256 totalReserves; //系统盈利 uint256 minPledgeRate; //最小质押率 uint256 liquidationDiscount; //清算折扣 uint256 decimals; //币种的最小精度 } // Mappings of users' balance of each token mapping(address => mapping(address => Balance)) public accountSupplySnapshot; //tokenContract->address(usr)->SupplySnapshot mapping(address => mapping(address => Balance)) public accountBorrowSnapshot; //tokenContract->address(usr)->BorrowSnapshot struct LiquidateInfo { address targetAccount; //被清算账户 address liquidator; //清算人 address assetCollatera; //抵押物token地址 address assetBorrow; //债务token地址 uint256 liquidateAmount; //清算额度,抵押物 uint256 targetAmount; //目标额度, 债务 uint256 timestamp; } mapping(uint256 => LiquidateInfo) public liquidateInfoMap; uint256 public liquidateIndexes; function setLiquidateInfoMap( address _targetAccount, address _liquidator, address _assetCollatera, address _assetBorrow, uint256 x, uint256 y ) internal { LiquidateInfo memory newStruct = LiquidateInfo( _targetAccount, _liquidator, _assetCollatera, _assetBorrow, x, y, block.timestamp ); // Update liquidation record liquidateInfoMap[liquidateIndexes] = newStruct; liquidateIndexes++; } //user table mapping(uint256 => address) public accounts; mapping(address => uint256) public indexes; uint256 public index = 1; // Add new user function join(address who) internal { if (indexes[who] == 0) { accounts[index] = who; indexes[who] = index; ++index; } } event SupplyPawnLog( address usr, address t, uint256 amount, uint256 beg, uint256 end ); event WithdrawPawnLog( address usr, address t, uint256 amount, uint256 beg, uint256 end ); event BorrowPawnLog( address usr, address t, uint256 amount, uint256 beg, uint256 end ); event RepayFastBorrowLog( address usr, address t, uint256 amount, uint256 beg, uint256 end ); event LiquidateBorrowPawnLog( address usr, address tBorrow, uint256 endBorrow, address liquidator, address tCol, uint256 endCol ); event WithdrawPawnEquityLog( address t, uint256 equityAvailableBefore, uint256 amount, address owner ); mapping(address => Market) public mkts; //tokenAddress->Market address[] public collateralTokens; //抵押币种 IOracle public oracleInstance; uint256 public constant initialInterestIndex = 10**18; uint256 public constant defaultOriginationFee = 0; // default is zero bps uint256 public constant originationFee = 0; uint256 public constant ONE_ETH = 1 ether; // 增加抵押币种 function addCollateralMarket(address asset) public onlyAdmin { for (uint256 i = 0; i < collateralTokens.length; i++) { if (collateralTokens[i] == asset) { return; } } collateralTokens.push(asset); } function getCollateralMarketsLength() external view returns (uint256) { return collateralTokens.length; } function setInterestRateModel(address t, address irm) public onlyAdmin { mkts[t].irm = IInterestRateModel(irm); } function setMinPledgeRate(address t, uint256 minPledgeRate) external onlyAdmin { mkts[t].minPledgeRate = minPledgeRate; } function setLiquidationDiscount(address t, uint256 liquidationDiscount) external onlyAdmin { mkts[t].liquidationDiscount = liquidationDiscount; } function initCollateralMarket( address t, address irm, address oracle, uint256 decimals ) external onlyAdmin { if (address(oracleInstance) == address(0)) { setOracle(oracle); } Market memory m = mkts[t]; if (address(m.irm) == address(0)) { setInterestRateModel(t, irm); } addCollateralMarket(t); if (m.supplyIndex == 0) { m.supplyIndex = initialInterestIndex; } if (m.borrowIndex == 0) { m.borrowIndex = initialInterestIndex; } if (m.decimals == 0) { m.decimals = decimals; } mkts[t] = m; } constructor() public { admin = msg.sender; } //Starting from Solidity 0.4.0, contracts without a fallback function automatically revert payments, making the code above redundant. // function() external payable { // revert("fallback can't be payable"); // } modifier onlyAdmin() { require(msg.sender == admin, "only admin can do this!"); _; } function proposeNewAdmin(address admin_) external onlyAdmin { proposedAdmin = admin_; } function claimAdministration() external { require(msg.sender == proposedAdmin, "Not proposed admin."); admin = proposedAdmin; proposedAdmin = address(0); } // Set the initial timestamp of tokens function setInitialTimestamp(address token) external onlyAdmin { mkts[token].accrualBlockNumber = now; } function setDecimals(address t, uint256 decimals) external onlyAdmin { mkts[t].decimals = decimals; } function setOracle(address oracle) public onlyAdmin { oracleInstance = IOracle(oracle); } modifier existOracle() { require(address(oracleInstance) != address(0), "oracle not set"); _; } // Get price of oracle function fetchAssetPrice(address asset) public view returns (uint256, bool) { require(address(oracleInstance) != address(0), "oracle not set"); return oracleInstance.get(asset); } function valid_uint(uint r) internal view returns (int256) { require(r <= int_max, "uint r is not valid"); return int256(r); } // Get the price of assetAmount tokens function getPriceForAssetAmount(address asset, uint256 assetAmount) public view returns (uint256) { require(address(oracleInstance) != address(0), "oracle not set"); (uint256 price, bool ok) = fetchAssetPrice(asset); require(ok && price != 0, "invalid token price"); return price.mul(assetAmount).div(10**mkts[asset].decimals); } // Calc the token amount of usdValue function getAssetAmountForValue(address t, uint256 usdValue) public view returns (uint256) { require(address(oracleInstance) != address(0), "oracle not set"); (uint256 price, bool ok) = fetchAssetPrice(t); require(ok && price != 0, "invalid token price"); return usdValue.mul(10**mkts[t].decimals).div(price); } // Balance of "t" token of this contract function getCash(address t) public view returns (uint256) { // address(0) represents for eth if (t == address(0)) { return address(this).balance; } IERC20 token = IERC20(t); return token.balanceOf(address(this)); } // Balance of "asset" token of the "from" account function getBalanceOf(address asset, address from) internal view returns (uint256) { // address(0) represents for eth if (asset == address(0)) { return address(from).balance; } IERC20 token = IERC20(asset); return token.balanceOf(from); } // totalBorrows / totalSupply function loanToDepositRatio(address asset) public view returns (uint256) { uint256 loan = mkts[asset].totalBorrows; uint256 deposit = mkts[asset].totalSupply; // uint256 _1 = 1 ether; return loan.mul(ONE_ETH).div(deposit); } //m:market, a:account //i(n,m)=i(n-1,m)*(1+rm*t) //return P*(i(n,m)/i(n-1,a)) // Calc the balance of the "t" token of "acc" account function getSupplyBalance(address acc, address t) public view returns (uint256) { Balance storage supplyBalance = accountSupplySnapshot[t][acc]; int256 mSupplyIndex = mkts[t].irm.pert( int256(mkts[t].supplyIndex), mkts[t].supplyRate, int256(now - mkts[t].accrualBlockNumber) ); uint256 userSupplyCurrent = uint256( mkts[t].irm.calculateBalance( valid_uint(supplyBalance.principal), int256(supplyBalance.interestIndex), mSupplyIndex ) ); return userSupplyCurrent; } // Calc the actual USD value of "t" token of "who" account function getSupplyBalanceInUSD(address who, address t) public view returns (uint256) { return getPriceForAssetAmount(t, getSupplyBalance(who, t)); } // Calc the profit of "t" token of "acc" account function getSupplyPnl(address acc, address t) public view returns (uint256) { Balance storage supplyBalance = accountSupplySnapshot[t][acc]; int256 mSupplyIndex = mkts[t].irm.pert( int256(mkts[t].supplyIndex), mkts[t].supplyRate, int256(now - mkts[t].accrualBlockNumber) ); uint256 userSupplyCurrent = uint256( mkts[t].irm.calculateBalance( valid_uint(supplyBalance.principal), int256(supplyBalance.interestIndex), mSupplyIndex ) ); if (userSupplyCurrent > supplyBalance.principal) { return supplyBalance.totalPnl.add( userSupplyCurrent.sub(supplyBalance.principal) ); } else { return supplyBalance.totalPnl; } } // Calc the profit of "t" token of "acc" account in USD value function getSupplyPnlInUSD(address who, address t) public view returns (uint256) { return getPriceForAssetAmount(t, getSupplyPnl(who, t)); } // Gets USD all token values of supply profit function getTotalSupplyPnl(address who) public view returns (uint256 sumPnl) { uint256 length = collateralTokens.length; for (uint256 i = 0; i < length; i++) { uint256 pnl = getSupplyPnlInUSD(who, collateralTokens[i]); sumPnl = sumPnl.add(pnl); } } //m:market, a:account //i(n,m)=i(n-1,m)*(1+rm*t) //return P*(i(n,m)/i(n-1,a)) function getBorrowBalance(address acc, address t) public view returns (uint256) { Balance storage borrowBalance = accountBorrowSnapshot[t][acc]; int256 mBorrowIndex = mkts[t].irm.pert( int256(mkts[t].borrowIndex), mkts[t].demondRate, int256(now - mkts[t].accrualBlockNumber) ); uint256 userBorrowCurrent = uint256( mkts[t].irm.calculateBalance( valid_uint(borrowBalance.principal), int256(borrowBalance.interestIndex), mBorrowIndex ) ); return userBorrowCurrent; } function getBorrowBalanceInUSD(address who, address t) public view returns (uint256) { return getPriceForAssetAmount(t, getBorrowBalance(who, t)); } function getBorrowPnl(address acc, address t) public view returns (uint256) { Balance storage borrowBalance = accountBorrowSnapshot[t][acc]; int256 mBorrowIndex = mkts[t].irm.pert( int256(mkts[t].borrowIndex), mkts[t].demondRate, int256(now - mkts[t].accrualBlockNumber) ); uint256 userBorrowCurrent = uint256( mkts[t].irm.calculateBalance( valid_uint(borrowBalance.principal), int256(borrowBalance.interestIndex), mBorrowIndex ) ); return borrowBalance.totalPnl.add(userBorrowCurrent).sub( borrowBalance.principal ); } function getBorrowPnlInUSD(address who, address t) public view returns (uint256) { return getPriceForAssetAmount(t, getBorrowPnl(who, t)); } // Gets USD all token values of borrow lose function getTotalBorrowPnl(address who) public view returns (uint256 sumPnl) { uint256 length = collateralTokens.length; // uint sumPnl = 0; for (uint256 i = 0; i < length; i++) { uint256 pnl = getBorrowPnlInUSD(who, collateralTokens[i]); sumPnl = sumPnl.add(pnl); } // return sumPnl; } // BorrowBalance * collateral ratio // collateral ratio always great than 1 function getBorrowBalanceLeverage(address who, address t) public view returns (uint256) { return getBorrowBalanceInUSD(who, t).mul(mkts[t].minPledgeRate).div( ONE_ETH ); } // Gets USD token values of supply and borrow balances function calcAccountTokenValuesInternal(address who, address t) public view returns (uint256, uint256) { return (getSupplyBalanceInUSD(who, t), getBorrowBalanceInUSD(who, t)); } // Gets USD token values of supply and borrow balances function calcAccountTokenValuesLeverageInternal(address who, address t) public view returns (uint256, uint256) { return ( getSupplyBalanceInUSD(who, t), getBorrowBalanceLeverage(who, t) ); } // Gets USD all token values of supply and borrow balances function calcAccountAllTokenValuesLeverageInternal(address who) public view returns (uint256 sumSupplies, uint256 sumBorrowLeverage) { uint256 length = collateralTokens.length; for (uint256 i = 0; i < length; i++) { ( uint256 supplyValue, uint256 borrowsLeverage ) = calcAccountTokenValuesLeverageInternal( who, collateralTokens[i] ); sumSupplies = sumSupplies.add(supplyValue); sumBorrowLeverage = sumBorrowLeverage.add(borrowsLeverage); } } function calcAccountLiquidity(address who) public view returns (uint256, uint256) { uint256 sumSupplies; uint256 sumBorrowsLeverage; //sumBorrows* collateral ratio ( sumSupplies, sumBorrowsLeverage ) = calcAccountAllTokenValuesLeverageInternal(who); if (sumSupplies < sumBorrowsLeverage) { return (0, sumBorrowsLeverage.sub(sumSupplies)); //不足 } else { return (sumSupplies.sub(sumBorrowsLeverage), 0); //有余 } } struct SupplyIR { uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newBorrowIndex; } // deposit function supplyPawn(address t, uint256 amount) external payable nonReentrant { uint256 supplyAmount = amount; // address(0) represents for eth if (t == address(0)) { require(amount == msg.value, "Eth value should be equal to amount"); supplyAmount = msg.value; } else { require(msg.value == 0, "Eth should not be provided"); } SupplyIR memory tmp; Market storage market = mkts[t]; Balance storage supplyBalance = accountSupplySnapshot[t][msg.sender]; uint256 lastTimestamp = market.accrualBlockNumber; uint256 blockDelta = now - lastTimestamp; // Calc the supplyIndex of supplyBalance tmp.newSupplyIndex = uint256( market.irm.pert( int256(market.supplyIndex), market.supplyRate, int256(blockDelta) ) ); tmp.userSupplyCurrent = uint256( market.irm.calculateBalance( valid_uint(accountSupplySnapshot[t][msg.sender].principal), int256(supplyBalance.interestIndex), int256(tmp.newSupplyIndex) ) ); tmp.userSupplyUpdated = tmp.userSupplyCurrent.add(supplyAmount); // Update supply of the market tmp.newTotalSupply = market.totalSupply.add(tmp.userSupplyUpdated).sub( supplyBalance.principal ); tmp.currentCash = getCash(t); // address(0) represents for eth // We support both ERC20 and ETH. // Calc the new Balance of the contract if it's ERC20 // else(ETH) does nothing because the cash has been added(msg.value) when the contract is called tmp.updatedCash = t != address(0) ? tmp.currentCash.add(supplyAmount) : tmp.currentCash; // Update supplyRate and demondRate market.supplyRate = market.irm.getDepositRate( valid_uint(tmp.updatedCash), valid_uint(market.totalBorrows) ); tmp.newBorrowIndex = uint256( market.irm.pert( int256(market.borrowIndex), market.demondRate, int256(blockDelta) ) ); market.demondRate = market.irm.getLoanRate( valid_uint(tmp.updatedCash), valid_uint(market.totalBorrows) ); market.borrowIndex = tmp.newBorrowIndex; market.supplyIndex = tmp.newSupplyIndex; market.totalSupply = tmp.newTotalSupply; market.accrualBlockNumber = now; // mkts[t] = market; tmp.startingBalance = supplyBalance.principal; supplyBalance.principal = tmp.userSupplyUpdated; supplyBalance.interestIndex = tmp.newSupplyIndex; // Update total profit of user if (tmp.userSupplyCurrent > tmp.startingBalance) { supplyBalance.totalPnl = supplyBalance.totalPnl.add( tmp.userSupplyCurrent.sub(tmp.startingBalance) ); } join(msg.sender); safeTransferFrom( t, msg.sender, address(this), address(this).makePayable(), supplyAmount, 0 ); emit SupplyPawnLog( msg.sender, t, supplyAmount, tmp.startingBalance, tmp.userSupplyUpdated ); } struct WithdrawIR { uint256 withdrawAmount; uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newBorrowIndex; uint256 accountLiquidity; uint256 accountShortfall; uint256 usdValueOfWithdrawal; uint256 withdrawCapacity; } // withdraw function withdrawPawn(address t, uint256 requestedAmount) external nonReentrant { Market storage market = mkts[t]; Balance storage supplyBalance = accountSupplySnapshot[t][msg.sender]; WithdrawIR memory tmp; uint256 lastTimestamp = mkts[t].accrualBlockNumber; uint256 blockDelta = now - lastTimestamp; // Judge if the user has ability to withdraw (tmp.accountLiquidity, tmp.accountShortfall) = calcAccountLiquidity( msg.sender ); require( tmp.accountLiquidity != 0 && tmp.accountShortfall == 0, "can't withdraw, shortfall" ); // Update the balance of the user tmp.newSupplyIndex = uint256( mkts[t].irm.pert( int256(mkts[t].supplyIndex), mkts[t].supplyRate, int256(blockDelta) ) ); tmp.userSupplyCurrent = uint256( mkts[t].irm.calculateBalance( valid_uint(supplyBalance.principal), int256(supplyBalance.interestIndex), int256(tmp.newSupplyIndex) ) ); // Get the balance of this contract tmp.currentCash = getCash(t); // uint(-1) represents the user want to withdraw all of his supplies of the "t" token if (requestedAmount == uint256(-1)) { // max withdraw amount = min(his account liquidity, his balance) tmp.withdrawCapacity = getAssetAmountForValue( t, tmp.accountLiquidity ); tmp.withdrawAmount = min( min(tmp.withdrawCapacity, tmp.userSupplyCurrent), tmp.currentCash ); // tmp.withdrawAmount = min(tmp.withdrawAmount, tmp.currentCash); } else { tmp.withdrawAmount = requestedAmount; } // Update balance of this contract tmp.updatedCash = tmp.currentCash.sub(tmp.withdrawAmount); tmp.userSupplyUpdated = tmp.userSupplyCurrent.sub(tmp.withdrawAmount); // Get the amount of token to withdraw tmp.usdValueOfWithdrawal = getPriceForAssetAmount( t, tmp.withdrawAmount ); // require account liquidity is enough require( tmp.usdValueOfWithdrawal <= tmp.accountLiquidity, "account is short" ); // Update totalSupply of the market tmp.newTotalSupply = market.totalSupply.add(tmp.userSupplyUpdated).sub( supplyBalance.principal ); tmp.newSupplyIndex = uint256( mkts[t].irm.pert( int256(mkts[t].supplyIndex), mkts[t].supplyRate, int256(blockDelta) ) ); // Update loan to deposit rate market.supplyRate = mkts[t].irm.getDepositRate( valid_uint(tmp.updatedCash), valid_uint(market.totalBorrows) ); tmp.newBorrowIndex = uint256( mkts[t].irm.pert( int256(mkts[t].borrowIndex), mkts[t].demondRate, int256(blockDelta) ) ); market.demondRate = mkts[t].irm.getLoanRate( valid_uint(tmp.updatedCash), valid_uint(market.totalBorrows) ); market.accrualBlockNumber = now; market.totalSupply = tmp.newTotalSupply; market.supplyIndex = tmp.newSupplyIndex; market.borrowIndex = tmp.newBorrowIndex; // mkts[t] = market; tmp.startingBalance = supplyBalance.principal; supplyBalance.principal = tmp.userSupplyUpdated; supplyBalance.interestIndex = tmp.newSupplyIndex; safeTransferFrom( t, address(this).makePayable(), address(this), msg.sender, tmp.withdrawAmount, 0 ); emit WithdrawPawnLog( msg.sender, t, tmp.withdrawAmount, tmp.startingBalance, tmp.userSupplyUpdated ); } struct PayBorrowIR { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 repayAmount; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 startingBalance; } function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a < b) { return a; } else { return b; } } //`(1 + originationFee) * borrowAmount` function calcBorrowAmountWithFee(uint256 borrowAmount) public pure returns (uint256) { return borrowAmount.mul((ONE_ETH).add(originationFee)).div(ONE_ETH); } // supply value * min pledge rate function getPriceForAssetAmountMulCollatRatio( address t, uint256 assetAmount ) public view returns (uint256) { return getPriceForAssetAmount(t, assetAmount) .mul(mkts[t].minPledgeRate) .div(ONE_ETH); } struct BorrowIR { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 borrowAmountWithFee; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 startingBalance; uint256 accountLiquidity; uint256 accountShortfall; uint256 usdValueOfBorrowAmountWithFee; } // borrow function BorrowPawn(address t, uint256 amount) external nonReentrant { BorrowIR memory tmp; Market storage market = mkts[t]; Balance storage borrowBalance = accountBorrowSnapshot[t][msg.sender]; uint256 lastTimestamp = mkts[t].accrualBlockNumber; uint256 blockDelta = now - lastTimestamp; // Calc borrow index tmp.newBorrowIndex = uint256( mkts[t].irm.pert( int256(mkts[t].borrowIndex), mkts[t].demondRate, int256(blockDelta) ) ); int256 lastIndex = int256(borrowBalance.interestIndex); tmp.userBorrowCurrent = uint256( mkts[t].irm.calculateBalance( valid_uint(borrowBalance.principal), lastIndex, int256(tmp.newBorrowIndex) ) ); // add borrow fee tmp.borrowAmountWithFee = calcBorrowAmountWithFee(amount); tmp.userBorrowUpdated = tmp.userBorrowCurrent.add( tmp.borrowAmountWithFee ); // Update market borrows tmp.newTotalBorrows = market .totalBorrows .add(tmp.userBorrowUpdated) .sub(borrowBalance.principal); // calc account liquidity (tmp.accountLiquidity, tmp.accountShortfall) = calcAccountLiquidity( msg.sender ); require( tmp.accountLiquidity != 0 && tmp.accountShortfall == 0, "can't borrow, shortfall" ); // require accountLiquitidy is enough tmp.usdValueOfBorrowAmountWithFee = getPriceForAssetAmountMulCollatRatio( t, tmp.borrowAmountWithFee ); require( tmp.usdValueOfBorrowAmountWithFee <= tmp.accountLiquidity, "can't borrow, without enough value" ); // Update the balance of this contract tmp.currentCash = getCash(t); tmp.updatedCash = tmp.currentCash.sub(amount); tmp.newSupplyIndex = uint256( mkts[t].irm.pert( int256(mkts[t].supplyIndex), mkts[t].supplyRate, int256(blockDelta) ) ); market.supplyRate = mkts[t].irm.getDepositRate( valid_uint(tmp.updatedCash), valid_uint(tmp.newTotalBorrows) ); market.demondRate = mkts[t].irm.getLoanRate( valid_uint(tmp.updatedCash), valid_uint(tmp.newTotalBorrows) ); market.accrualBlockNumber = now; market.totalBorrows = tmp.newTotalBorrows; market.supplyIndex = tmp.newSupplyIndex; market.borrowIndex = tmp.newBorrowIndex; // mkts[t] = market; tmp.startingBalance = borrowBalance.principal; borrowBalance.principal = tmp.userBorrowUpdated; borrowBalance.interestIndex = tmp.newBorrowIndex; // 更新币种的借币总额 // borrowBalance.totalPnl = borrowBalance.totalPnl.add(tmp.userBorrowCurrent.sub(tmp.startingBalance)); safeTransferFrom( t, address(this).makePayable(), address(this), msg.sender, amount, 0 ); emit BorrowPawnLog( msg.sender, t, amount, tmp.startingBalance, tmp.userBorrowUpdated ); // return 0; } // repay function repayFastBorrow(address t, uint256 amount) external payable nonReentrant { PayBorrowIR memory tmp; Market storage market = mkts[t]; Balance storage borrowBalance = accountBorrowSnapshot[t][msg.sender]; uint256 lastTimestamp = mkts[t].accrualBlockNumber; uint256 blockDelta = now - lastTimestamp; // calc the new borrow index tmp.newBorrowIndex = uint256( mkts[t].irm.pert( int256(mkts[t].borrowIndex), mkts[t].demondRate, int256(blockDelta) ) ); int256 lastIndex = int256(borrowBalance.interestIndex); tmp.userBorrowCurrent = uint256( mkts[t].irm.calculateBalance( valid_uint(borrowBalance.principal), lastIndex, int256(tmp.newBorrowIndex) ) ); // uint(-1) represents the user want to repay all of his borrows of "t" token if (amount == uint256(-1)) { // that is the minimum of (his balance, his borrows) tmp.repayAmount = min( getBalanceOf(t, msg.sender), tmp.userBorrowCurrent ); // address(0) represents for eth // if the user want to repay eth, he needs to repay a little more // because the exact amount will be calculated in the above // the extra eth will be returned in the safeTransferFrom if (t == address(0)) { require( msg.value > tmp.repayAmount, "Eth value should be larger than repayAmount" ); } } else { tmp.repayAmount = amount; if (t == address(0)) { require( msg.value == tmp.repayAmount, "Eth value should be equal to repayAmount" ); } } // calc the new borrows of user tmp.userBorrowUpdated = tmp.userBorrowCurrent.sub(tmp.repayAmount); // calc the new borrows of market tmp.newTotalBorrows = market .totalBorrows .add(tmp.userBorrowUpdated) .sub(borrowBalance.principal); tmp.currentCash = getCash(t); // address(0) represents for eth // just like the supplyPawn function, eth has been transfered. tmp.updatedCash = t != address(0) ? tmp.currentCash.add(tmp.repayAmount) : tmp.currentCash; tmp.newSupplyIndex = uint256( mkts[t].irm.pert( int256(mkts[t].supplyIndex), mkts[t].supplyRate, int256(blockDelta) ) ); // update deposit and loan rate market.supplyRate = mkts[t].irm.getDepositRate( valid_uint(tmp.updatedCash), valid_uint(tmp.newTotalBorrows) ); market.demondRate = mkts[t].irm.getLoanRate( valid_uint(tmp.updatedCash), valid_uint(tmp.newTotalBorrows) ); market.accrualBlockNumber = now; market.totalBorrows = tmp.newTotalBorrows; market.supplyIndex = tmp.newSupplyIndex; market.borrowIndex = tmp.newBorrowIndex; // mkts[t] = market; tmp.startingBalance = borrowBalance.principal; borrowBalance.principal = tmp.userBorrowUpdated; borrowBalance.interestIndex = tmp.newBorrowIndex; safeTransferFrom( t, msg.sender, address(this), address(this).makePayable(), tmp.repayAmount, msg.value ); emit RepayFastBorrowLog( msg.sender, t, tmp.repayAmount, tmp.startingBalance, tmp.userBorrowUpdated ); } // shortfall/(price*(minPledgeRate-liquidationDiscount-1)) // underwaterAsset is borrowAsset function calcDiscountedRepayToEvenAmount( address targetAccount, address underwaterAsset, uint256 underwaterAssetPrice ) public view returns (uint256) { (, uint256 shortfall) = calcAccountLiquidity(targetAccount); uint256 minPledgeRate = mkts[underwaterAsset].minPledgeRate; uint256 liquidationDiscount = mkts[underwaterAsset].liquidationDiscount; uint256 gap = minPledgeRate.sub(liquidationDiscount).sub(1 ether); return shortfall.mul(10**mkts[underwaterAsset].decimals).div( underwaterAssetPrice.mul(gap).div(ONE_ETH) ); //underwater asset amount } //[supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) //[supplyCurrent * (Oracle price for the collateral)] / [ (1 + liquidationDiscount) * (Oracle price for the borrow) ] // amount of underwaterAsset to be repayed by liquidator, calculated by the amount of collateral asset function calcDiscountedBorrowDenominatedCollateral( address underwaterAsset, address collateralAsset, uint256 underwaterAssetPrice, uint256 collateralPrice, uint256 supplyCurrent_TargetCollateralAsset ) public view returns (uint256 res) { uint256 liquidationDiscount = mkts[underwaterAsset].liquidationDiscount; uint256 onePlusLiquidationDiscount = (ONE_ETH).add(liquidationDiscount); uint256 supplyCurrentTimesOracleCollateral = supplyCurrent_TargetCollateralAsset.mul(collateralPrice); res = supplyCurrentTimesOracleCollateral.div( onePlusLiquidationDiscount.mul(underwaterAssetPrice).div(ONE_ETH) ); //underwaterAsset amout res = res.mul(10**mkts[underwaterAsset].decimals); res = res.div(10**mkts[collateralAsset].decimals); } //closeBorrowAmount_TargetUnderwaterAsset * (1+liquidationDiscount) * priceBorrow/priceCollateral //underwaterAssetPrice * (1+liquidationDiscount) *closeBorrowAmount_TargetUnderwaterAsset) / collateralPrice //underwater is borrow // calc the amount of collateral asset bought by underwaterAsset(amount: closeBorrowAmount_TargetUnderwaterAsset) function calcAmountSeize( address underwaterAsset, address collateralAsset, uint256 underwaterAssetPrice, uint256 collateralPrice, uint256 closeBorrowAmount_TargetUnderwaterAsset ) public view returns (uint256 res) { uint256 liquidationDiscount = mkts[underwaterAsset].liquidationDiscount; uint256 onePlusLiquidationDiscount = (ONE_ETH).add(liquidationDiscount); res = underwaterAssetPrice.mul(onePlusLiquidationDiscount); res = res.mul(closeBorrowAmount_TargetUnderwaterAsset); res = res.div(collateralPrice); res = res.div(ONE_ETH); res = res.mul(10**mkts[collateralAsset].decimals); res = res.div(10**mkts[underwaterAsset].decimals); } struct LiquidateIR { // we need these addresses in the struct for use with `emitLiquidationEvent` to avoid `CompilerError: Stack too deep, try removing local variables.` address targetAccount; address assetBorrow; address liquidator; address assetCollateral; // borrow index and supply index are global to the asset, not specific to the user uint256 newBorrowIndex_UnderwaterAsset; uint256 newSupplyIndex_UnderwaterAsset; uint256 newBorrowIndex_CollateralAsset; uint256 newSupplyIndex_CollateralAsset; // the target borrow's full balance with accumulated interest uint256 currentBorrowBalance_TargetUnderwaterAsset; // currentBorrowBalance_TargetUnderwaterAsset minus whatever gets repaid as part of the liquidation uint256 updatedBorrowBalance_TargetUnderwaterAsset; uint256 newTotalBorrows_ProtocolUnderwaterAsset; uint256 startingBorrowBalance_TargetUnderwaterAsset; uint256 startingSupplyBalance_TargetCollateralAsset; uint256 startingSupplyBalance_LiquidatorCollateralAsset; uint256 currentSupplyBalance_TargetCollateralAsset; uint256 updatedSupplyBalance_TargetCollateralAsset; // If liquidator already has a balance of collateralAsset, we will accumulate // interest on it before transferring seized collateral from the borrower. uint256 currentSupplyBalance_LiquidatorCollateralAsset; // This will be the liquidator's accumulated balance of collateral asset before the liquidation (if any) // plus the amount seized from the borrower. uint256 updatedSupplyBalance_LiquidatorCollateralAsset; uint256 newTotalSupply_ProtocolCollateralAsset; uint256 currentCash_ProtocolUnderwaterAsset; uint256 updatedCash_ProtocolUnderwaterAsset; // cash does not change for collateral asset //mkts[t] uint256 newSupplyRateMantissa_ProtocolUnderwaterAsset; uint256 newBorrowRateMantissa_ProtocolUnderwaterAsset; // Why no variables for the interest rates for the collateral asset? // We don't need to calculate new rates for the collateral asset since neither cash nor borrows change uint256 discountedRepayToEvenAmount; //[supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (discountedBorrowDenominatedCollateral) uint256 discountedBorrowDenominatedCollateral; uint256 maxCloseableBorrowAmount_TargetUnderwaterAsset; uint256 closeBorrowAmount_TargetUnderwaterAsset; uint256 seizeSupplyAmount_TargetCollateralAsset; uint256 collateralPrice; uint256 underwaterAssetPrice; } // get the max amount to be liquidated function calcMaxLiquidateAmount( address targetAccount, address assetBorrow, address assetCollateral ) external view returns (uint256) { require(msg.sender != targetAccount, "can't self-liquidate"); LiquidateIR memory tmp; uint256 blockDelta = now - mkts[assetBorrow].accrualBlockNumber; Market storage borrowMarket = mkts[assetBorrow]; Market storage collateralMarket = mkts[assetCollateral]; Balance storage borrowBalance_TargeUnderwaterAsset = accountBorrowSnapshot[assetBorrow][targetAccount]; Balance storage supplyBalance_TargetCollateralAsset = accountSupplySnapshot[assetCollateral][targetAccount]; tmp.newSupplyIndex_CollateralAsset = uint256( collateralMarket.irm.pert( int256(collateralMarket.supplyIndex), collateralMarket.supplyRate, int256(blockDelta) ) ); tmp.newBorrowIndex_UnderwaterAsset = uint256( borrowMarket.irm.pert( int256(borrowMarket.borrowIndex), borrowMarket.demondRate, int256(blockDelta) ) ); tmp.currentSupplyBalance_TargetCollateralAsset = uint256( collateralMarket.irm.calculateBalance( valid_uint(supplyBalance_TargetCollateralAsset.principal), int256(supplyBalance_TargetCollateralAsset.interestIndex), int256(tmp.newSupplyIndex_CollateralAsset) ) ); tmp.currentBorrowBalance_TargetUnderwaterAsset = uint256( borrowMarket.irm.calculateBalance( valid_uint(borrowBalance_TargeUnderwaterAsset.principal), int256(borrowBalance_TargeUnderwaterAsset.interestIndex), int256(tmp.newBorrowIndex_UnderwaterAsset) ) ); bool ok; (tmp.collateralPrice, ok) = fetchAssetPrice(assetCollateral); require(ok, "fail to get collateralPrice"); (tmp.underwaterAssetPrice, ok) = fetchAssetPrice(assetBorrow); require(ok, "fail to get underwaterAssetPrice"); tmp.discountedBorrowDenominatedCollateral = calcDiscountedBorrowDenominatedCollateral( assetBorrow, assetCollateral, tmp.underwaterAssetPrice, tmp.collateralPrice, tmp.currentSupplyBalance_TargetCollateralAsset ); tmp.discountedRepayToEvenAmount = calcDiscountedRepayToEvenAmount( targetAccount, assetBorrow, tmp.underwaterAssetPrice ); tmp.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( tmp.currentBorrowBalance_TargetUnderwaterAsset, tmp.discountedBorrowDenominatedCollateral ); tmp.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( tmp.maxCloseableBorrowAmount_TargetUnderwaterAsset, tmp.discountedRepayToEvenAmount ); return tmp.maxCloseableBorrowAmount_TargetUnderwaterAsset; } // liquidate function liquidateBorrowPawn( address targetAccount, address assetBorrow, address assetCollateral, uint256 requestedAmountClose ) external payable nonReentrant { require(msg.sender != targetAccount, "can't self-liquidate"); LiquidateIR memory tmp; // Copy these addresses into the struct for use with `emitLiquidationEvent` // We'll use tmp.liquidator inside this function for clarity vs using msg.sender. tmp.targetAccount = targetAccount; tmp.assetBorrow = assetBorrow; tmp.liquidator = msg.sender; tmp.assetCollateral = assetCollateral; uint256 blockDelta = now - mkts[assetBorrow].accrualBlockNumber; Market storage borrowMarket = mkts[assetBorrow]; Market storage collateralMarket = mkts[assetCollateral]; // borrower's borrow balance and supply balance Balance storage borrowBalance_TargeUnderwaterAsset = accountBorrowSnapshot[assetBorrow][targetAccount]; Balance storage supplyBalance_TargetCollateralAsset = accountSupplySnapshot[assetCollateral][targetAccount]; // Liquidator might already hold some of the collateral asset Balance storage supplyBalance_LiquidatorCollateralAsset = accountSupplySnapshot[assetCollateral][tmp.liquidator]; bool ok; (tmp.collateralPrice, ok) = fetchAssetPrice(assetCollateral); require(ok, "fail to get collateralPrice"); (tmp.underwaterAssetPrice, ok) = fetchAssetPrice(assetBorrow); require(ok, "fail to get underwaterAssetPrice"); // calc borrower's borrow balance with the newest interest tmp.newBorrowIndex_UnderwaterAsset = uint256( borrowMarket.irm.pert( int256(borrowMarket.borrowIndex), borrowMarket.demondRate, int256(blockDelta) ) ); tmp.currentBorrowBalance_TargetUnderwaterAsset = uint256( borrowMarket.irm.calculateBalance( valid_uint(borrowBalance_TargeUnderwaterAsset.principal), int256(borrowBalance_TargeUnderwaterAsset.interestIndex), int256(tmp.newBorrowIndex_UnderwaterAsset) ) ); // calc borrower's supply balance with the newest interest tmp.newSupplyIndex_CollateralAsset = uint256( collateralMarket.irm.pert( int256(collateralMarket.supplyIndex), collateralMarket.supplyRate, int256(blockDelta) ) ); tmp.currentSupplyBalance_TargetCollateralAsset = uint256( collateralMarket.irm.calculateBalance( valid_uint(supplyBalance_TargetCollateralAsset.principal), int256(supplyBalance_TargetCollateralAsset.interestIndex), int256(tmp.newSupplyIndex_CollateralAsset) ) ); // calc liquidator's balance of the collateral asset tmp.currentSupplyBalance_LiquidatorCollateralAsset = uint256( collateralMarket.irm.calculateBalance( valid_uint(supplyBalance_LiquidatorCollateralAsset.principal), int256(supplyBalance_LiquidatorCollateralAsset.interestIndex), int256(tmp.newSupplyIndex_CollateralAsset) ) ); // update collateral asset of the market tmp.newTotalSupply_ProtocolCollateralAsset = collateralMarket .totalSupply .add(tmp.currentSupplyBalance_TargetCollateralAsset) .sub(supplyBalance_TargetCollateralAsset.principal); tmp.newTotalSupply_ProtocolCollateralAsset = tmp .newTotalSupply_ProtocolCollateralAsset .add(tmp.currentSupplyBalance_LiquidatorCollateralAsset) .sub(supplyBalance_LiquidatorCollateralAsset.principal); // calc the max amount to be liquidated tmp.discountedBorrowDenominatedCollateral = calcDiscountedBorrowDenominatedCollateral( assetBorrow, assetCollateral, tmp.underwaterAssetPrice, tmp.collateralPrice, tmp.currentSupplyBalance_TargetCollateralAsset ); tmp.discountedRepayToEvenAmount = calcDiscountedRepayToEvenAmount( targetAccount, assetBorrow, tmp.underwaterAssetPrice ); tmp.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( min( tmp.currentBorrowBalance_TargetUnderwaterAsset, tmp.discountedBorrowDenominatedCollateral ), tmp.discountedRepayToEvenAmount ); // uint(-1) represents the user want to liquidate all if (requestedAmountClose == uint256(-1)) { tmp.closeBorrowAmount_TargetUnderwaterAsset = tmp .maxCloseableBorrowAmount_TargetUnderwaterAsset; } else { tmp.closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } require( tmp.closeBorrowAmount_TargetUnderwaterAsset <= tmp.maxCloseableBorrowAmount_TargetUnderwaterAsset, "closeBorrowAmount > maxCloseableBorrowAmount err" ); // address(0) represents for eth if (assetBorrow == address(0)) { // just the repay method, eth amount be transfered should be a litte more require( msg.value >= tmp.closeBorrowAmount_TargetUnderwaterAsset, "Not enough ETH" ); } else { // user needs to have enough balance require( getBalanceOf(assetBorrow, tmp.liquidator) >= tmp.closeBorrowAmount_TargetUnderwaterAsset, "insufficient balance" ); } // 计算清算人实际清算得到的此质押币数量 // The amount of collateral asset that liquidator can get tmp.seizeSupplyAmount_TargetCollateralAsset = calcAmountSeize( assetBorrow, assetCollateral, tmp.underwaterAssetPrice, tmp.collateralPrice, tmp.closeBorrowAmount_TargetUnderwaterAsset ); // 被清算人借币余额减少 // Update borrower's balance tmp.updatedBorrowBalance_TargetUnderwaterAsset = tmp .currentBorrowBalance_TargetUnderwaterAsset .sub(tmp.closeBorrowAmount_TargetUnderwaterAsset); // 更新借币市场总量 // Update borrow market tmp.newTotalBorrows_ProtocolUnderwaterAsset = borrowMarket .totalBorrows .add(tmp.updatedBorrowBalance_TargetUnderwaterAsset) .sub(borrowBalance_TargeUnderwaterAsset.principal); tmp.currentCash_ProtocolUnderwaterAsset = getCash(assetBorrow); // address(0) represents for eth // eth has been transfered when called tmp.updatedCash_ProtocolUnderwaterAsset = assetBorrow != address(0) ? tmp.currentCash_ProtocolUnderwaterAsset.add( tmp.closeBorrowAmount_TargetUnderwaterAsset ) : tmp.currentCash_ProtocolUnderwaterAsset; tmp.newSupplyIndex_UnderwaterAsset = uint256( borrowMarket.irm.pert( int256(borrowMarket.supplyIndex), borrowMarket.demondRate, int256(blockDelta) ) ); borrowMarket.supplyRate = borrowMarket.irm.getDepositRate( int256(tmp.updatedCash_ProtocolUnderwaterAsset), int256(tmp.newTotalBorrows_ProtocolUnderwaterAsset) ); borrowMarket.demondRate = borrowMarket.irm.getLoanRate( int256(tmp.updatedCash_ProtocolUnderwaterAsset), int256(tmp.newTotalBorrows_ProtocolUnderwaterAsset) ); tmp.newBorrowIndex_CollateralAsset = uint256( collateralMarket.irm.pert( int256(collateralMarket.supplyIndex), collateralMarket.demondRate, int256(blockDelta) ) ); // Update the balance of liquidator and borrower tmp.updatedSupplyBalance_TargetCollateralAsset = tmp .currentSupplyBalance_TargetCollateralAsset .sub(tmp.seizeSupplyAmount_TargetCollateralAsset); tmp.updatedSupplyBalance_LiquidatorCollateralAsset = tmp .currentSupplyBalance_LiquidatorCollateralAsset .add(tmp.seizeSupplyAmount_TargetCollateralAsset); borrowMarket.accrualBlockNumber = now; borrowMarket.totalBorrows = tmp.newTotalBorrows_ProtocolUnderwaterAsset; borrowMarket.supplyIndex = tmp.newSupplyIndex_UnderwaterAsset; borrowMarket.borrowIndex = tmp.newBorrowIndex_UnderwaterAsset; // mkts[assetBorrow] = borrowMarket; collateralMarket.accrualBlockNumber = now; collateralMarket.totalSupply = tmp .newTotalSupply_ProtocolCollateralAsset; collateralMarket.supplyIndex = tmp.newSupplyIndex_CollateralAsset; collateralMarket.borrowIndex = tmp.newBorrowIndex_CollateralAsset; // mkts[assetCollateral] = collateralMarket; tmp.startingBorrowBalance_TargetUnderwaterAsset = borrowBalance_TargeUnderwaterAsset .principal; // save for use in event borrowBalance_TargeUnderwaterAsset.principal = tmp .updatedBorrowBalance_TargetUnderwaterAsset; borrowBalance_TargeUnderwaterAsset.interestIndex = tmp .newBorrowIndex_UnderwaterAsset; tmp.startingSupplyBalance_TargetCollateralAsset = supplyBalance_TargetCollateralAsset .principal; // save for use in event supplyBalance_TargetCollateralAsset.principal = tmp .updatedSupplyBalance_TargetCollateralAsset; supplyBalance_TargetCollateralAsset.interestIndex = tmp .newSupplyIndex_CollateralAsset; tmp.startingSupplyBalance_LiquidatorCollateralAsset = supplyBalance_LiquidatorCollateralAsset .principal; // save for use in event supplyBalance_LiquidatorCollateralAsset.principal = tmp .updatedSupplyBalance_LiquidatorCollateralAsset; supplyBalance_LiquidatorCollateralAsset.interestIndex = tmp .newSupplyIndex_CollateralAsset; setLiquidateInfoMap( tmp.targetAccount, tmp.liquidator, tmp.assetCollateral, assetBorrow, tmp.seizeSupplyAmount_TargetCollateralAsset, tmp.closeBorrowAmount_TargetUnderwaterAsset ); safeTransferFrom( assetBorrow, tmp.liquidator.makePayable(), address(this), address(this).makePayable(), tmp.closeBorrowAmount_TargetUnderwaterAsset, msg.value ); emit LiquidateBorrowPawnLog( tmp.targetAccount, assetBorrow, tmp.updatedBorrowBalance_TargetUnderwaterAsset, tmp.liquidator, tmp.assetCollateral, tmp.updatedSupplyBalance_TargetCollateralAsset ); } function safeTransferFrom( address token, address payable owner, address spender, address payable to, uint256 amount, uint256 msgValue ) internal { require(amount != 0, "invalid safeTransferFrom amount"); if (owner != spender && token != address(0)) { // transfer in ERC20 require( IERC20(token).allowance(owner, spender) >= amount, "Insufficient allowance" ); } if (token != address(0)) { require( IERC20(token).balanceOf(owner) >= amount, "Insufficient balance" ); } else if (owner == spender) { // eth, owner == spender represents for transfer out, requires enough balance require(owner.balance >= amount, "Insufficient eth balance"); } if (owner != spender) { // transfer in if (token != address(0)) { // transferFrom ERC20 IERC20(token).safeTransferFrom(owner, to, amount); } else if (msgValue != 0 && msgValue > amount) { // return the extra eth to user owner.transfer(msgValue.sub(amount)); } // eth has been transfered when called using msg.value } else { // transfer out if (token != address(0)) { // ERC20 IERC20(token).safeTransfer(to, amount); } else { // 参数设置, msgValue 大于0,即还款或清算逻辑,实际还的钱大于需要还的钱,需要返回多余的钱 // msgValue 等于 0,借钱或取钱逻辑,直接转出 amount 数量的币 // msgValue greater than 0 represents for repay or liquidate, // which means we should give back the extra eth to user // msgValue equals to 0 represents for withdraw or borrow // just take the wanted money if (msgValue != 0 && msgValue > amount) { to.transfer(msgValue.sub(amount)); } else { to.transfer(amount); } } } } // admin transfers profit out function withdrawPawnEquity(address t, uint256 amount) external nonReentrant onlyAdmin { uint256 cash = getCash(t); uint256 equity = cash.add(mkts[t].totalBorrows).sub( mkts[t].totalSupply ); require(equity >= amount, "insufficient equity amount"); safeTransferFrom( t, address(this).makePayable(), address(this), admin.makePayable(), amount, 0 ); emit WithdrawPawnEquityLog(t, equity, amount, admin); } }
tokenContract->address(usr)->SupplySnapshot
public accountSupplySnapshot;
13,067,280
[ 1, 2316, 8924, 2122, 2867, 12, 13640, 13, 2122, 3088, 1283, 4568, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1071, 2236, 3088, 1283, 4568, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.8; library SafeMath { function MUL38(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 DIV634(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 SUB406(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } function ADD700(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } } contract Ownable { address private _owner; event OWNERSHIPTRANSFERRED30(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = 0xfc0281163cFeDA9FbB3B18A72A27310B1725fD65; emit OWNERSHIPTRANSFERRED30(address(0), _owner); } function OWNER975() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER510() { //inject NONSTANDARD NAMING require(ISOWNER350(), "Ownable: caller is not the owner"); _; } function ISOWNER350() public view returns (bool) { //inject NONSTANDARD NAMING return msg.sender == _owner; } function RENOUNCEOWNERSHIP332() public ONLYOWNER510 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED30(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP193(address newOwner) public ONLYOWNER510 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP229(newOwner); } function _TRANSFEROWNERSHIP229(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED30(_owner, newOwner); _owner = newOwner; } } interface IERC20 { function TRANSFER697(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function APPROVE20(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM431(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TOTALSUPPLY947() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF859(address who) external view returns (uint256); //inject NONSTANDARD NAMING function ALLOWANCE181(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING event TRANSFER948(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL469(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; function TOTALSUPPLY947() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF859(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[owner]; } function ALLOWANCE181(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function TRANSFER697(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER167(msg.sender, to, value); return true; } function APPROVE20(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE409(msg.sender, spender, value); return true; } function TRANSFERFROM431(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER167(from, to, value); _APPROVE409(from, msg.sender, _allowances[from][msg.sender].SUB406(value)); return true; } function INCREASEALLOWANCE260(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE409(msg.sender, spender, _allowances[msg.sender][spender].ADD700(addedValue)); return true; } function DECREASEALLOWANCE155(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE409(msg.sender, spender, _allowances[msg.sender][spender].SUB406(subtractedValue)); return true; } function _TRANSFER167(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _balances[from] = _balances[from].SUB406(value); _balances[to] = _balances[to].ADD700(value); emit TRANSFER948(from, to, value); } function _MINT833(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.ADD700(value); _balances[account] = _balances[account].ADD700(value); emit TRANSFER948(address(0), account, value); } function _APPROVE409(address owner, address spender, uint256 value) 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] = value; emit APPROVAL469(owner, spender, value); } } contract CSCToken is ERC20, Ownable { using SafeMath for uint256; string public constant name863 = "Crypto Service Capital Token"; //inject NONSTANDARD NAMING string public constant symbol721 = "CSCT"; //inject NONSTANDARD NAMING uint8 public constant decimals85 = 18; //inject NONSTANDARD NAMING bool public mintingFinished = false; mapping (address => bool) private _minters; event MINT126(address indexed to, uint256 amount); //inject NONSTANDARD NAMING event MINTFINISHED370(); //inject NONSTANDARD NAMING modifier CANMINT211() { //inject NONSTANDARD NAMING require(!mintingFinished); _; } function ISMINTER256(address minter) public view returns (bool) { //inject NONSTANDARD NAMING if (OWNER975() == minter) { return true; } return _minters[minter]; } modifier ONLYMINTER211() { //inject NONSTANDARD NAMING require(ISMINTER256(msg.sender), "Minter: caller is not the minter"); _; } function ADDMINTER63(address _minter) external ONLYOWNER510 returns (bool) { //inject NONSTANDARD NAMING require(_minter != address(0)); _minters[_minter] = true; return true; } function REMOVEMINTER886(address _minter) external ONLYOWNER510 returns (bool) { //inject NONSTANDARD NAMING require(_minter != address(0)); _minters[_minter] = false; return true; } function MINT259(address to, uint256 value) public ONLYMINTER211 returns (bool) { //inject NONSTANDARD NAMING _MINT833(to, value); emit MINT126(to, value); return true; } function FINISHMINTING196() ONLYOWNER510 CANMINT211 external returns (bool) { //inject NONSTANDARD NAMING mintingFinished = true; emit MINTFINISHED370(); return true; } } contract Crowdsale is Ownable { using SafeMath for uint256; uint256 public constant rate431 = 1000; // How many token units a buyer gets per wei //inject NONSTANDARD NAMING uint256 public constant cap376 = 10000 ether; // Maximum amount of funds //inject NONSTANDARD NAMING bool public isFinalized = false; // End timestamps where investments are allowed uint256 public startTime = 1559347199; // 31-May-19 23:59:59 UTC uint256 public endTime = 1577836799; // 30-Dec-19 23:59:59 UTC CSCToken public token; // CSCT token itself address payable public wallet = 0x1524Aa69ef4BA327576FcF548f7dD14aEaC8CA18; // Wallet of funds uint256 public weiRaised; // Amount of raised money in wei uint256 public firstBonus = 30; // 1st bonus percentage uint256 public secondBonus = 50; // 2nd bonus percentage event TOKENPURCHASE96(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); //inject NONSTANDARD NAMING event FINALIZED531(); //inject NONSTANDARD NAMING constructor (CSCToken _CSCT) public { assert(address(_CSCT) != address(0)); token = _CSCT; } function () external payable { BUYTOKENS779(msg.sender); } // @return true if the transaction can buy tokens function VALIDPURCHASE868() internal view returns (bool) { //inject NONSTANDARD NAMING require(!token.mintingFinished()); require(weiRaised <= cap376); require(now >= startTime); require(now <= endTime); require(msg.value >= 0.001 ether); return true; } function TOKENSFORWEI360(uint weiAmount) public view returns (uint tokens) { //inject NONSTANDARD NAMING tokens = weiAmount.MUL38(rate431); tokens = tokens.ADD700(GETBONUS366(tokens, weiAmount)); } function GETBONUS366(uint256 _tokens, uint256 _weiAmount) public view returns (uint256) { //inject NONSTANDARD NAMING if (_weiAmount >= 30 ether) { return _tokens.MUL38(secondBonus).DIV634(100); } return _tokens.MUL38(firstBonus).DIV634(100); } function BUYTOKENS779(address beneficiary) public payable { //inject NONSTANDARD NAMING require(beneficiary != address(0)); require(VALIDPURCHASE868()); uint256 weiAmount = msg.value; uint256 tokens = TOKENSFORWEI360(weiAmount); weiRaised = weiRaised.ADD700(weiAmount); token.MINT259(beneficiary, tokens); emit TOKENPURCHASE96(msg.sender, beneficiary, weiAmount, tokens); wallet.transfer(msg.value); } function SETFIRSTBONUS839(uint256 _newBonus) ONLYOWNER510 external { //inject NONSTANDARD NAMING firstBonus = _newBonus; } function SETSECONDBONUS714(uint256 _newBonus) ONLYOWNER510 external { //inject NONSTANDARD NAMING secondBonus = _newBonus; } function CHANGEENDTIME347(uint256 _newTime) ONLYOWNER510 external { //inject NONSTANDARD NAMING require(endTime >= now); endTime = _newTime; } // Calls the contract's finalization function. function FINALIZE617() ONLYOWNER510 external { //inject NONSTANDARD NAMING require(!isFinalized); endTime = now; isFinalized = true; emit FINALIZED531(); } // @return true if crowdsale event has ended function HASENDED686() external view returns (bool) { //inject NONSTANDARD NAMING return now > endTime; } }
inject NONSTANDARD NAMING
modifier ONLYMINTER211() {
14,049,166
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 20747, 6236, 2560, 22, 2499, 1435, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/extensions/ERC1155BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/extensions/ERC1155SupplyUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; //TODO write events //TODO write upgrade logic //TODO optimize for gas //TODO follow users and favorite videos //TODO list top users //TODO save video market value /// @custom:security-contact [email protected] contract YouCollector is Initializable, ERC1155Upgradeable, AccessControlUpgradeable, PausableUpgradeable, ERC1155BurnableUpgradeable, ERC1155SupplyUpgradeable { bytes32 public constant URI_SETTER_ROLE = keccak256("URI_SETTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); uint256 public constant DAY = 24 * 60 * 60; uint256 public constant VIDEO_ID_ID = 0; uint256 public constant COLLECTION_ID = 1; uint256 public constant SLOT_ID = 2; uint256 public constant MARKETPLACE_ITEM_ID = 2; uint256 public constant SORT_CREATED_ASC = 0; uint256 public constant SORT_CREATED_DESC = 1; uint256 public constant SORT_PRICE_ASC = 2; uint256 public constant SORT_PRICE_DESC = 3; address payable private creatorAddress; uint256 public videoIdMintingPrice = 0; uint256 public collectionMintingPrice = 1 * 10**18; uint256 public slotMintingPrice = 0.333 * 10**18; uint256 public marketplaceItemMintingPrice = 0; uint256 public videoIdTransferPlatformFeeRatio = 5; // 5% // TODO setter uint256 public videoIdTransferAuthorFeeRatio = 5; // 5% // TODO figure it out, setter uint256 public marketplaceItemMinimumBidTime = 1 * DAY; uint256 public marketplaceItemPagination = 4 * 12; struct Collection { uint256 id; string name; uint256 slots; string[] videoIds; } uint256 private _currentCollectionId = 0; // id generator uint256 public newCollectionSlots = 8; string public newCollectionName = "My Collection"; struct MarketplaceItem { string videoId; address payable owner; address payable bidder; uint256 price; // Direct buy price uint256 bid; // 0 if no bidding allowed uint256 bidCount; uint256 bidDate; // 0 if no bidder uint256 startDate; // 0 if direct buy uint256 endDate; // 0 if direct buy } mapping (address => uint256) public userToRegistrationDate; mapping (address => Collection[]) public ownerToCollections; mapping (string => address) public videoIdToOwner; mapping (string => address) public videoIdToAuthor; mapping (string => uint256) public videoIdToCollectionId; MarketplaceItem[] public marketplaceItemsByDate; MarketplaceItem[] public marketplaceItemsByPrice; mapping (string => MarketplaceItem) public videoIdToMarketplaceItem; /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} function initialize() initializer public { __ERC1155_init("https://youcollector.art/metadatas/{id}.json"); __AccessControl_init(); __Pausable_init(); __ERC1155Burnable_init(); __ERC1155Supply_init(); _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); _grantRole(URI_SETTER_ROLE, msg.sender); _grantRole(PAUSER_ROLE, msg.sender); creatorAddress = payable(msg.sender); } /* --- GETTERS --- */ function getVideoIdInfo(string memory videoId) public view returns (address owner, address author, uint256 collectionId, string memory collectionName, MarketplaceItem memory marketplaceItem) { require(bytes(videoId).length > 0, "videoId is empty!"); require(videoIdToOwner[videoId] != address(0x0), "videoId does not exist!"); owner = videoIdToOwner[videoId]; author = videoIdToAuthor[videoId]; collectionId = videoIdToCollectionId[videoId]; collectionName = ownerToCollections[owner][collectionId].name; marketplaceItem = videoIdToMarketplaceItem[videoId]; } function getCollections(address owner) public view returns (Collection[] memory collections) { collections = ownerToCollections[owner]; } function getMarketplaceItems(uint256 skip, uint256 sort) public view returns (MarketplaceItem[] memory marketplaceItems) { marketplaceItems = new MarketplaceItem[](marketplaceItemPagination); uint256 passCount = 0; if (sort == SORT_CREATED_DESC) { // TODO optimize with variable for (uint256 i = marketplaceItemsByDate.length - skip - 1; i >= marketplaceItemsByDate.length - skip - marketplaceItemPagination - passCount - 1; i--) { if (marketplaceItemsByDate[i].endDate > block.timestamp) { passCount++; continue; } marketplaceItems[marketplaceItemPagination - i + passCount] = marketplaceItemsByDate[i]; } return marketplaceItems; } else if (sort == SORT_CREATED_DESC) { for (uint256 i = skip; i < marketplaceItemPagination + passCount; i++) { if (marketplaceItemsByDate[i].endDate > block.timestamp) { passCount++; continue; } marketplaceItems[i - passCount] = marketplaceItemsByDate[i]; } return marketplaceItems; } // else if (sort == SORT_PRICE_ASC) { // return marketplaceItems; // } // else if (sort == SORT_PRICE_DESC) { // return marketplaceItems; // } else { revert("Invalid sort!"); } } /* --- SETTERS --- */ function setVideoIdMintingPrice(uint256 newPrice) public onlyRole(DEFAULT_ADMIN_ROLE) { videoIdMintingPrice = newPrice; } function setCollectionMintingPrice(uint256 newPrice) public onlyRole(DEFAULT_ADMIN_ROLE) { collectionMintingPrice = newPrice; } function setSlotMintingPrice(uint256 newPrice) public onlyRole(DEFAULT_ADMIN_ROLE) { slotMintingPrice = newPrice; } function setNewCollectionSlots(uint256 newSlots) public onlyRole(DEFAULT_ADMIN_ROLE) { newCollectionSlots = newSlots; } function setMarketplaceItemMintingPrice(uint256 newMarketplaceItemMintingPrice) public onlyRole(DEFAULT_ADMIN_ROLE) { marketplaceItemMintingPrice = newMarketplaceItemMintingPrice; } function setMarketplaceItemMinimumBidTime(uint256 newMarketplaceItemMinimumBidTime) public onlyRole(DEFAULT_ADMIN_ROLE) { marketplaceItemMinimumBidTime = newMarketplaceItemMinimumBidTime; } function setMarketplaceItemPagination(uint256 newMarketplaceItemPagination) public onlyRole(DEFAULT_ADMIN_ROLE) { marketplaceItemPagination = newMarketplaceItemPagination; } /* --- REGISTRATION --- */ function registerNewUser(string[] memory videoIds) public payable returns (uint256) { require(userToRegistrationDate[msg.sender] == 0, "User already registered"); require(videoIds.length <= newCollectionSlots, "To many videoIds to mint!"); for (uint256 i = 0; i < videoIds.length; i++) { require(bytes(videoIds[i]).length > 0, "videoIds contains an empty string"); } uint256 collectionId = mintCollection(newCollectionName); int256 collectionIndex = _getCollectionIndex(ownerToCollections[msg.sender], collectionId); _mint(msg.sender, VIDEO_ID_ID, videoIds.length, ""); for (uint256 i = 0; i < videoIds.length; i++) { videoIdToCollectionId[videoIds[i]] = collectionId; } ownerToCollections[msg.sender][uint256(collectionIndex)].videoIds = videoIds; userToRegistrationDate[msg.sender] = block.timestamp; creatorAddress.transfer(msg.value); return collectionId; } /* --- MINTING --- */ function mintCollection(string memory collectionName) public payable returns (uint256) { require(bytes(collectionName).length > 0, "collectionName is empty"); require(ownerToCollections[msg.sender].length == 0 || msg.value >= collectionMintingPrice, "Not enought value was sent to mint a collection!"); uint256[] memory ids = new uint256[](2); ids[0] = COLLECTION_ID; ids[1] = SLOT_ID; uint256[] memory amounts = new uint256[](2); amounts[0] = 1; amounts[1] = newCollectionSlots; _mintBatch(msg.sender, ids, amounts, ""); _currentCollectionId++; ownerToCollections[msg.sender].push(Collection(_currentCollectionId, collectionName, newCollectionSlots, new string[](0))); creatorAddress.transfer(msg.value); return _currentCollectionId; } function mintCollectionSlots(uint256 collectionId, uint256 slotAmount) public payable returns (uint256) { require(collectionId <= _currentCollectionId, "collectionId is not valid!"); require(slotAmount > 0, "slotAmount must be greater than 0!"); int256 collectionIndex = _getCollectionIndex(ownerToCollections[msg.sender], collectionId); require(collectionIndex >= 0, "User does not own this collection!"); require(msg.value >= slotMintingPrice, "Not enought value was sent to mint a slot!"); _mint(msg.sender, SLOT_ID, slotAmount, ""); uint256 newSlotAmount = ownerToCollections[msg.sender][uint256(collectionIndex)].slots += slotAmount; creatorAddress.transfer(msg.value); return newSlotAmount; } function mintVideoId(string memory videoId, uint256 collectionId) public payable { require(bytes(videoId).length > 0, "videoId is empty!"); require(collectionId <= _currentCollectionId, "collectionId is not valid!"); require(videoIdToOwner[videoId] == address(0x0), "Video already minted!"); int256 collectionIndex = _getCollectionIndex(ownerToCollections[msg.sender], collectionId); require(collectionIndex >= 0, "User does not own this collection!"); Collection storage collection = ownerToCollections[msg.sender][uint256(collectionIndex)]; require(collection.slots > collection.videoIds.length, "No more slots available in this collection!"); require(msg.value >= videoIdMintingPrice, "Not enought value was sent to mint a video!"); _mint(msg.sender, VIDEO_ID_ID, 1, ""); videoIdToOwner[videoId] = msg.sender; collection.videoIds.push(videoId); creatorAddress.transfer(msg.value); } function mintMarketplaceItem(string memory videoId, uint256 price, uint256 bid, uint256 bidEndDate) public payable { require(bytes(videoId).length > 0, "videoId is empty!"); require(videoIdToOwner[videoId] == msg.sender, "User does not own this video!"); require(price > 0, "price must be greater than 0!"); require(bidEndDate > block.timestamp + marketplaceItemMinimumBidTime, "bidEndDate must be greater than current block timestamp + marketplaceItemMinimumBidTime!"); require(msg.value >= marketplaceItemMintingPrice, "Not enought value was sent to mint a marketplace item!"); _mint(msg.sender, MARKETPLACE_ITEM_ID, 1, ""); MarketplaceItem memory marketplaceItem = MarketplaceItem( videoId, payable(msg.sender), payable(address(0x0)), price, bid, 0, 0, block.timestamp, bidEndDate ); marketplaceItemsByDate.push(marketplaceItem); marketplaceItemsByPrice.push(marketplaceItem); _sortMarketplaceItemsByPrice(marketplaceItemsByPrice); // Should use min(price, bid) and fill holes // TODO decide if kept here videoIdToMarketplaceItem[videoId] = marketplaceItem; creatorAddress.transfer(msg.value); } /* --- COLLECTIONS --- */ function renameCollection(uint256 collectionId, string memory newName) public { require(collectionId <= _currentCollectionId, "collectionId is not valid!"); require(bytes(newName).length > 0, "newName is empty!"); int256 collectionIndex = _getCollectionIndex(ownerToCollections[msg.sender], collectionId); require(collectionIndex >= 0, "User does not own this collection!"); ownerToCollections[msg.sender][uint256(collectionIndex)].name = newName; } function moveCollection(uint256 collectionId, int256 indexDelta) public { require(collectionId <= _currentCollectionId, "collectionId is not valid!"); require(indexDelta != 0, "indexDelta is 0!"); int256 collectionIndex = _getCollectionIndex(ownerToCollections[msg.sender], collectionId); require(collectionIndex >= 0, "User does not own this collection!"); int256 newIndex = collectionIndex + indexDelta; require(newIndex >= 0, "New index is out of bounds!"); uint256 unsignedNewIndex = uint256(newIndex); uint256 unsignedIndex = uint256(collectionIndex); require(unsignedNewIndex < ownerToCollections[msg.sender].length, "New index is out of bounds!"); (ownerToCollections[msg.sender][unsignedNewIndex], ownerToCollections[msg.sender][unsignedIndex]) = (ownerToCollections[msg.sender][unsignedIndex], ownerToCollections[msg.sender][unsignedNewIndex]); } /* --- MARKETPLACE --- */ function bidVideoId(string memory videoId) public payable { MarketplaceItem storage marketplaceItem = videoIdToMarketplaceItem[videoId]; require(marketplaceItem.owner != msg.sender, "Bidder should not be the owner of this videoId!"); require(marketplaceItem.endDate > block.timestamp, "Bidding is closed!"); require(marketplaceItem.bid < msg.value, "You should bid a higger amount than the current bid!"); marketplaceItem.bidder.transfer(marketplaceItem.bid); // Refund previous bidder marketplaceItem.bid = msg.value; marketplaceItem.bidder = payable(msg.sender); marketplaceItem.bidDate = block.timestamp; } function claimVideoId(string memory videoId) public payable { MarketplaceItem storage marketplaceItem = videoIdToMarketplaceItem[videoId]; require(marketplaceItem.bidder == msg.sender, "Claiming is reserved to the highest bidder!"); require(marketplaceItem.endDate < block.timestamp, "Bidding should be closed!"); marketplaceItem.owner.transfer(marketplaceItem.bid); // TODO } /* --- DONATION --- */ function donate() public payable returns (string memory) { creatorAddress.transfer(msg.value); return "Thank you for your donation!"; } /* --- ADMIN METHODS --- */ function setURI(string memory newuri) public onlyRole(URI_SETTER_ROLE) { _setURI(newuri); } function pause() public onlyRole(PAUSER_ROLE) { _pause(); } function unpause() public onlyRole(PAUSER_ROLE) { _unpause(); } /* --- HELPERS --- */ function _getCollectionIndex(Collection[] memory collections, uint256 collectionId) internal pure returns (int256) { for (uint256 i = 0; i < collections.length; i++) { if (collections[i].id == collectionId) { return int256(i); } } return -1; } function _sortMarketplaceItemsByPrice(MarketplaceItem[] storage marketplaceItems) internal { // for i = 2:n, // for (k = i; k > 1 and a[k] < a[k-1]; k--) // swap a[k,k-1] // → invariant: a[1..i] is sorted // end } /* --- INTERNALS --- */ function _beforeTokenTransfer(address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal whenNotPaused override(ERC1155Upgradeable, ERC1155SupplyUpgradeable) { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } // The following functions are overrides required by Solidity. function supportsInterface(bytes4 interfaceId) public view override(ERC1155Upgradeable, AccessControlUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } }
TODO optimize with variable else if (sort == SORT_PRICE_ASC) { return marketplaceItems; } else if (sort == SORT_PRICE_DESC) { return marketplaceItems; }
function getMarketplaceItems(uint256 skip, uint256 sort) public view returns (MarketplaceItem[] memory marketplaceItems) { marketplaceItems = new MarketplaceItem[](marketplaceItemPagination); uint256 passCount = 0; if (sort == SORT_CREATED_DESC) { for (uint256 i = marketplaceItemsByDate.length - skip - 1; i >= marketplaceItemsByDate.length - skip - marketplaceItemPagination - passCount - 1; i--) { if (marketplaceItemsByDate[i].endDate > block.timestamp) { passCount++; continue; } marketplaceItems[marketplaceItemPagination - i + passCount] = marketplaceItemsByDate[i]; } return marketplaceItems; } else if (sort == SORT_CREATED_DESC) { for (uint256 i = skip; i < marketplaceItemPagination + passCount; i++) { if (marketplaceItemsByDate[i].endDate > block.timestamp) { passCount++; continue; } marketplaceItems[i - passCount] = marketplaceItemsByDate[i]; } return marketplaceItems; } else { revert("Invalid sort!"); } } --- */
7,242,220
[ 1, 6241, 10979, 598, 2190, 469, 309, 261, 3804, 422, 11530, 67, 7698, 1441, 67, 8633, 13, 288, 377, 327, 29917, 3126, 31, 289, 469, 309, 261, 3804, 422, 11530, 67, 7698, 1441, 67, 10964, 13, 288, 377, 327, 29917, 3126, 31, 289, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 23232, 24577, 3126, 12, 11890, 5034, 2488, 16, 2254, 5034, 1524, 13, 1071, 1476, 1135, 261, 3882, 24577, 1180, 8526, 3778, 29917, 3126, 13, 288, 203, 3639, 29917, 3126, 273, 394, 6622, 24577, 1180, 8526, 12, 3355, 24577, 1180, 19224, 1769, 203, 3639, 2254, 5034, 1342, 1380, 273, 374, 31, 203, 203, 3639, 309, 261, 3804, 422, 11530, 67, 18546, 67, 10964, 13, 288, 203, 5411, 364, 261, 11890, 5034, 277, 273, 29917, 3126, 858, 1626, 18, 2469, 300, 2488, 300, 404, 31, 277, 1545, 29917, 3126, 858, 1626, 18, 2469, 300, 2488, 300, 29917, 1180, 19224, 300, 1342, 1380, 300, 404, 31, 277, 413, 13, 288, 203, 7734, 309, 261, 3355, 24577, 3126, 858, 1626, 63, 77, 8009, 409, 1626, 405, 1203, 18, 5508, 13, 288, 203, 10792, 1342, 1380, 9904, 31, 203, 203, 10792, 1324, 31, 203, 7734, 289, 203, 203, 7734, 29917, 3126, 63, 3355, 24577, 1180, 19224, 300, 277, 397, 1342, 1380, 65, 273, 29917, 3126, 858, 1626, 63, 77, 15533, 203, 5411, 289, 203, 203, 5411, 327, 29917, 3126, 31, 203, 3639, 289, 203, 3639, 469, 309, 261, 3804, 422, 11530, 67, 18546, 67, 10964, 13, 288, 203, 5411, 364, 261, 11890, 5034, 277, 273, 2488, 31, 277, 411, 29917, 1180, 19224, 397, 1342, 1380, 31, 277, 27245, 288, 203, 7734, 309, 261, 3355, 24577, 3126, 858, 1626, 63, 77, 8009, 409, 1626, 405, 1203, 18, 5508, 13, 288, 203, 10792, 1342, 1380, 9904, 31, 203, 203, 10792, 1324, 31, 203, 7734, 289, 203, 203, 7734, 29917, 2 ]
./partial_match/1/0xd4260e4Bfb354259F5e30279cb0D7F784Ea5f37A/sources/VokenPublicSale2.sol
* @dev Returns the {limitIndex} and {weiMax}./
function _limit(uint256 weiAmount) private view returns (uint256 __wei) { uint256 __purchased = _weiSeasonAccountPurchased[_season][msg.sender]; for(uint16 i = 0; i < LIMIT_WEIS.length; i++) { if (__purchased >= LIMIT_WEIS[i]) { return 0; } if (__purchased < LIMIT_WEIS[i]) { __wei = LIMIT_WEIS[i].sub(__purchased); if (weiAmount >= __wei && _seasonLimitAccounts[_season][i].length < LIMIT_COUNTER[i]) { return __wei; } } } if (__purchased < LIMIT_WEI_MIN) { return LIMIT_WEI_MIN.sub(__purchased); } }
2,613,654
[ 1, 1356, 326, 288, 3595, 1016, 97, 471, 288, 1814, 77, 2747, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 445, 389, 3595, 12, 11890, 5034, 732, 77, 6275, 13, 3238, 1476, 1135, 261, 11890, 5034, 1001, 1814, 77, 13, 288, 203, 5411, 2254, 5034, 1001, 12688, 343, 8905, 273, 389, 1814, 77, 1761, 2753, 3032, 10262, 343, 8905, 63, 67, 30321, 6362, 3576, 18, 15330, 15533, 203, 5411, 364, 12, 11890, 2313, 277, 273, 374, 31, 277, 411, 13319, 67, 6950, 5127, 18, 2469, 31, 277, 27245, 288, 203, 7734, 309, 261, 972, 12688, 343, 8905, 1545, 13319, 67, 6950, 5127, 63, 77, 5717, 288, 203, 10792, 327, 374, 31, 203, 7734, 289, 203, 203, 7734, 309, 261, 972, 12688, 343, 8905, 411, 13319, 67, 6950, 5127, 63, 77, 5717, 288, 203, 10792, 1001, 1814, 77, 273, 13319, 67, 6950, 5127, 63, 77, 8009, 1717, 12, 972, 12688, 343, 8905, 1769, 203, 10792, 309, 261, 1814, 77, 6275, 1545, 1001, 1814, 77, 597, 389, 30321, 3039, 13971, 63, 67, 30321, 6362, 77, 8009, 2469, 411, 13319, 67, 7240, 654, 63, 77, 5717, 288, 203, 13491, 327, 1001, 1814, 77, 31, 203, 10792, 289, 203, 7734, 289, 203, 5411, 289, 203, 203, 5411, 309, 261, 972, 12688, 343, 8905, 411, 13319, 67, 6950, 45, 67, 6236, 13, 288, 203, 7734, 327, 13319, 67, 6950, 45, 67, 6236, 18, 1717, 12, 972, 12688, 343, 8905, 1769, 203, 5411, 289, 203, 3639, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // █████ ███ █████ ████ █████████ █████ // // ░░███ ░███ ░░███ ░░███ ███░░░░░███ ░░███ // // ░███ ░███ ░███ ██████ ░███ ██████ ██████ █████████████ ██████ ░███ ░░░ ███████ ████████ ██████ ████████ ███████ ██████ ████████ // // ░███ ░███ ░███ ███░░███ ░███ ███░░███ ███░░███░░███░░███░░███ ███░░███ ░░█████████ ░░░███░ ░░███░░███ ░░░░░███ ░░███░░███ ███░░███ ███░░███░░███░░███ // // ░░███ █████ ███ ░███████ ░███ ░███ ░░░ ░███ ░███ ░███ ░███ ░███ ░███████ ░░░░░░░░███ ░███ ░███ ░░░ ███████ ░███ ░███ ░███ ░███░███████ ░███ ░░░ // // ░░░█████░█████░ ░███░░░ ░███ ░███ ███░███ ░███ ░███ ░███ ░███ ░███░░░ ███ ░███ ░███ ███ ░███ ███░░███ ░███ ░███ ░███ ░███░███░░░ ░███ // // ░░███ ░░███ ░░██████ █████░░██████ ░░██████ █████░███ █████░░██████ ░░█████████ ░░█████ █████ ░░████████ ████ █████░░███████░░██████ █████ // // ░░░ ░░░ ░░░░░░ ░░░░░ ░░░░░░ ░░░░░░ ░░░░░ ░░░ ░░░░░ ░░░░░░ ░░░░░░░░░ ░░░░░ ░░░░░ ░░░░░░░░ ░░░░ ░░░░░ ░░░░░███ ░░░░░░ ░░░░░ // // ███ ░███ // // ░░██████ // // ░░░░░░ // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./EscrowManagement.sol"; import "./SignedMessages.sol"; import "./TokenSegments.sol"; // we whitelist OpenSea so that minters can save on gas and spend it on NFTs contract OwnableDelegateProxy { } contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } contract ConjuredLands is ReentrancyGuard, EscrowManagement, ERC721, ERC721Enumerable, Ownable, SignedMessages, TokenSegments { using Strings for uint256; address proxyRegistryAddress; mapping (address => bool) private airdroppers; mapping(address => uint256[]) private burnedTokensByOwners; uint8 public maxNumberOfTokens = 30; address[] public ownersThatBurned; address[20] public premiumOwners; uint256 public tokenPrice = 0.0555 ether; uint256 public premiumTokenPrice = 5.55 ether; uint256 public constant maxSupply = 10888; uint256 public constant maxIndex = 10887; mapping (uint256 => uint256) private tokenCreationBlocknumber; bool public mintingActive = true; bool public burningActive = false; uint8 public premiumMintingSlots = 22; // that's October 19th 2021 folks! uint256 public salesStartTime = 1634839200; mapping (address => uint256) mintingBlockByOwners; mapping(address => uint256) public highestAmountOfMintedTokensByOwners; string private __baseURI; bool baseURIfrozen = false; // generate random index uint256 internal nonce = 19831594194915648; mapping(int8 => uint256[maxSupply]) private alignmentIndices; // the good, the evil and the neutral https://www.youtube.com/watch?v=WCN5JJY_wiA uint16[3] public alignmentMaxSupply; uint16[3] public alignmentTotalSupply; uint16[3] public alignmentFirstIndex; // these are URIs for the custom part, single URLs and segmented baseURIs mapping(uint256 => string) specialTokenURIs; constructor(string memory _name, string memory _symbol, address[] memory _teamMembers, uint8[] memory _splits, address _proxyRegistryAddress) ERC721(_name, _symbol) { // set the team members require(_teamMembers.length == _splits.length, "Wrong team lengths"); if (_teamMembers.length > 0) { uint8 totalSplit = 0; for (uint8 i = 0; i < _teamMembers.length; i++) { EscrowManagement._addTeamMemberSplit(_teamMembers[i], _splits[i]); totalSplit += _splits[i]; } require(totalSplit == 100, "Total split not 100"); } alignmentMaxSupply[0] = 3000; // good alignmentMaxSupply[1] = 3000; // evil alignmentMaxSupply[2] = 4000; // neutral alignmentFirstIndex[0] = 888; // the indexes 0- 887 are reserved for the giveaways alignmentFirstIndex[1] = alignmentFirstIndex[0] + alignmentMaxSupply[0]; alignmentFirstIndex[2] = alignmentFirstIndex[1] + alignmentMaxSupply[1]; // set the deployer of this contract as an issuer of signed messages SignedMessages.setIssuer(msg.sender, true); __baseURI = "ipfs://QmamCw1tks7fpFyDCfGYVQyMkSwtJ39BRGxuA2D37hFME1/"; proxyRegistryAddress = _proxyRegistryAddress; } function _baseURI() internal view override returns(string memory) { return __baseURI; } function setBaseURI(string memory newBaseURI) public onlyOwner(){ require(!baseURIfrozen, "BaseURI frozen"); __baseURI = newBaseURI; } function baseURI() public view returns(string memory){ return __baseURI; } // calling this function locks the possibility to change the baseURI forever function freezeBaseURI() public onlyOwner(){ baseURIfrozen = true; } function tokenURI(uint256 tokenId) public view override returns(string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); // check if token is in a special segment int256 segmentId = TokenSegments.getSegmentId(tokenId); if (segmentId != -1) { // found a segment, get the URI, only return if it is set string memory segmentURI = TokenSegments.getBaseURIBySegmentId(segmentId); if (bytes(segmentURI).length > 0) { return string(abi.encodePacked(segmentURI,tokenId.toString())); } } // check if a special tokenURI is set, otherwise fallback to standard if (bytes(specialTokenURIs[tokenId]).length == 0){ return ERC721.tokenURI(tokenId); } else { // special tokenURI is set return specialTokenURIs[tokenId]; } } function setSpecialTokenURI(uint256 tokenId, string memory newTokenURI) public onlyOwner(){ require(getAlignmentByIndex(tokenId) == -1, "No special token"); specialTokenURIs[tokenId] = newTokenURI; } function setSegmentBaseTokenURIs(uint256 startingIndex, uint256 endingIndex, string memory _URI) public onlyOwner(){ TokenSegments._setSegmentBaseTokenURIs(startingIndex, endingIndex, _URI); } function setBaseURIBySegmentId(int256 pointer, string memory _URI) public onlyOwner(){ TokenSegments._setBaseURIBySegmentId(pointer, _URI); } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) override public view returns(bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } // use this to update the registry address, if a wrong one was passed with the constructor function setProxyRegistryAddress(address _proxyRegistryAddress) public onlyOwner(){ proxyRegistryAddress = _proxyRegistryAddress; } function approveAirdropperContract(address contractAddress, bool approval) public onlyOwner(){ airdroppers[contractAddress] = approval; } function airdropper_allowedCaller(address caller) public view returns(bool){ // only team members can airdrop return (EscrowManagement.teamMembersSplit[caller] > 0); } // used by the external airdropper function airdropper_allowedToken(uint256 tokenId) public view returns(bool){ // only tokens in the giveaway section are allowed for airdrops return (getAlignmentByIndex(tokenId) == -1); } function airdropper_mint(address to, uint256 tokenId) public{ // protect this call - only the airdropper contract can can call this require(airdroppers[msg.sender], "Not an airdropper"); _internalMintById(to, tokenId); } function setIssuerForSignedMessages(address issuer, bool status) public onlyOwner(){ SignedMessages.setIssuer(issuer, status); } function getAlignmentByIndex(uint256 _index) public view returns(int8){ // we take the last one, and loop int8 alignment = -1; // check the boundaries - lower than the first or higher than the last if ((_index < alignmentFirstIndex[0]) || ((_index > alignmentFirstIndex[alignmentFirstIndex.length - 1] + alignmentMaxSupply[alignmentMaxSupply.length - 1] - 1))) { return -1; } for (uint8 ix = 0; ix < alignmentFirstIndex.length; ix++) { if (alignmentFirstIndex[ix] <= _index) { alignment = int8(ix); } } return alignment; } function addTeamMemberSplit(address teamMember, uint8 split) public onlyOwner(){ EscrowManagement._addTeamMemberSplit(teamMember, split); } function getTeamMembers() public onlyOwner view returns(address[] memory){ return EscrowManagement._getTeamMembers(); } function remainingSupply() public view returns(uint256){ // returns the total remainingSupply return maxSupply - totalSupply(); } function remainingSupply(uint8 alignment) public view returns(uint16){ return alignmentMaxSupply[alignment] - alignmentTotalSupply[alignment]; } function salesStarted() public view returns (bool) { return block.timestamp >= salesStartTime; } // set the time from which the sales will be started function setSalesStartTime(uint256 _salesStartTime) public onlyOwner(){ salesStartTime = _salesStartTime; } function flipMintingState() public onlyOwner(){ mintingActive = !mintingActive; } function flipBurningState() public onlyOwner(){ burningActive = !burningActive; } // change the prices for minting function setTokenPrice(uint256 newPrice) public onlyOwner(){ tokenPrice = newPrice; } function setPremiumTokenPrice(uint256 newPremiumPrice) public onlyOwner(){ premiumTokenPrice = newPremiumPrice; } function getRandomId(uint256 _presetIndex, uint8 _alignment) internal returns(uint256){ uint256 totalSize = remainingSupply(_alignment); int8 alignment = int8(_alignment); // allow the caller to preset an index uint256 index; if (_presetIndex == 0) { index = alignmentFirstIndex[uint8(alignment)] + uint256(keccak256(abi.encodePacked(nonce, "ourSaltAndPepper", blockhash(block.number), msg.sender, block.difficulty, block.timestamp, gasleft()))) % totalSize; } else { index = _presetIndex; alignment = getAlignmentByIndex(index); } if (alignment == -1) { // if the index is out of bounds, then exit return 0; } uint256 value = 0; // the indices holds the value for unused index positions // so you never get a collision if (alignmentIndices[alignment][index] != 0) { value = alignmentIndices[alignment][index]; } else { value = index; } // Move last value to the actual position, so if it get taken, you can give back the free one if (alignmentIndices[alignment][totalSize - 1] == 0) { // Array position not initialized, so use that position alignmentIndices[alignment][index] = totalSize - 1; } else { // Array position holds a value so use that alignmentIndices[alignment][index] = alignmentIndices[alignment][totalSize - 1]; } nonce++; return value; } // team members can always mint out of the giveaway section function membersMint(address to, uint256 tokenId) onlyTeamMembers() public{ // can only mint in the non public section require(getAlignmentByIndex(tokenId) == -1, "Token in public section"); _internalMintById(to, tokenId); } // internal minting function by id, can flexibly be called by the external controllers function _internalMintById(address to, uint256 tokenId) internal{ require(tokenId <= maxIndex, "Token out of index"); _safeMint(to, tokenId); getRandomId(tokenId, 0); // consume the index in the alignment, if it was part of the open section int8 alignment = getAlignmentByIndex(tokenId); if (alignment != -1) { alignmentTotalSupply[uint8(alignment)]++; } } // internal minting function via random index, can flexibly be called by the external controllers function _internalMintRandom(address to, uint256 numberOfTokens, uint8 alignment) internal{ require(numberOfTokens <= maxNumberOfTokens, "Max amount exceeded"); for (uint i = 0; i < numberOfTokens; i++) { uint mintIndex = getRandomId(0, alignment); if (alignmentTotalSupply[alignment] < alignmentMaxSupply[alignment]) { _safeMint(to, mintIndex); alignmentTotalSupply[alignment]++; } } if (numberOfTokens > 0) { // this is for preventing getting the id in the same transaction (semaphore) mintingBlockByOwners[msg.sender] = block.number; // keep track of the minting amounts (even is something has been transferred or burned) highestAmountOfMintedTokensByOwners[msg.sender] += numberOfTokens; emit FundsReceived(msg.sender, msg.value, "payment by minting sale"); } } function mint(uint256 numberOfTokens, uint8 alignment) public payable nonReentrant{ require(mintingActive && salesStarted(), "Minting is not active"); require((tokenPrice * numberOfTokens) == msg.value, "Wrong payment"); require(numberOfTokens <= remainingSupply(alignment), "Purchase amount exceeds max supply"); _internalMintRandom(msg.sender, numberOfTokens, alignment); } function premiumMint(uint8 alignment) public payable nonReentrant{ require(mintingActive && salesStarted(), "Minting is not active"); require(premiumMintingSlots>0, "No more premium minting slots"); require(totalSupply()<= maxSupply, "Maximum supply reached"); require(msg.value == premiumTokenPrice, "Wrong payment"); premiumOwners[premiumMintingSlots -1] = msg.sender; premiumMintingSlots--; _internalMintRandom(msg.sender, 1, alignment); } function burn(uint256 tokenId) public nonReentrant{ require(burningActive, "Burning not active."); super._burn(tokenId); // keep track of burners if (burnedTokensByOwners[msg.sender].length == 0){ // first time they burn, add the caller to the list ownersThatBurned.push(msg.sender); } burnedTokensByOwners[msg.sender].push(tokenId); } function getBurnedTokensByOwner(address owner) public view returns(uint256[] memory){ return burnedTokensByOwners[owner]; } event FundsReceived(address from, uint256 amount, string description); // accounting purposes: we need to be able to split the incoming funds between sales and royalty receive() external payable { emit FundsReceived(msg.sender, msg.value, "direct payment, no sale"); } fallback() external payable { emit FundsReceived(msg.sender, msg.value, "direct payment, no sale"); } /* * Functions for handling signed messages * * */ function mintById_SignedMessage(uint256 _tokenId, uint256 _setPrice, uint256 expirationTimestamp, uint256 _nonce, bytes memory _sig) public payable{ // check validity and execute require(expirationTimestamp <= block.timestamp, "Expired"); bytes32 message = SignedMessages.prefixed(keccak256(abi.encodePacked(msg.sender, _tokenId, _setPrice, expirationTimestamp, _nonce))); require(msg.value == _setPrice, "Wrong payment"); require(SignedMessages.consumePass(message, _sig, _nonce), "Error in signed msg"); _internalMintById(msg.sender, _tokenId); if (msg.value > 0) { emit FundsReceived(msg.sender, msg.value, "payment by minting sale"); } } //DAppJS.addSignatureCall('test', 'address', 'uint8', 'uint256', 'uint256', 'uint256','uint256', 'bytes memory'); function mintByAlignment_SignedMessage(uint8 _alignment, uint256 _numberOfTokens, uint256 _maxAmountOfTokens, uint256 _setPrice, uint256 expirationTimestamp, uint256 _nonce, bytes memory _sig) public payable{ // check validity and execute require(expirationTimestamp <= block.timestamp, "Expired"); require(_numberOfTokens <= _maxAmountOfTokens, "Amount too big"); bytes32 message = SignedMessages.prefixed(keccak256(abi.encodePacked(msg.sender, _alignment, _maxAmountOfTokens, _setPrice, expirationTimestamp, _nonce))); require(msg.value == _setPrice * _numberOfTokens, "Wrong payment"); require(SignedMessages.consumePass(message, _sig, _nonce), "Error in signed msg"); _internalMintRandom(msg.sender, _numberOfTokens, _alignment); if (msg.value > 0) { emit FundsReceived(msg.sender, msg.value, "payment by minting sale"); } } function mintAnyAlignment_SignedMessage(uint8 _alignment, uint256 _numberOfTokens, uint256 _maxAmountOfTokens, uint256 _setPrice, uint256 expirationTimestamp, uint256 _nonce, bytes memory _sig) public payable{ // check validity and execute require(expirationTimestamp <= block.timestamp, "Expired"); require(_numberOfTokens <= _maxAmountOfTokens, "Amount too big"); bytes32 message = SignedMessages.prefixed(keccak256(abi.encodePacked(msg.sender, _maxAmountOfTokens, _setPrice, expirationTimestamp, _nonce))); require(msg.value == _setPrice * _numberOfTokens, "Wrong payment"); require(SignedMessages.consumePass(message, _sig, _nonce), "Error in signed msg"); _internalMintRandom(msg.sender, _numberOfTokens, _alignment); if (msg.value > 0) { emit FundsReceived(msg.sender, msg.value, "payment by minting sale"); } } /* * Withdrawal functions */ function withdrawToOwner() public onlyOwner(){ EscrowManagement._withdrawToOwner(owner()); } // these functions are meant to help retrieve ERC721, ERC1155 and ERC20 tokens that have been sent to this contract function withdrawERC721(address _contract, uint256 id, address to) public onlyOwner(){ EscrowManagement._withdrawERC721(_contract, id, to); } function withdrawERC1155(address _contract, uint256[] memory ids, uint256[] memory amounts, address to) public onlyOwner(){ // withdraw a 1155 token EscrowManagement._withdrawERC1155(_contract, ids, amounts, to); } function withdrawERC20(address _contract, address to, uint256 amount) public onlyOwner(){ // withdraw a 20 token EscrowManagement._withdrawERC20(_contract, to, amount); } function balanceOf(address owner) public view override(ERC721) returns (uint256) { return super.balanceOf(owner); } function transferSplitByOwner(address from, address to, uint8 split) public onlyOwner(){ // allow the contract owner to change the split, if anything with withdrawals goes wrong, or a team member loses access to their EOA EscrowManagement._transferSplit(from, to, split); } function tokensOfOwner(address owner) public view returns (uint256[] memory){ // allow this function only after the minting has happened for passed owner require(block.number > mintingBlockByOwners[owner], "Hello @0xnietzsche"); uint256 tokenCount = balanceOf(owner); if (tokenCount == 0) { // The address has no tokens return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(owner, index); } return result; } } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable, ERC1155Receiver) returns (bool) { return super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT pragma solidity ^ 0.8.0; /* * Manage different baseURIs per tokenSegments. * A segment is defined by a starting and and ending index. * The last added segment that fits a passed ID wins over previous ones. * A segment can be changed back to an empty string. * A segment can be determined by passing a tokenId * */ contract TokenSegments{ string[] segmentBaseURIs; uint256[] tokenSegmentsStartingIndex; uint256[] tokenSegmentsEndingIndex; function _setSegmentBaseTokenURIs(uint256 startingIndex, uint256 endingIndex, string memory _URI) internal{ tokenSegmentsStartingIndex.push(startingIndex); tokenSegmentsEndingIndex.push(endingIndex); segmentBaseURIs.push(_URI); } function getSegmentId(uint256 pointer) public view returns(int256){ // go backwards, so that segments can be overwritten by adding them if (tokenSegmentsStartingIndex.length == 0) { return -1; } for (int256 i = int256(tokenSegmentsStartingIndex.length - 1); i >= 0; i--) { if ((tokenSegmentsStartingIndex[uint256(i)] <= pointer) && (tokenSegmentsEndingIndex[uint256(i)] >= pointer)) { return i; } } return -1; } function getSegmentBaseURI(uint256 tokenId) public view returns(string memory){ int256 segmentId = getSegmentId(tokenId); if (segmentId == -1) { return ""; } return segmentBaseURIs[uint256(segmentId)]; } function getBaseURIBySegmentId(int256 pointer) public view returns(string memory){ return segmentBaseURIs[uint256(pointer)]; } function _setBaseURIBySegmentId(int256 pointer, string memory _URI) internal{ segmentBaseURIs[uint256(pointer)] = _URI; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // handles the signed messages contract SignedMessages{ mapping(uint256 => bool) internal nonces; mapping(address => bool) internal issuers; /// builds a prefixed hash to mimic the behavior of eth_sign. function prefixed(bytes32 hash) internal pure returns(bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } function consumePass(bytes32 message, bytes memory sig, uint256 nonce) internal returns(bool){ // check the nonce first if (nonces[nonce]) { return false; } // check the issuer if (!issuers[recoverSigner(message, sig)]) { return false; } // consume the nonce if it is safe nonces[nonce] = true; return true; } function validateNonce(uint256 _nonce) public view returns(bool){ return nonces[_nonce]; } function setIssuer(address issuer, bool status) internal{ issuers[issuer] = status; } function getIssuerStatus(address issuer) public view returns(bool){ return issuers[issuer]; } function recoverSigner(bytes32 _message, bytes memory sig) internal pure returns(address){ uint8 v; bytes32 r; bytes32 s; (v, r, s) = splitSignature(sig); return ecrecover(_message, v, r, s); } function splitSignature(bytes memory sig) internal pure returns(uint8, bytes32, bytes32){ require(sig.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { // first 32 bytes, after the length prefix r:= mload(add(sig, 32)) // second 32 bytes s:= mload(add(sig, 64)) // final byte (first byte of the next 32 bytes) v:= byte(0, mload(add(sig, 96))) } return (v, r, s); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol"; abstract contract ERC1155Interface{ function safeBatchTransferFrom(address from,address to,uint256[] memory ids,uint256[] memory amounts,bytes memory data) public virtual; } abstract contract ERC721Interface{ function safeTransferFrom(address from,address to,uint256 tokenId) public virtual; } abstract contract ERC20Interface{ function transfer(address recipient, uint256 amount) public virtual returns(bool); } contract EscrowManagement is ReentrancyGuard, ERC721Holder, ERC1155Holder{ address[] internal teamMembers; mapping (address => uint8) internal teamMembersSplit; modifier onlyTeamMembers(){ require(teamMembersSplit[msg.sender] > 0, "No team member"); _; } function _getTeamMembers() internal view returns(address[] memory){ return teamMembers; } function getTeamMemberSplit(address teamMember) public view returns(uint8){ return teamMembersSplit[teamMember]; } /* * Escrow and withdrawal functions for decentral team members */ function _addTeamMemberSplit(address teamMember, uint8 split) internal{ require(teamMembersSplit[teamMember] == 0, "Team member already added"); require(split<101, "Split too big"); teamMembers.push(teamMember); teamMembersSplit[teamMember] = split; } function _transferSplit(address from, address to, uint8 split) internal{ // transfer split from one member to another // the caller has to be a team member require(split <= teamMembersSplit[from], "Split too big"); if (teamMembersSplit[to] == 0) { // if to was not yet a team member, then welcome teamMembers.push(to); } teamMembersSplit[from] = teamMembersSplit[from] - split; teamMembersSplit[to] = teamMembersSplit[to] + split; } function transferSplit(address from, address to, uint8 split) public nonReentrant onlyTeamMembers(){ // the from has the be the caller for team members require(msg.sender == from, "Not the sender"); _transferSplit(from, to, split); } // withdraw - pays out the team members by the defined distribution // every call pays out the actual balance to all team members // this function can be called by anyone function withdraw() public nonReentrant{ uint256 balance = address(this).balance; require(balance > 0, "No balance"); uint256 amountOfTeamMembers = teamMembers.length; require(amountOfTeamMembers >0, "0 team members found"); // in order to distribute everything and take care of rests due to the division, the first team members gets the rest // i=1 -> we start with the second member, the first goes after the for bool success; for (uint256 i=1; i<amountOfTeamMembers; i++) { uint256 payoutAmount = balance /100 * teamMembersSplit[teamMembers[i]]; // only payout if amount is positive if (payoutAmount > 0){ (success, ) = (payable(teamMembers[i])).call{value:payoutAmount}(""); //(payable(teamMembers[i])).transfer(payoutAmount); require(success, "Withdraw failed"); } } // payout the rest to first team member (success, ) = (payable(teamMembers[0])).call{value:address(this).balance}(""); //(payable(teamMembers[0])).transfer(address(this).balance); require(success, "Withdraw failed-0"); } // this function is for safety, if no team members have been defined function _withdrawToOwner(address owner) internal{ require(teamMembers.length == 0, "Team members are defined"); (bool success, ) = (payable(owner)).call{value:address(this).balance}(""); //(payable(owner)).transfer(address(this).balance); require(success, "Withdraw failed."); } // these functions are meant to help retrieve ERC721, ERC1155 and ERC20 tokens that have been sent to this contract function _withdrawERC721(address _contract, uint256 id, address to) internal{ // withdraw a 721 token ERC721Interface ERC721Contract = ERC721Interface(_contract); // transfer ownership from this contract to the specified address ERC721Contract.safeTransferFrom(address(this), to,id); } function _withdrawERC1155(address _contract, uint256[] memory ids, uint256[] memory amounts, address to) internal{ // withdraw a 1155 token ERC1155Interface ERC1155Contract = ERC1155Interface(_contract); // transfer ownership from this contract to the specified address ERC1155Contract.safeBatchTransferFrom(address(this),to,ids,amounts,''); } function _withdrawERC20(address _contract, address to, uint256 amount) internal{ // withdraw a 20 token ERC20Interface ERC20Contract = ERC20Interface(_contract); // transfer ownership from this contract to the specified address ERC20Contract.transfer(to, amount); } } // 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; 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 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; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // 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 "../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; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title 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 "../../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; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC1155Receiver.sol"; import "../../../utils/introspection/ERC165.sol"; /** * @dev _Available since v3.1._ */ abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC1155Receiver.sol"; /** * @dev _Available since v3.1._ */ contract ERC1155Holder is ERC1155Receiver { 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; } } // SPDX-License-Identifier: MIT 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. 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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../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); } }
we take the last one, and loop check the boundaries - lower than the first or higher than the last
function getAlignmentByIndex(uint256 _index) public view returns(int8){ int8 alignment = -1; if ((_index < alignmentFirstIndex[0]) || ((_index > alignmentFirstIndex[alignmentFirstIndex.length - 1] + alignmentMaxSupply[alignmentMaxSupply.length - 1] - 1))) { return -1; } for (uint8 ix = 0; ix < alignmentFirstIndex.length; ix++) { if (alignmentFirstIndex[ix] <= _index) { alignment = int8(ix); } } return alignment; }
1,249,336
[ 1, 1814, 4862, 326, 1142, 1245, 16, 471, 2798, 866, 326, 15054, 300, 2612, 2353, 326, 1122, 578, 10478, 2353, 326, 1142, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 11535, 21268, 12, 11890, 5034, 389, 1615, 13, 1071, 1476, 1135, 12, 474, 28, 15329, 203, 3639, 509, 28, 8710, 273, 300, 21, 31, 203, 3639, 309, 14015, 67, 1615, 411, 8710, 3759, 1016, 63, 20, 5717, 747, 203, 5411, 14015, 67, 1615, 405, 8710, 3759, 1016, 63, 14409, 3759, 1016, 18, 2469, 300, 404, 65, 397, 8710, 2747, 3088, 1283, 63, 14409, 2747, 3088, 1283, 18, 2469, 300, 404, 65, 300, 404, 20349, 288, 203, 5411, 327, 300, 21, 31, 203, 3639, 289, 203, 3639, 364, 261, 11890, 28, 8288, 273, 374, 31, 8288, 411, 8710, 3759, 1016, 18, 2469, 31, 8288, 27245, 288, 203, 5411, 309, 261, 14409, 3759, 1016, 63, 697, 65, 1648, 389, 1615, 13, 288, 203, 7734, 8710, 273, 509, 28, 12, 697, 1769, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 8710, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./verifier.sol"; contract TriangleJump { // Some generic state variable uint public num; Verifier private verifier; constructor(address _verifierAddress) { verifier = Verifier(_verifierAddress); } // Just a generic function to represent some state update function updateSomeState(uint _num) public { num = _num; } function executeTriangleMove( uint[2] memory a, uint[2][2] memory b, uint[2] memory c, uint[1] memory input) public { require(verifier.verifyProof(a, b, c, input), "The Triangle Jump is invalid."); // Execute some state update after verifying the proof (just an example) updateSomeState(a[0]); } }
Some generic state variable
contract TriangleJump { uint public num; Verifier private verifier; pragma solidity ^0.6.0; constructor(address _verifierAddress) { verifier = Verifier(_verifierAddress); } function updateSomeState(uint _num) public { num = _num; } function executeTriangleMove( uint[2] memory a, uint[2][2] memory b, uint[2] memory c, uint[1] memory input) public { require(verifier.verifyProof(a, b, c, input), "The Triangle Jump is invalid."); updateSomeState(a[0]); } }
13,031,673
[ 1, 17358, 5210, 919, 2190, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 10000, 4341, 26743, 288, 203, 565, 2254, 1071, 818, 31, 203, 203, 565, 6160, 1251, 3238, 20130, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 26, 18, 20, 31, 203, 565, 3885, 12, 2867, 389, 31797, 1887, 13, 288, 203, 3639, 20130, 273, 6160, 1251, 24899, 31797, 1887, 1769, 203, 565, 289, 203, 203, 565, 445, 1089, 17358, 1119, 12, 11890, 389, 2107, 13, 1071, 288, 203, 3639, 818, 273, 389, 2107, 31, 203, 565, 289, 203, 203, 565, 445, 1836, 31506, 7607, 12, 203, 3639, 2254, 63, 22, 65, 3778, 279, 16, 203, 3639, 2254, 63, 22, 6362, 22, 65, 3778, 324, 16, 203, 3639, 2254, 63, 22, 65, 3778, 276, 16, 203, 3639, 2254, 63, 21, 65, 3778, 810, 13, 7010, 3639, 1071, 7010, 565, 288, 203, 3639, 2583, 12, 31797, 18, 8705, 20439, 12, 69, 16, 324, 16, 276, 16, 810, 3631, 203, 3639, 315, 1986, 10000, 4341, 804, 2801, 353, 2057, 1199, 1769, 203, 203, 3639, 1089, 17358, 1119, 12, 69, 63, 20, 19226, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; /** * @title DataTypes * @notice TODO */ contract DataTypes { /*** Constants ***/ uint UNI_TOKEN_TYPE = 0; uint PIGI_TOKEN_TYPE = 1; /*** Blocks ***/ struct Block { bytes32 rootHash; uint blockSize; } /*** Txs ***/ struct SwapTx { address sender; uint tokenType; uint32 inputAmount; uint32 minOutputAmount; uint timeout; } struct TransferTx { address sender; address recipient; uint tokenType; uint32 amount; } /*** Transitions ***/ struct CreateAndTransferTransition { bytes32 stateRoot; uint32 senderSlotIndex; uint32 recipientSlotIndex; address createdAccountPubkey; uint tokenType; uint32 amount; bytes signature; } struct TransferTransition { bytes32 stateRoot; uint32 senderSlotIndex; uint32 recipientSlotIndex; uint tokenType; uint32 amount; bytes signature; } struct SwapTransition { bytes32 stateRoot; uint32 senderSlotIndex; uint32 uniswapSlotIndex; uint tokenType; uint32 inputAmount; uint32 minOutputAmount; uint timeout; bytes signature; } struct TransitionInclusionProof { uint blockNumber; uint transitionIndex; bytes32[] siblings; } struct IncludedTransition { bytes transition; // One of the 3 transition types TransitionInclusionProof inclusionProof; } /*** Storage ***/ struct Storage { address pubkey; uint32[2] balances; } struct StorageSlot { uint32 slotIndex; Storage value; } struct IncludedStorageSlot { StorageSlot storageSlot; bytes32[] siblings; } }
* @title DataTypes @notice TODO/
contract DataTypes { uint UNI_TOKEN_TYPE = 0; uint PIGI_TOKEN_TYPE = 1; struct Block { bytes32 rootHash; uint blockSize; } struct SwapTx { address sender; uint tokenType; uint32 inputAmount; uint32 minOutputAmount; uint timeout; } struct TransferTx { address sender; address recipient; uint tokenType; uint32 amount; } struct CreateAndTransferTransition { bytes32 stateRoot; uint32 senderSlotIndex; uint32 recipientSlotIndex; address createdAccountPubkey; uint tokenType; uint32 amount; bytes signature; } struct TransferTransition { bytes32 stateRoot; uint32 senderSlotIndex; uint32 recipientSlotIndex; uint tokenType; uint32 amount; bytes signature; } struct SwapTransition { bytes32 stateRoot; uint32 senderSlotIndex; uint32 uniswapSlotIndex; uint tokenType; uint32 inputAmount; uint32 minOutputAmount; uint timeout; bytes signature; } struct TransitionInclusionProof { uint blockNumber; uint transitionIndex; bytes32[] siblings; } struct IncludedTransition { TransitionInclusionProof inclusionProof; } struct Storage { address pubkey; uint32[2] balances; } struct StorageSlot { uint32 slotIndex; Storage value; } struct IncludedStorageSlot { StorageSlot storageSlot; bytes32[] siblings; } }
5,452,600
[ 1, 751, 2016, 225, 2660, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 1910, 2016, 288, 203, 565, 2254, 19462, 67, 8412, 67, 2399, 273, 374, 31, 203, 565, 2254, 453, 3047, 45, 67, 8412, 67, 2399, 273, 404, 31, 203, 203, 565, 1958, 3914, 288, 203, 3639, 1731, 1578, 1365, 2310, 31, 203, 3639, 2254, 13766, 31, 203, 565, 289, 203, 203, 565, 1958, 12738, 4188, 288, 203, 3639, 1758, 5793, 31, 203, 3639, 2254, 22302, 31, 203, 3639, 2254, 1578, 810, 6275, 31, 203, 3639, 2254, 1578, 1131, 1447, 6275, 31, 203, 3639, 2254, 2021, 31, 203, 565, 289, 203, 203, 565, 1958, 12279, 4188, 288, 203, 3639, 1758, 5793, 31, 203, 3639, 1758, 8027, 31, 203, 3639, 2254, 22302, 31, 203, 3639, 2254, 1578, 3844, 31, 203, 565, 289, 203, 203, 565, 1958, 1788, 1876, 5912, 8850, 288, 203, 3639, 1731, 1578, 919, 2375, 31, 203, 3639, 2254, 1578, 5793, 8764, 1016, 31, 203, 3639, 2254, 1578, 8027, 8764, 1016, 31, 203, 3639, 1758, 2522, 3032, 9581, 856, 31, 203, 3639, 2254, 22302, 31, 203, 3639, 2254, 1578, 3844, 31, 203, 3639, 1731, 3372, 31, 203, 565, 289, 203, 203, 565, 1958, 12279, 8850, 288, 203, 3639, 1731, 1578, 919, 2375, 31, 203, 3639, 2254, 1578, 5793, 8764, 1016, 31, 203, 3639, 2254, 1578, 8027, 8764, 1016, 31, 203, 3639, 2254, 22302, 31, 203, 3639, 2254, 1578, 3844, 31, 203, 3639, 1731, 3372, 31, 203, 565, 289, 203, 203, 565, 1958, 12738, 8850, 288, 203, 3639, 1731, 1578, 919, 2375, 31, 203, 3639, 2254, 1578, 5793, 8764, 1016, 31, 203, 3639, 2254, 1578, 2 ]
./full_match/80001/0xD62c210150CECbb5F12f82c966734681947E0067/sources/https_/github.com/jdkanani/fx-portal/blob/main/contracts/tunnel/FxBaseChildTunnel.sol
* @notice Mock child tunnel contract to receive and send message from L2/ MessageTunnel on L1 will get data from this event fx child fx root tunnel
abstract contract FxBaseChildTunnel is IFxMessageProcessor{ event MessageSent(bytes message); address public fxChild; address public fxRootTunnel; constructor(address _fxChild) { fxChild = _fxChild; } modifier validateSender(address sender) { require(sender == fxRootTunnel, "FxBaseChildTunnel: INVALID_SENDER_FROM_ROOT"); _; } function setFxRootTunnel(address _fxRootTunnel) public { require(fxRootTunnel == address(0x0), "FxBaseChildTunnel: ROOT_TUNNEL_ALREADY_SET"); fxRootTunnel = _fxRootTunnel; } function processMessageFromRoot(uint256 stateId, address rootMessageSender, bytes calldata data) public override { require(msg.sender == fxChild, "FxBaseChildTunnel: INVALID_SENDER"); _processMessageFromRoot(stateId, rootMessageSender, data); } function _sendMessageToRoot(bytes memory message) internal { emit MessageSent(message); } }
9,483,489
[ 1, 9865, 1151, 14825, 6835, 358, 6798, 471, 1366, 883, 628, 511, 22, 19, 2350, 20329, 603, 511, 21, 903, 336, 501, 628, 333, 871, 12661, 1151, 12661, 1365, 14825, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 478, 92, 2171, 1763, 20329, 353, 11083, 92, 1079, 5164, 95, 203, 565, 871, 2350, 7828, 12, 3890, 883, 1769, 203, 203, 565, 1758, 1071, 12661, 1763, 31, 203, 203, 565, 1758, 1071, 12661, 2375, 20329, 31, 203, 203, 565, 3885, 12, 2867, 389, 19595, 1763, 13, 288, 203, 3639, 12661, 1763, 273, 389, 19595, 1763, 31, 203, 565, 289, 203, 203, 565, 9606, 1954, 12021, 12, 2867, 5793, 13, 288, 203, 3639, 2583, 12, 15330, 422, 12661, 2375, 20329, 16, 315, 42, 92, 2171, 1763, 20329, 30, 10071, 67, 1090, 18556, 67, 11249, 67, 9185, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 24340, 92, 2375, 20329, 12, 2867, 389, 19595, 2375, 20329, 13, 1071, 288, 203, 3639, 2583, 12, 19595, 2375, 20329, 422, 1758, 12, 20, 92, 20, 3631, 315, 42, 92, 2171, 1763, 20329, 30, 11011, 67, 56, 2124, 50, 2247, 67, 1013, 20305, 67, 4043, 8863, 203, 3639, 12661, 2375, 20329, 273, 389, 19595, 2375, 20329, 31, 203, 565, 289, 203, 203, 565, 445, 1207, 1079, 1265, 2375, 12, 11890, 5034, 919, 548, 16, 1758, 1365, 1079, 12021, 16, 1731, 745, 892, 501, 13, 1071, 3849, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 12661, 1763, 16, 315, 42, 92, 2171, 1763, 20329, 30, 10071, 67, 1090, 18556, 8863, 203, 3639, 389, 2567, 1079, 1265, 2375, 12, 2019, 548, 16, 1365, 1079, 12021, 16, 501, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 4661, 1079, 774, 2375, 12, 3890, 3778, 883, 13, 2 ]
./partial_match/421613/0xE6Db969E4d0615F1A6071e8F806055662676cEF6/sources/contracts/protocol/libraries/logic/ReserveLogic.sol
contains the credit tokens to be minted to the user
params.answer = params.repayRatio;
16,825,136
[ 1, 12298, 326, 12896, 2430, 358, 506, 312, 474, 329, 358, 326, 729, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 859, 18, 13490, 273, 859, 18, 266, 10239, 8541, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-08-20 */ // Sources flattened with hardhat v2.4.3 https://hardhat.org // File @openzeppelin/contracts/utils/introspection/[email protected] // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File contracts/IERC2981.sol pragma solidity >=0.8.5; /// /// @dev Interface for the NFT Royalty Standard /// interface IERC2981 is IERC165 { /// ERC165 bytes to add to interface array - set in parent contract /// implementing this standard /// /// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a /// bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; /// _registerInterface(_INTERFACE_ID_ERC2981); /// @notice Called with the sale price to determine how much royalty // is owed and to whom. /// @param _tokenId - the NFT asset queried for royalty information /// @param _salePrice - the sale price of the NFT asset specified by _tokenId /// @return receiver - address of who should be sent the royalty payment /// @return royaltyAmount - the royalty payment amount for _salePrice function royaltyInfo( uint256 _tokenId, uint256 _salePrice ) external view returns ( address receiver, uint256 royaltyAmount ); /// @notice Informs callers that this contract supports ERC2981 /// @dev If `_registerInterface(_INTERFACE_ID_ERC2981)` is called /// in the initializer, this should be automatic /// @param interfaceID The interface identifier, as specified in ERC-165 /// @return `true` if the contract implements /// `_INTERFACE_ID_ERC2981` and `false` otherwise function supportsInterface(bytes4 interfaceID) external view override returns (bool); } // File @openzeppelin/contracts/utils/[email protected] 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] pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File contracts/MerkleProof.sol pragma solidity ^0.8.5; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ contract MerkleProof is Ownable { // merkle tree root used to validate the provided address and assigned proof bytes32 public root; /** * @dev Set the merkle tree root hash * @param _root hash to save */ function setMerkleRoot(bytes32 _root) public onlyOwner { require(_root.length > 0, "Root is empty"); require(root == bytes32(""), "Root was already assigned"); root = _root; } /** * @dev Modifier to check if the sender can mint tokens * @param proof hashes to validate */ modifier canMintEarly(bytes32[] memory proof) { require(isProofValid(proof), "the proof for this sender is not valid"); _; } /** * @dev Check if the sender can mint tokens * @param proof hashes to validate */ function isProofValid(bytes32[] memory proof) public view returns (bool) { bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); return verify(leaf, proof); } /** * @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 leaf, bytes32[] memory proof) internal view 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; } } // File @openzeppelin/contracts/token/ERC721/[email protected] 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] 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] pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File @openzeppelin/contracts/utils/[email protected] 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); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/utils/[email protected] 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] pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File @openzeppelin/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(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 any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File @openzeppelin/contracts/utils/math/[email protected] 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; } } } // File @openzeppelin/contracts/security/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @dev ERC721 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC721Pausable is ERC721, Pausable { /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File @openzeppelin/contracts/utils/introspection/[email protected] pragma solidity ^0.8.0; /** * @dev Storage based implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165Storage is ERC165 { /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return super.supportsInterface(interfaceId) || _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; } } // File @openzeppelin/contracts/security/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File contracts/ReaperHills.sol pragma solidity >=0.8.5; contract ReaperHills is MerkleProof, ERC165Storage, ERC721Pausable, ERC721Enumerable, ReentrancyGuard { using SafeMath for uint256; // struct that holds information about when a token was created/transferred struct NFTDetails { uint256 tokenId; uint256 starTime; uint256 endTime; } // emits BaseURIChanged event when the baseUri changes event BaseURIChanged( address indexed _owner, string initialBaseURI, string finalBaseURI ); // interface used by marketplaces to get the royalty for a specific sell bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; // maximum number of tokens that can be minted uint256 public constant MAX_TOKENS = 10000; // maximum number of tokens that can be early minted in a single transaction uint256 public constant MAX_EARLY_TOKENS_PER_PURCHASE = 25; // maximum number of tokens that can be early minted in a single transaction first day uint256 public constant MAX_EARLY_TOKENS_PER_PURCHASE_FIRST_DAY = 5; // maximum number of tokens that can be minted in a single transaction uint256 public constant MAX_TOKENS_PER_PURCHASE = 50; // the price to mint a token uint256 public constant MINT_PRICE = 60000000000000000; // 0.06 Ether // Reserved tokens for Team/Giveaways/Airdrops etc uint256 public reservedTokens = 100; // Already minted reserved tokens uint256 public mintedReservedTokens = 0; uint256 public mintingStartTime; mapping(address => uint256) public earlyMintedTokensByOwner; // royalty got from a sell uint256 public constant ROYALTY_SELL_PERCENT = 10; // 10% of sell price // part of royalty that is being distributed to the team 1 uint256 public constant ROYALTY_SELL_PERCENT_TEAM_1 = 40; // 2% of sell price // part of royalty that is being distributed to the team 2 uint256 public constant ROYALTY_SELL_PERCENT_TEAM_2 = 40; // 2% of sell price // part of royalty that is being distributed to the team 3 uint256 public constant ROYALTY_SELL_PERCENT_TEAM_3 = 15; // 0.75% of sell price // part of royalty that is being distributed to the team 4 uint256 public constant ROYALTY_SELL_PERCENT_TEAM_4 = 5; // 0.25% of sell price // address team 1 to receive part of royalty address public royaltyReceiverTeam1; // address team 2 to receive part of royalty address public royaltyReceiverTeam2; // address team 3 to receive part of royalty address public royaltyReceiverTeam3; // address team 4 to receive part of royalty address public royaltyReceiverTeam4; // address team 4 to receive part of royalty address public communityAddress; // allow early adopters to mint tokens. Once disabled can't be enabled back bool public earlyMinting = true; // flag to signal if the owner can change the BaseURI bool public canChangeBaseURI = true; // the base uri where the NFT metadata would point to string public baseURI = ""; // hash to proof that the images and metadata from IPFS is valid string public provenance = ""; // mapping from owner to list of token ids mapping(address => uint256[]) public ownerTokenList; // mapping from token ID to token details of the owner tokens list mapping(address => mapping(uint256 => NFTDetails)) public ownedTokensDetails; // nonce to be used on generating the random token id uint256 private nonce = 0; uint256[MAX_TOKENS] private indices; constructor( string memory name_, string memory symbol_, address royaltyReceiver1_, address royaltyReceiver2_, address royaltyReceiver3_, address royaltyReceiver4_, address communityAddress_ ) ERC721(name_, symbol_) { royaltyReceiverTeam1 = royaltyReceiver1_; royaltyReceiverTeam2 = royaltyReceiver2_; royaltyReceiverTeam3 = royaltyReceiver3_; royaltyReceiverTeam4 = royaltyReceiver4_; communityAddress = communityAddress_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(type(IERC721).interfaceId); _registerInterface(type(IERC721Metadata).interfaceId); _registerInterface(type(IERC721Enumerable).interfaceId); } function firstMints() public onlyOwner { for (uint8 id = 1; id <= 6; id++) { indices[id - 1] = MAX_TOKENS - totalSupply() - 1; ownerTokenList[communityAddress].push(id); ownedTokensDetails[communityAddress][id] = NFTDetails( id, block.timestamp, 0 ); _safeMint(communityAddress, id); } } /* * accepts ether sent with no txData */ receive() external payable {} /* * refuses ether sent with txData that does not match any function signature in the contract */ fallback() external {} /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function pause() public onlyOwner { super._pause(); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function unpause() public onlyOwner { super._unpause(); } /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721Pausable, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } /** * @dev Retrieve the ETH balance of the current contract */ function getBalance() public view returns (uint256) { return address(this).balance; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC165Storage, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overwritten * in child contracts. */ function _baseURI() internal view override returns (string memory) { return baseURI; } /** * @dev Set the baseURI to a given uri * @param uri string to save */ function changeBaseURI(string memory uri) public onlyOwner { require(canChangeBaseURI, "The baseURI can't be changed anymore"); require(bytes(uri).length > 0, "uri is empty"); string memory initialBaseURI = baseURI; baseURI = uri; emit BaseURIChanged(msg.sender, initialBaseURI, baseURI); } /** * @dev Get the list of tokens for a specific owner * @param _owner address to retrieve token ids for */ function tokensByOwner(address _owner) external view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } /** * @dev Set the NFT IPFS hash proof for tokens metadata * @param hashProof string to save */ function setProvenance(string memory hashProof) public onlyOwner { require(bytes(hashProof).length > 0, "hash proof is empty"); provenance = hashProof; } /** * @dev Disable early minting */ function disableEarlyMinting() external onlyOwner { require(earlyMinting, "Early minting already disabled"); earlyMinting = false; } /** * @dev Disable changes for baseURI */ function disableBaseURIChanges() external onlyOwner { require(canChangeBaseURI, "The owner can't change the baseURI anymore"); canChangeBaseURI = false; } /** * Credits to LarvaLabs Meebits contract */ function randomIndex() internal returns (uint256) { uint256 totalSize = MAX_TOKENS - totalSupply(); uint256 index = uint256( keccak256( abi.encodePacked( nonce, msg.sender, block.difficulty, block.timestamp ) ) ) % totalSize; uint256 value = 0; if (indices[index] != 0) { value = indices[index]; } else { value = index; } // Move last value to selected position if (indices[totalSize - 1] == 0) { // Array position not initialized, so use position indices[index] = totalSize - 1; } else { // Array position holds a value so use that indices[index] = indices[totalSize - 1]; } nonce++; // Don't allow a zero index, start counting at 1 return value + 1; } /** * @dev Mint tokens early * @param _count the number of tokens to be minted * @param proof to validate if the sender can mint the tokens early */ function earlyMint(uint256 _count, bytes32[] memory proof) public payable nonReentrant canMintEarly(proof) { require( earlyMinting, "The early minting is disabled. Use the mint function." ); require( _count > 0 && _count <= MAX_EARLY_TOKENS_PER_PURCHASE, "Too many early tokens to mint at once" ); require( _count + earlyMintedTokensByOwner[msg.sender] <= MAX_EARLY_TOKENS_PER_PURCHASE, "Too many early tokens to mint" ); if (block.timestamp - mintingStartTime <= 86400) { require( _count <= MAX_EARLY_TOKENS_PER_PURCHASE_FIRST_DAY, "To many tokens to be minted early in the first day" ); } earlyMintedTokensByOwner[msg.sender] += _count; _mint(_count); } /** * @dev Withdraw contract balance to owner */ function withdraw() public onlyOwner { sendValueTo(msg.sender, address(this).balance); } /** * @dev Mint tokens for community wallet */ function mintToCommunityWallet(uint8 _count) external onlyOwner { require( _count > 0 && _count <= reservedTokens, "Too many reserved tokens to mint at once" ); require( _count + mintedReservedTokens <= reservedTokens, "Too many reserved tokens to mint" ); mintedReservedTokens += _count; mintNTokensFor(communityAddress, _count); } /** * @dev Mint new tokens * @param _count the number of tokens to be minted */ function mint(uint256 _count) public payable nonReentrant { require( !earlyMinting, "The early minting is enabled. Use earlyMint function." ); _mint(_count); } /** * @dev Mint new tokens * @param _count the number of tokens to be minted */ function _mint(uint256 _count) internal { require(!paused(), "The minting of new tokens is paused"); uint256 totalSupply = totalSupply(); require( _count > 0 && _count <= MAX_TOKENS_PER_PURCHASE, "The maximum number of tokens that can be minted was exceeded" ); require( totalSupply + _count <= MAX_TOKENS, "Exceeds maximum tokens available for purchase" ); require( msg.value >= MINT_PRICE.mul(_count), "Ether value sent is not correct" ); for (uint256 i = 0; i < _count; i++) { _mintToken(msg.sender); } uint256 value = msg.value; sendValueTo( royaltyReceiverTeam1, (value * ROYALTY_SELL_PERCENT_TEAM_1) / 100 ); sendValueTo( royaltyReceiverTeam2, (value * ROYALTY_SELL_PERCENT_TEAM_2) / 100 ); sendValueTo( royaltyReceiverTeam3, (value * ROYALTY_SELL_PERCENT_TEAM_3) / 100 ); sendValueTo( royaltyReceiverTeam4, (value * ROYALTY_SELL_PERCENT_TEAM_4) / 100 ); } /** * @dev Mint token for an address * @param to address to mint token for */ function _mintToken(address to) internal { uint256 id = randomIndex(); ownerTokenList[to].push(id); ownedTokensDetails[to][id] = NFTDetails(id, block.timestamp, 0); _safeMint(to, id); } /** * @dev Mint n tokens for an address * @param to address to mint tokens for * @param n number of tokens to mint */ function mintNTokensFor(address to, uint8 n) internal { for (uint8 i = 0; i < n; i++) { _mintToken(to); } } /** * @dev Send an amount of value to a specific address * @param to_ address that will receive the value * @param value to be sent to the address */ function sendValueTo(address to_, uint256 value) internal { address payable to = payable(to_); (bool success, ) = to.call{value: value}(""); require(success, "Transfer failed."); } /** * @dev Get token history list of sender */ function getTokenList() public view returns (uint256[] memory) { return ownerTokenList[msg.sender]; } /** * @dev Get token history list of owner * @param owner_ for which to get all the tokens */ function getTokenListFor(address owner_) public view returns (uint256[] memory) { return ownerTokenList[owner_]; } /** * @dev Get token details for sender */ function getTokenDetails() public view returns (NFTDetails[] memory) { return getTokenDetailsFor(msg.sender); } /** * @dev Get token details for a specific address * @param owner_ for which to get all the token details */ function getTokenDetailsFor(address owner_) public view returns (NFTDetails[] memory) { return getTokenDetailsForFromIndex(owner_, 0); } /** * @dev Get token details for a specific address from an index of owner's token lsit * @param owner_ for which to get the token details * @param index from which to start retrieving the token details */ function getTokenDetailsForFromIndex(address owner_, uint256 index) public view returns (NFTDetails[] memory) { uint256[] memory ownerList = ownerTokenList[owner_]; NFTDetails[] memory details = new NFTDetails[]( ownerList.length - index ); uint256 counter = 0; for (uint256 i = index; i < ownerList.length; i++) { details[counter] = ownedTokensDetails[owner_][ownerList[i]]; counter++; } return details; } /** * @dev Change token owner details mappings */ function _updateTokenOwners( address from, address to, uint256 tokenId ) internal { ownedTokensDetails[from][tokenId].endTime = block.timestamp; ownerTokenList[to].push(tokenId); ownedTokensDetails[to][tokenId] = NFTDetails( tokenId, block.timestamp, 0 ); } /** * @dev See {IERC721-safeTransferFrom}. * @param from address from which to transfer the token * @param to address to which to transfer the token * @param tokenId to transfer */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { _updateTokenOwners(from, to, tokenId); super.safeTransferFrom(from, to, tokenId); } /** * @dev See {IERC721-transferFrom}. * @param from address from which to transfer the token * @param to address to which to transfer the token * @param tokenId to transfer */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _updateTokenOwners(from, to, tokenId); super.transferFrom(from, to, tokenId); } }
* @dev These functions deal with verification of Merkle trees (hash trees),/ merkle tree root used to validate the provided address and assigned proof
contract MerkleProof is Ownable { bytes32 public root; function setMerkleRoot(bytes32 _root) public onlyOwner { require(_root.length > 0, "Root is empty"); require(root == bytes32(""), "Root was already assigned"); root = _root; } modifier canMintEarly(bytes32[] memory proof) { require(isProofValid(proof), "the proof for this sender is not valid"); _; } function isProofValid(bytes32[] memory proof) public view returns (bool) { bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); return verify(leaf, proof); } function verify(bytes32 leaf, bytes32[] memory proof) internal view returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { computedHash = keccak256( abi.encodePacked(computedHash, proofElement) ); computedHash = keccak256( abi.encodePacked(proofElement, computedHash) ); } } } function verify(bytes32 leaf, bytes32[] memory proof) internal view returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { computedHash = keccak256( abi.encodePacked(computedHash, proofElement) ); computedHash = keccak256( abi.encodePacked(proofElement, computedHash) ); } } } function verify(bytes32 leaf, bytes32[] memory proof) internal view returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { computedHash = keccak256( abi.encodePacked(computedHash, proofElement) ); computedHash = keccak256( abi.encodePacked(proofElement, computedHash) ); } } } } else { return computedHash == root; }
2,425,116
[ 1, 29690, 4186, 10490, 598, 11805, 434, 31827, 11491, 261, 2816, 11491, 3631, 19, 30235, 2151, 1365, 1399, 358, 1954, 326, 2112, 1758, 471, 6958, 14601, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 31827, 20439, 353, 14223, 6914, 288, 203, 565, 1731, 1578, 1071, 1365, 31, 203, 203, 203, 565, 445, 444, 8478, 15609, 2375, 12, 3890, 1578, 389, 3085, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 24899, 3085, 18, 2469, 405, 374, 16, 315, 2375, 353, 1008, 8863, 203, 3639, 2583, 12, 3085, 422, 1731, 1578, 2932, 6, 3631, 315, 2375, 1703, 1818, 6958, 8863, 203, 3639, 1365, 273, 389, 3085, 31, 203, 565, 289, 203, 203, 565, 9606, 848, 49, 474, 41, 20279, 12, 3890, 1578, 8526, 3778, 14601, 13, 288, 203, 3639, 2583, 12, 291, 20439, 1556, 12, 24207, 3631, 315, 5787, 14601, 364, 333, 5793, 353, 486, 923, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 203, 565, 445, 353, 20439, 1556, 12, 3890, 1578, 8526, 3778, 14601, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 1731, 1578, 7839, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 3576, 18, 15330, 10019, 203, 3639, 327, 3929, 12, 12070, 16, 14601, 1769, 203, 565, 289, 203, 203, 565, 445, 3929, 12, 3890, 1578, 7839, 16, 1731, 1578, 8526, 3778, 14601, 13, 203, 3639, 2713, 1476, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 1731, 1578, 8470, 2310, 273, 7839, 31, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 14601, 18, 2469, 31, 277, 27245, 288, 203, 5411, 1731, 1578, 14601, 1046, 273, 14601, 63, 77, 15533, 203, 203, 5411, 309, 261, 20307, 2310, 1648, 14601, 1046, 13, 2 ]
pragma solidity ^0.4.22; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns(uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns(uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns(uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns(uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address and * provides basic authorization control functions */ contract Ownable { // Public properties address public owner; // Log if ownership has been changed event ChangeOwnership(address indexed _owner, address indexed _newOwner); // Checks if address is an owner modifier OnlyOwner() { require(msg.sender == owner); _; } // The Ownable constructor sets the owner address function Ownable() public { owner = msg.sender; } // Transfer current ownership to the new account function transferOwnership(address _newOwner) public OnlyOwner { require(_newOwner != address(0x0)); owner = _newOwner; emit ChangeOwnership(owner, _newOwner); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { /* * @dev Event to notify listeners about pause. * @param pauseReason string Reason the token was paused for. */ event Pause(string pauseReason); /* * @dev Event to notify listeners about pause. * @param unpauseReason string Reason the token was unpaused for. */ event Unpause(string unpauseReason); bool public isPaused; string public pauseNotice; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier IsNotPaused() { require(!isPaused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier IsPaused() { require(isPaused); _; } /** * @dev called by the owner to pause, triggers stopped state * @param _reason string The reason for the pause. */ function pause(string _reason) OnlyOwner IsNotPaused public { isPaused = true; pauseNotice = _reason; emit Pause(_reason); } /** * @dev called by the owner to unpause, returns to normal state * @param _reason string Reason for the un pause. */ function unpause(string _reason) OnlyOwner IsPaused public { isPaused = false; pauseNotice = _reason; emit Unpause(_reason); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns(uint256 theBalance); function transfer(address to, uint256 value) public returns(bool success); 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 theAllowance); function transferFrom(address from, address to, uint256 value) public returns(bool success); function approve(address spender, uint256 value) public returns(bool success); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken without allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; // Balances for each account mapping(address => uint256) balances; /** * @dev Get the token balance for account * @param _address The address to query the balance of._address * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _address) public constant returns(uint256 theBalance){ return balances[_address]; } /** * @dev Transfer the balance from owner's account to another account * @param _to The address to transfer to. * @param _value The amount to be transferred. * @return Returns true if transfer has been successful */ function transfer(address _to, uint256 _value) public returns(bool success){ require(_to != address(0x0) && _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; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 */ contract StandardToken is BasicToken, ERC20 { // Owner of account approves the transfer of an amount to another account mapping (address => mapping (address => uint256)) allowed; /** * @dev Returns the amount of tokens approved by the owner that can be transferred to the spender's account * @param _owner The address which owns the funds. * @param _spender The address which will spend the funds. * @return An uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns(uint256 theAllowance){ return allowed[_owner][_spender]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * 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 * * @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 success){ require(allowed[msg.sender][_spender] == 0 || _value == 0); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Transfer from `from` account to `to` account using allowance in `from` account to the sender * * @param _from Origin address * @param _to Destination address * @param _value Amount of CHR tokens to send */ function transferFrom(address _from, address _to, uint256 _value) public returns(bool success) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(msg.sender, _value); } } /** * CHERR.IO is a standard ERC20 token with some additional functionalities: * - Transfers are only enabled after contract owner enables it (after the ICO) * - Contract sets 60% of the total supply as allowance for ICO contract */ contract Cherrio is StandardToken, BurnableToken, Ownable, Pausable { using SafeMath for uint256; // Metadata string public constant name = "CHERR.IO"; string public constant symbol = "CHR"; uint8 public constant decimals = 18; // Token supplies uint256 public constant INITIAL_SUPPLY = 200000000 * (10 ** uint256(decimals)); uint256 public constant ADMIN_ALLOWANCE = 80000000 * (10 ** uint256(decimals)); uint256 public constant CONTRACT_ALLOWANCE = INITIAL_SUPPLY - ADMIN_ALLOWANCE; // Funding cap in ETH. Change to equal $12M at time of token offering uint256 public constant FUNDING_ETH_HARD_CAP = 15000 ether; // Minimum cap in ETH. Change to equal $3M at time of token offering uint256 public constant MINIMUM_ETH_SOFT_CAP = 3750 ether; // Min contribution is 0.1 ether uint256 public constant MINIMUM_CONTRIBUTION = 100 finney; // Price of the tokens as in tokens per ether uint256 public constant RATE = 5333; // Price of the tokens in tier 1 uint256 public constant RATE_TIER1 = 8743; // Price of the tokens in tier 2 uint256 public constant RATE_TIER2 = 7306; // Price of the tokens in tier 3 uint256 public constant RATE_TIER3 = 6584; // Price of the tokens in public sale for limited timeline uint256 public constant RATE_PUBLIC_SALE = 5926; // Maximum cap for tier 1 (60M CHR tokens) uint256 public constant TIER1_CAP = 60000000 * (10 ** uint256(decimals)); // Maximum cap for tier 2 (36M CHR tokens) uint256 public constant TIER2_CAP = 36000000 * (10 ** uint256(decimals)); // Maximum cap for each contributor in tier 1 uint256 public participantCapTier1; // Maximum cap for each contributor in tier 2 uint256 public participantCapTier2; // ETH cap for pool addres only in tier 1 uint256 public poolAddressCapTier1; // ETH cap for pool addres only in tier 2 uint256 public poolAddressCapTier2; // The address of the token admin address public adminAddress; // The address where ETH funds are collected address public beneficiaryAddress; // The address of the contract address public contractAddress; // The address of the pool who can send unlimited ETH to the contract address public poolAddress; // Enable transfers after conclusion of the token offering bool public transferIsEnabled; // Amount of raised in Wei uint256 public weiRaised; // Amount of CHR tokens sent to participant for presale and public sale uint256[4] public tokensSent; // Start of public pre-sale in timestamp uint256 startTimePresale; // Start and end time of public sale in timestamp uint256 startTime; uint256 endTime; // Discount period for public sale uint256 publicSaleDiscountEndTime; // End time limits in timestamp for each tier bonus uint256[3] public tierEndTime; //Check if contract address is already set bool contractAddressIsSet; struct Contributor { bool canContribute; uint8 tier; uint256 contributionInWeiTier1; uint256 contributionInWeiTier2; uint256 contributionInWeiTier3; uint256 contributionInWeiPublicSale; } struct Pool { uint256 contributionInWei; } enum Stages { Pending, PreSale, PublicSale, Ended } // The current stage of the offering Stages public stage; mapping(address => Contributor) public contributors; mapping(address => mapping(uint8 => Pool)) public pool; // Check if transfer is enabled modifier TransferIsEnabled { require(transferIsEnabled || msg.sender == adminAddress || msg.sender == contractAddress); _; } /** * @dev Check if address is a valid destination to transfer tokens to * - must not be zero address * - must not be the token address * - must not be the owner's address * - must not be the admin's address * - must not be the token offering contract address * - must not be the beneficiary address */ modifier ValidDestination(address _to) { require(_to != address(0x0)); require(_to != address(this)); require(_to != owner); require(_to != address(adminAddress)); require(_to != address(contractAddress)); require(_to != address(beneficiaryAddress)); _; } /** * Modifier that requires certain stage before executing the main function body * * @param _expectedStage Value that the current stage is required to match */ modifier AtStage(Stages _expectedStage) { require(stage == _expectedStage); _; } // Check if ICO is live modifier CheckIfICOIsLive() { require(stage != Stages.Pending && stage != Stages.Ended); if(stage == Stages.PreSale) { require( startTimePresale > 0 && now >= startTimePresale && now <= tierEndTime[2] ); } else { require( startTime > 0 && now >= startTime && now <= endTime ); } _; } // Check if participant sent more then miniminum required contribution modifier CheckPurchase() { require(msg.value >= MINIMUM_CONTRIBUTION); _; } /** * Event for token purchase logging * * @param _purchaser Participant who paid for CHR tokens * @param _value Amount in WEI paid for token * @param _tokens Amount of tokens purchased */ event TokenPurchase(address indexed _purchaser, uint256 _value, uint256 _tokens); /** * Event when token offering started * * @param _msg Message * @param _startTime Start time in timestamp * @param _endTime End time in timestamp */ event OfferingOpens(string _msg, uint256 _startTime, uint256 _endTime); /** * Event when token offering ended and how much has been raised in wei * * @param _endTime End time in timestamp * @param _totalWeiRaised Total raised funds in wei */ event OfferingCloses(uint256 _endTime, uint256 _totalWeiRaised); /** * Cherrio constructor */ function Cherrio() public { totalSupply = INITIAL_SUPPLY; // Mint tokens balances[msg.sender] = totalSupply; emit Transfer(address(0x0), msg.sender, totalSupply); // Aprove an allowance for admin account adminAddress = 0xe0509bB3921aacc433108D403f020a7c2f92e936; approve(adminAddress, ADMIN_ALLOWANCE); participantCapTier1 = 100 ether; participantCapTier2 = 100 ether; poolAddressCapTier1 = 2000 ether; poolAddressCapTier2 = 2000 ether; weiRaised = 0; startTimePresale = 0; startTime = 0; endTime = 0; publicSaleDiscountEndTime = 0; transferIsEnabled = false; contractAddressIsSet = false; } /** * Add approved addresses * * @param _addresses Array of approved addresses * @param _tier Tier */ function addApprovedAddresses(address[] _addresses, uint8 _tier) external OnlyOwner { uint256 length = _addresses.length; for(uint256 i = 0; i < length; i++) { if(!contributors[_addresses[i]].canContribute) { contributors[_addresses[i]].canContribute = true; contributors[_addresses[i]].tier = _tier; contributors[_addresses[i]].contributionInWeiTier1 = 0; contributors[_addresses[i]].contributionInWeiTier2 = 0; contributors[_addresses[i]].contributionInWeiTier3 = 0; contributors[_addresses[i]].contributionInWeiPublicSale = 0; } } } /** * Add approved address * * @param _address Approved address * @param _tier Tier */ function addSingleApprovedAddress(address _address, uint8 _tier) external OnlyOwner { if(!contributors[_address].canContribute) { contributors[_address].canContribute = true; contributors[_address].tier = _tier; contributors[_address].contributionInWeiTier1 = 0; contributors[_address].contributionInWeiTier2 = 0; contributors[_address].contributionInWeiTier3 = 0; contributors[_address].contributionInWeiPublicSale = 0; } } /** * Set token offering address to approve allowance for offering contract to distribute tokens */ function setTokenOffering() external OnlyOwner{ require(!contractAddressIsSet); require(!transferIsEnabled); contractAddress = address(this); approve(contractAddress, CONTRACT_ALLOWANCE); beneficiaryAddress = 0xAec8c4242c8c2E532c6D6478A7de380263234845; poolAddress = 0x1A2C916B640520E1e93A78fEa04A49D8345a5aa9; pool[poolAddress][0].contributionInWei = 0; pool[poolAddress][1].contributionInWei = 0; pool[poolAddress][2].contributionInWei = 0; pool[poolAddress][3].contributionInWei = 0; tokensSent[0] = 0; tokensSent[1] = 0; tokensSent[2] = 0; tokensSent[3] = 0; stage = Stages.Pending; contractAddressIsSet = true; } /** * Set when presale starts * * @param _startTimePresale Start time of presale in timestamp */ function startPresale(uint256 _startTimePresale) external OnlyOwner AtStage(Stages.Pending) { if(_startTimePresale == 0) { startTimePresale = now; } else { startTimePresale = _startTimePresale; } setTierEndTime(); stage = Stages.PreSale; } /** * Set when public sale starts * * @param _startTime Start time of public sale in timestamp */ function startPublicSale(uint256 _startTime) external OnlyOwner AtStage(Stages.PreSale) { if(_startTime == 0) { startTime = now; } else { startTime = _startTime; } endTime = startTime + 15 days; publicSaleDiscountEndTime = startTime + 3 days; stage = Stages.PublicSale; } // Fallback function can be used to buy CHR tokens function () public payable { buy(); } function buy() public payable IsNotPaused CheckIfICOIsLive returns(bool _success) { uint8 currentTier = getCurrentTier(); if(currentTier > 3) { revert(); } if(!buyTokens(currentTier)) { revert(); } return true; } /** * @param _tier Current Token Sale tier */ function buyTokens(uint8 _tier) internal ValidDestination(msg.sender) CheckPurchase returns(bool _success) { if(weiRaised.add(msg.value) > FUNDING_ETH_HARD_CAP) { revert(); } uint256 contributionInWei = msg.value; if(!checkTierCap(_tier, contributionInWei)) { revert(); } uint256 rate = getTierTokens(_tier); uint256 tokens = contributionInWei.mul(rate); if(msg.sender != poolAddress) { if(stage == Stages.PreSale) { if(!checkAllowedTier(msg.sender, _tier)) { revert(); } } if(!checkAllowedContribution(msg.sender, contributionInWei, _tier)) { revert(); } if(!this.transferFrom(owner, msg.sender, tokens)) { revert(); } if(stage == Stages.PreSale) { if(_tier == 0) { contributors[msg.sender].contributionInWeiTier1 = contributors[msg.sender].contributionInWeiTier1.add(contributionInWei); } else if(_tier == 1) { contributors[msg.sender].contributionInWeiTier2 = contributors[msg.sender].contributionInWeiTier2.add(contributionInWei); } else if(_tier == 2) { contributors[msg.sender].contributionInWeiTier3 = contributors[msg.sender].contributionInWeiTier3.add(contributionInWei); } } else { contributors[msg.sender].contributionInWeiPublicSale = contributors[msg.sender].contributionInWeiPublicSale.add(contributionInWei); } } else { if(!checkPoolAddressTierCap(_tier, contributionInWei)) { revert(); } if(!this.transferFrom(owner, msg.sender, tokens)) { revert(); } pool[poolAddress][_tier].contributionInWei = pool[poolAddress][_tier].contributionInWei.add(contributionInWei); } weiRaised = weiRaised.add(contributionInWei); tokensSent[_tier] = tokensSent[_tier].add(tokens); if(weiRaised >= FUNDING_ETH_HARD_CAP) { offeringEnded(); } beneficiaryAddress.transfer(address(this).balance); emit TokenPurchase(msg.sender, contributionInWei, tokens); return true; } /** * Manually withdraw tokens to private investors * * @param _to Address of private investor * @param _value The number of tokens to send to private investor */ function withdrawCrowdsaleTokens(address _to, uint256 _value) external OnlyOwner ValidDestination(_to) returns (bool _success) { if(!this.transferFrom(owner, _to, _value)) { revert(); } return true; } /** * Transfer from sender to another account * * @param _to Destination address * @param _value Amount of CHR tokens to send */ function transfer(address _to, uint256 _value) public ValidDestination(_to) TransferIsEnabled IsNotPaused returns(bool _success){ return super.transfer(_to, _value); } /** * Transfer from `from` account to `to` account using allowance in `from` account to the sender * * @param _from Origin address * @param _to Destination address * @param _value Amount of CHR tokens to send */ function transferFrom(address _from, address _to, uint256 _value) public ValidDestination(_to) TransferIsEnabled IsNotPaused returns(bool _success){ return super.transferFrom(_from, _to, _value); } /** * Check if participant is allowed to contribute in current tier * * @param _address Participant address * @param _tier Current tier */ function checkAllowedTier(address _address, uint8 _tier) internal view returns (bool _allowed) { if(contributors[_address].tier <= _tier) { return true; } else{ return false; } } /** * Check contribution cap for only tier 1 and 2 * * @param _tier Current tier * @param _value Participant contribution */ function checkTierCap(uint8 _tier, uint256 _value) internal view returns (bool _success) { uint256 currentlyTokensSent = tokensSent[_tier]; bool status = true; if(_tier == 0) { if(TIER1_CAP < currentlyTokensSent.add(_value)) { status = false; } } else if(_tier == 1) { if(TIER2_CAP < currentlyTokensSent.add(_value)) { status = false; } } return status; } /** * Check cap for pool address in tier 1 and 2 * * @param _tier Current tier * @param _value Pool contribution */ function checkPoolAddressTierCap(uint8 _tier, uint256 _value) internal view returns (bool _success) { uint256 currentContribution = pool[poolAddress][_tier].contributionInWei; if((_tier == 0 && (poolAddressCapTier1 < currentContribution.add(_value))) || (_tier == 1 && (poolAddressCapTier2 < currentContribution.add(_value)))) { return false; } return true; } /** * Check cap for pool address in tier 1 and 2 * * @param _address Participant address * @param _value Participant contribution * @param _tier Current tier */ function checkAllowedContribution(address _address, uint256 _value, uint8 _tier) internal view returns (bool _success) { bool status = false; if(contributors[_address].canContribute) { if(_tier == 0) { if(participantCapTier1 >= contributors[_address].contributionInWeiTier1.add(_value)) { status = true; } } else if(_tier == 1) { if(participantCapTier2 >= contributors[_address].contributionInWeiTier2.add(_value)) { status = true; } } else if(_tier == 2) { status = true; } else { status = true; } } return status; } /** * Get current tier tokens rate * * @param _tier Current tier */ function getTierTokens(uint8 _tier) internal view returns(uint256 _tokens) { uint256 tokens = RATE_TIER1; if(_tier == 1) { tokens = RATE_TIER2; } else if(_tier == 2) { tokens = RATE_TIER3; } else if(_tier == 3) { if(now <= publicSaleDiscountEndTime) { tokens = RATE_PUBLIC_SALE; } else { tokens = RATE; } } return tokens; } // Get current tier function getCurrentTier() public view returns(uint8 _tier) { uint8 currentTier = 3; // 3 is public sale if(stage == Stages.PreSale) { if(now <= tierEndTime[0]) { currentTier = 0; } else if(now <= tierEndTime[1]) { currentTier = 1; } else if(now <= tierEndTime[2]) { currentTier = 2; } } else { if(now > endTime) { currentTier = 4; // Token offering ended } } return currentTier; } // Set end time for each tier function setTierEndTime() internal AtStage(Stages.Pending) { tierEndTime[0] = startTimePresale + 1 days; tierEndTime[1] = tierEndTime[0] + 2 days; tierEndTime[2] = tierEndTime[1] + 6 days; } // End the token offering function endOffering() public OnlyOwner { offeringEnded(); } // Token offering is ended function offeringEnded() internal { endTime = now; stage = Stages.Ended; emit OfferingCloses(endTime, weiRaised); } // Enable transfers, burn unsold tokens & set tokenOfferingAddress to 0 function enableTransfer() public OnlyOwner returns(bool _success){ transferIsEnabled = true; uint256 tokensToBurn = allowed[msg.sender][contractAddress]; if(tokensToBurn != 0){ burn(tokensToBurn); approve(contractAddress, 0); } return true; } /** * Extend end time * * @param _addedTime Addtional time in secods */ function extendEndTime(uint256 _addedTime) external OnlyOwner { endTime = endTime + _addedTime; } /** * Extend public sale discount time * * @param _addedPublicSaleDiscountEndTime Addtional time in secods */ function extendPublicSaleDiscountEndTime(uint256 _addedPublicSaleDiscountEndTime) external OnlyOwner { publicSaleDiscountEndTime = publicSaleDiscountEndTime + _addedPublicSaleDiscountEndTime; } /** * Update pool cap for tier 1 * * @param _poolAddressCapTier1 Tier cap */ function updatePoolAddressCapTier1(uint256 _poolAddressCapTier1) external OnlyOwner { poolAddressCapTier1 = _poolAddressCapTier1; } /** * Update pool cap for tier 2 * * @param _poolAddressCapTier2 Tier cap */ function updatePoolAddressCapTier2(uint256 _poolAddressCapTier2) external OnlyOwner { poolAddressCapTier2 = _poolAddressCapTier2; } // /** * Update participant cap for tier 1 * * @param _participantCapTier1 Tier cap */ function updateParticipantCapTier1(uint256 _participantCapTier1) external OnlyOwner { participantCapTier1 = _participantCapTier1; } /** * Update participant cap for tier 2 * * @param _participantCapTier2 Tier cap */ function updateParticipantCapTier2(uint256 _participantCapTier2) external OnlyOwner { participantCapTier2 = _participantCapTier2; } }
* Event for token purchase logging @param _purchaser Participant who paid for CHR tokens @param _value Amount in WEI paid for token @param _tokens Amount of tokens purchased/
event TokenPurchase(address indexed _purchaser, uint256 _value, uint256 _tokens);
5,504,637
[ 1, 1133, 364, 1147, 23701, 2907, 225, 389, 12688, 343, 14558, 31333, 10354, 30591, 364, 6469, 54, 2430, 225, 389, 1132, 377, 16811, 316, 13880, 45, 30591, 364, 1147, 225, 389, 7860, 565, 16811, 434, 2430, 5405, 343, 8905, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 3155, 23164, 12, 2867, 8808, 389, 12688, 343, 14558, 16, 2254, 5034, 389, 1132, 16, 2254, 5034, 389, 7860, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; pragma abicoder v2; // OpenZeppelin v4 import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import { VerifyingKey, SnarkProof, Commitment, SNARK_SCALAR_FIELD, CIRCUIT_OUTPUTS } from "./Globals.sol"; import { Verifier } from "./Verifier.sol"; import { Commitments } from "./Commitments.sol"; import { TokenWhitelist } from "./TokenWhitelist.sol"; /** * @title Railgun Logic * @author Railgun Contributors * @notice Functions to interact with the railgun contract * @dev Wallets for Railgun will only need to interact with functions specified in this contract. * This contract is written to be run behind a ERC1967-like proxy. Upon deployment of proxy the _data parameter should * call the initializeRailgunLogic function. */ contract RailgunLogic is Initializable, OwnableUpgradeable, Commitments, TokenWhitelist, Verifier { using SafeERC20 for IERC20; uint256 private constant MAX_DEPOSIT_WITHDRAW = 2**120; // NOTE: The order of instantiation MUST stay the same across upgrades // add new variables to the bottom of the list // See https://docs.openzeppelin.com/learn/upgrading-smart-contracts#upgrading // Treasury variables address payable public treasury; // Treasury contract uint256 private constant BASIS_POINTS = 10000; // Number of basis points that equal 100% // % fee in 100ths of a %. 100 = 1%. uint256 public depositFee; uint256 public withdrawFee; // Flat fee in wei that applies to all transactions uint256 public transferFee; // Treasury events event TreasuryChange(address treasury); event FeeChange(uint256 depositFee, uint256 withdrawFee, uint256 transferFee); // Transaction events event Nullifier(uint256 indexed nullifier); /** * @notice Initialize Railgun contract * @dev OpenZeppelin initializer ensures this can only be called once * This function also calls initializers on inherited contracts * @param _tokenWhitelist - Initial token whitelist to use * @param _treasury - address to send usage fees to * @param _depositFee - Deposit fee * @param _withdrawFee - Withdraw fee * @param _transferFee - Flat fee that applies to all transactions * @param _owner - governance contract */ function initializeRailgunLogic( VerifyingKey calldata _vKeySmall, VerifyingKey calldata _vKeyLarge, address[] calldata _tokenWhitelist, address payable _treasury, uint256 _depositFee, uint256 _withdrawFee, uint256 _transferFee, address _owner ) external initializer { // Call initializers OwnableUpgradeable.__Ownable_init(); Commitments.initializeCommitments(); TokenWhitelist.initializeTokenWhitelist(_tokenWhitelist); Verifier.initializeVerifier(_vKeySmall, _vKeyLarge); // Set treasury and fee changeTreasury(_treasury); changeFee(_depositFee, _withdrawFee, _transferFee); // Change Owner OwnableUpgradeable.transferOwnership(_owner); } /** * @notice Change treasury address, only callable by owner (governance contract) * @dev This will change the address of the contract we're sending the fees to in the future * it won't transfer tokens already in the treasury * @param _treasury - Address of new treasury contract */ function changeTreasury(address payable _treasury) public onlyOwner { // Do nothing if the new treasury address is same as the old if (treasury != _treasury) { // Change treasury treasury = _treasury; // Emit treasury change event emit TreasuryChange(_treasury); } } /** * @notice Change fee rate for future transactions * @param _depositFee - Deposit fee * @param _withdrawFee - Withdraw fee * @param _transferFee - Flat fee that applies to all transactions */ function changeFee( uint256 _depositFee, uint256 _withdrawFee, uint256 _transferFee ) public onlyOwner { if ( _depositFee != depositFee || _withdrawFee != withdrawFee || _transferFee != transferFee ) { // Change fee depositFee = _depositFee; withdrawFee = _withdrawFee; transferFee = _transferFee; // Emit fee change event emit FeeChange(_depositFee, _withdrawFee, _transferFee); } } /** * @notice Perform a transaction in the Railgun system * @dev This function will perform any combination of deposit, internal transfer * and withdraw actions. * @param _proof - snark proof * @param _adaptIDcontract - contract address to this proof to (ignored if set to 0) * @param _adaptIDparameters - hash of the contract parameters (only used to verify proof, this is verified by the * calling contract) * @param _depositAmount - deposit amount * @param _withdrawAmount - withdraw amount * @param _tokenField - token to use if deposit/withdraw is requested * @param _outputEthAddress - eth address to use if withdraw is requested * @param _treeNumber - merkle tree number * @param _merkleRoot - merkle root to verify against * @param _nullifiers - nullifiers of commitments * @param _commitmentsOut - output commitments */ function transact( // Proof SnarkProof calldata _proof, // Shared address _adaptIDcontract, uint256 _adaptIDparameters, uint256 _depositAmount, uint256 _withdrawAmount, address _tokenField, address _outputEthAddress, // Join uint256 _treeNumber, uint256 _merkleRoot, uint256[] calldata _nullifiers, // Split Commitment[CIRCUIT_OUTPUTS] calldata _commitmentsOut ) external payable { // Check treasury fee is paid require(msg.value >= transferFee, "RailgunLogic: Fee not paid"); // Transfer to treasury // If the treasury contract fails (eg. with revert()) the tx or consumes more than 2300 gas railgun transactions will fail // If this is ever the case, changeTreasury() will neeed to be called to change to a good contract treasury.transfer(msg.value); // If _adaptIDcontract is not zero check that it matches the caller require(_adaptIDcontract == address (0) || _adaptIDcontract == msg.sender, "AdaptID doesn't match caller contract"); // Check merkle root is valid require(Commitments.rootHistory[_treeNumber][_merkleRoot], "RailgunLogic: Invalid Merkle Root"); // Check depositAmount and withdrawAmount are below max allowed value require(_depositAmount < MAX_DEPOSIT_WITHDRAW, "RailgunLogic: depositAmount too high"); require(_withdrawAmount < MAX_DEPOSIT_WITHDRAW, "RailgunLogic: withdrawAmount too high"); // If deposit amount is not 0, token should be on whitelist // address(0) is wildcard (disables whitelist) require( _depositAmount == 0 || TokenWhitelist.tokenWhitelist[_tokenField] || TokenWhitelist.tokenWhitelist[address(0)], "RailgunLogic: Token isn't whitelisted for deposit" ); // Check nullifiers haven't been seen before, this check will also fail if duplicate nullifiers are found in the same transaction for (uint i = 0; i < _nullifiers.length; i++) { uint256 nullifier = _nullifiers[i]; require(!Commitments.nullifiers[nullifier], "RailgunLogic: Nullifier already seen"); // Push to seen nullifiers Commitments.nullifiers[nullifier] = true; // Emit event emit Nullifier(nullifier); } // Verify proof require( Verifier.verifyProof( // Proof _proof, // Shared _adaptIDcontract, _adaptIDparameters, _depositAmount, _withdrawAmount, _tokenField, _outputEthAddress, // Join _treeNumber, _merkleRoot, _nullifiers, // Split _commitmentsOut ), "RailgunLogic: Invalid SNARK proof" ); // Add commitments to accumulator Commitments.addCommitments(_commitmentsOut); IERC20 token = IERC20(_tokenField); // Deposit tokens if required // Fee is on top of deposit if (_depositAmount > 0) { // Calculate fee uint256 feeAmount = _depositAmount * depositFee / BASIS_POINTS; // Use OpenZeppelin safetransfer to revert on failure - https://github.com/ethereum/solidity/issues/4116 // Transfer deposit token.safeTransferFrom(msg.sender, address(this), _depositAmount); // Transfer fee token.safeTransferFrom(msg.sender, treasury, feeAmount); } // Withdraw tokens if required // Fee is subtracted from withdraw if (_withdrawAmount > 0) { // Calculate fee uint256 feeAmount = _withdrawAmount * withdrawFee / BASIS_POINTS; // Use OpenZeppelin safetransfer to revert on failure - https://github.com/ethereum/solidity/issues/4116 // Transfer withdraw token.safeTransfer(_outputEthAddress, _withdrawAmount - feeAmount); // Transfer fee token.safeTransfer(treasury, feeAmount); } } /** * @notice Deposits requested amount and token, creates a commitment hash from supplied values and adds to tree * @dev This is for DeFi integrations where the resulting number of tokens to be added * can't be known in advance (eg. AMM trade where transaction ordering could cause toekn amounts to change) * @param _pubkey - pubkey of commitment * @param _random - randomness field of commitment * @param _amount - amount of commitment * @param _tokenField - token ID of commitment */ function generateDeposit( uint256[2] calldata _pubkey, uint256 _random, uint256 _amount, address _tokenField ) external payable { // Check treasury fee is paid require(msg.value >= transferFee, "RailgunLogic: Fee not paid"); // Transfer to treasury // If the treasury contract fails (eg. with revert()) the tx or consumes more than 2300 gas railgun transactions will fail // If this is ever the case, changeTreasury() will neeed to be called to change to a good contract treasury.transfer(msg.value); // Check deposit amount is not 0 require(_amount > 0, "RailgunLogic: Cannot deposit 0 tokens"); // Check token is on the whitelist // address(0) is wildcard (disables whitelist) require( TokenWhitelist.tokenWhitelist[_tokenField] || TokenWhitelist.tokenWhitelist[address(0)], "RailgunLogic: Token isn't whitelisted for deposit" ); // Check deposit amount isn't greater than max deposit amount require(_amount < MAX_DEPOSIT_WITHDRAW, "RailgunLogic: depositAmount too high"); // Check _random is in snark scalar field require(_random < SNARK_SCALAR_FIELD, "RailgunLogic: random out of range"); // Check pubkey points are in snark scalar field require(_pubkey[0] < SNARK_SCALAR_FIELD, "RailgunLogic: pubkey[0] out of range"); require(_pubkey[1] < SNARK_SCALAR_FIELD, "RailgunLogic: pubkey[1] out of range"); // Calculate fee // Fee is subtracted from deposit uint256 feeAmount = _amount * depositFee / BASIS_POINTS; uint256 depositAmount = _amount - feeAmount; // Generate and add commmitment Commitments.addGeneratedCommitment(_pubkey, _random, depositAmount, _tokenField); IERC20 token = IERC20(_tokenField); // Use OpenZeppelin safetransfer to revert on failure - https://github.com/ethereum/solidity/issues/4116 token.safeTransferFrom(msg.sender, address(this), depositAmount); // Transfer fee token.safeTransferFrom(msg.sender, treasury, feeAmount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // 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; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; pragma abicoder v2; // Constants uint256 constant SNARK_SCALAR_FIELD = 21888242871839275222246405745257275088548364400416034343698204186575808495617; uint256 constant CIRCUIT_OUTPUTS = 3; uint256 constant CIPHERTEXT_WORDS = 6; // Commitment hash and ciphertext struct Commitment { uint256 hash; uint256[CIPHERTEXT_WORDS] ciphertext; // Ciphertext order: iv, recipient pubkey (2 x uint256), random, amount, token uint256[2] senderPubKey; // Ephemeral one time use } struct G1Point { uint256 x; uint256 y; } // Encoding of field elements is: X[0] * z + X[1] struct G2Point { uint256[2] x; uint256[2] y; } // Verification key for SNARK struct VerifyingKey { G1Point alpha1; G2Point beta2; G2Point gamma2; G2Point delta2; G1Point[2] ic; } struct SnarkProof { G1Point a; G2Point b; G1Point c; } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; pragma abicoder v2; // OpenZeppelin v4 import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import { SnarkProof, VerifyingKey, Commitment, SNARK_SCALAR_FIELD, CIRCUIT_OUTPUTS } from "./Globals.sol"; import { Snark } from "./Snark.sol"; /** * @title Verifier * @author Railgun Contributors * @notice Verifies * @dev Functions in this contract statelessly verify proofs, nullifiers, adaptID, and * depositAmount/withdrawAmount max sizes should be checked in RailgunLogic. * Note, functions have been split up to prevent exceedign solidity stack size limit. */ contract Verifier is Initializable, OwnableUpgradeable { // Verifying keys VerifyingKey public vKeySmall; VerifyingKey public vKeyLarge; // Verification key changed events event SmallVerificationKeyChange(VerifyingKey vkey); event LargeVerificationKeyChange(VerifyingKey vkey); /** * @notice Sets initial values for verification key * @dev OpenZeppelin initializer ensures this can only be called once * @param _vKeySmall - Initial vkey value for small circuit * @param _vKeyLarge - Initial vkey value for large circuit */ function initializeVerifier(VerifyingKey calldata _vKeySmall, VerifyingKey calldata _vKeyLarge) internal initializer { // Set verification key setVKeySmall(_vKeySmall); setVKeyLarge(_vKeyLarge); } /** * @notice Hashes inputs for small proof verification * @param _adaptIDcontract - contract address to this proof to (ignored if set to 0) * @param _adaptIDparameters - hash of the contract parameters (only used to verify proof, this is verified by the * calling contract) * @param _depositAmount - deposit amount * @param _withdrawAmount - withdraw amount * @param _tokenField - token ID to use if deposit/withdraw is requested * @param _outputEthAddress - eth address to use if withdraw is requested * @param _treeNumber - merkle tree number * @param _merkleRoot - merkle root to verify against * @param _nullifiers - nullifiers of commitments * @param _commitmentsOut - output commitments * @return hash */ function hashSmallInputs( // Shared address _adaptIDcontract, uint256 _adaptIDparameters, uint256 _depositAmount, uint256 _withdrawAmount, address _tokenField, address _outputEthAddress, // Join uint256 _treeNumber, uint256 _merkleRoot, uint256[] calldata _nullifiers, // Split Commitment[CIRCUIT_OUTPUTS] calldata _commitmentsOut ) private pure returns (uint256) { // Hash adaptID into single parameter uint256[2] memory adaptIDhashPreimage; adaptIDhashPreimage[0] = uint256(uint160(_adaptIDcontract)); adaptIDhashPreimage[1] = _adaptIDparameters; uint256 adaptIDhash = uint256(sha256(abi.encodePacked(adaptIDhashPreimage))); // Hash ciphertext into single parameter uint256[24] memory cipherTextHashPreimage; // Commitment 0 cipherTextHashPreimage[0] = _commitmentsOut[0].senderPubKey[0]; cipherTextHashPreimage[1] = _commitmentsOut[0].senderPubKey[1]; cipherTextHashPreimage[2] = _commitmentsOut[0].ciphertext[0]; cipherTextHashPreimage[3] = _commitmentsOut[0].ciphertext[1]; cipherTextHashPreimage[4] = _commitmentsOut[0].ciphertext[2]; cipherTextHashPreimage[5] = _commitmentsOut[0].ciphertext[3]; cipherTextHashPreimage[6] = _commitmentsOut[0].ciphertext[4]; cipherTextHashPreimage[7] = _commitmentsOut[0].ciphertext[5]; // Commitment 1 cipherTextHashPreimage[8] = _commitmentsOut[1].senderPubKey[0]; cipherTextHashPreimage[9] = _commitmentsOut[1].senderPubKey[1]; cipherTextHashPreimage[10] = _commitmentsOut[1].ciphertext[0]; cipherTextHashPreimage[11] = _commitmentsOut[1].ciphertext[1]; cipherTextHashPreimage[12] = _commitmentsOut[1].ciphertext[2]; cipherTextHashPreimage[13] = _commitmentsOut[1].ciphertext[3]; cipherTextHashPreimage[14] = _commitmentsOut[1].ciphertext[4]; cipherTextHashPreimage[15] = _commitmentsOut[1].ciphertext[5]; // Commitment 2 cipherTextHashPreimage[16] = _commitmentsOut[2].senderPubKey[0]; cipherTextHashPreimage[17] = _commitmentsOut[2].senderPubKey[1]; cipherTextHashPreimage[18] = _commitmentsOut[2].ciphertext[0]; cipherTextHashPreimage[19] = _commitmentsOut[2].ciphertext[1]; cipherTextHashPreimage[20] = _commitmentsOut[2].ciphertext[2]; cipherTextHashPreimage[21] = _commitmentsOut[2].ciphertext[3]; cipherTextHashPreimage[22] = _commitmentsOut[2].ciphertext[4]; cipherTextHashPreimage[23] = _commitmentsOut[2].ciphertext[5]; uint256 cipherTextHash = uint256(sha256(abi.encodePacked(cipherTextHashPreimage))); uint256[13] memory inputsHashPreimage; inputsHashPreimage[0] = adaptIDhash % SNARK_SCALAR_FIELD; inputsHashPreimage[1] = _depositAmount; inputsHashPreimage[2] = _withdrawAmount; inputsHashPreimage[3] = uint256(uint160(_tokenField)); inputsHashPreimage[4] = uint256(uint160(_outputEthAddress)); inputsHashPreimage[5] = _treeNumber; inputsHashPreimage[6] = _merkleRoot; inputsHashPreimage[7] = _nullifiers[0]; inputsHashPreimage[8] = _nullifiers[1]; inputsHashPreimage[9] = _commitmentsOut[0].hash; inputsHashPreimage[10] = _commitmentsOut[1].hash; inputsHashPreimage[11] = _commitmentsOut[2].hash; inputsHashPreimage[12] = cipherTextHash % SNARK_SCALAR_FIELD; return uint256(sha256(abi.encodePacked(inputsHashPreimage))); } /** * @notice Verify proof from a small transaction * @dev This function won't check if the merkle root is stored in the contract, * the nullifiers haven't been seed before, or if the deposit or withdraw amounts aren't * larger than allowed. It only verifies the snark proof is valid and the ciphertext is bound to the * proof. * @param _proof - snark proof * @param _inputsHash - hash of inputs * @return valid */ function verifySmallProof( SnarkProof memory _proof, uint256 _inputsHash ) private view returns (bool) { return Snark.verify( vKeySmall, _proof, _inputsHash ); } /** * @notice Hashes inputs for large proof verification * @param _adaptIDcontract - contract address to this proof to (verified in RailgunLogic.sol) * @param _adaptIDparameters - hash of the contract parameters (verified by the calling contract) * @param _depositAmount - deposit amount * @param _withdrawAmount - withdraw amount * @param _tokenField - token ID to use if deposit/withdraw is requested * @param _outputEthAddress - eth address to use if withdraw is requested * @param _treeNumber - merkle tree number * @param _merkleRoot - merkle root to verify against * @param _nullifiers - nullifiers of commitments * @param _commitmentsOut - output commitments * @return hash */ function hashLargeInputs( // Shared address _adaptIDcontract, uint256 _adaptIDparameters, uint256 _depositAmount, uint256 _withdrawAmount, address _tokenField, address _outputEthAddress, // Join uint256 _treeNumber, uint256 _merkleRoot, uint256[] calldata _nullifiers, // Split Commitment[CIRCUIT_OUTPUTS] calldata _commitmentsOut ) private pure returns (uint256) { // Hash adaptID into single parameter uint256[2] memory adaptIDhashPreimage; adaptIDhashPreimage[0] = uint256(uint160(_adaptIDcontract)); adaptIDhashPreimage[1] = _adaptIDparameters; uint256 adaptIDhash = uint256(sha256(abi.encodePacked(adaptIDhashPreimage))); // Hash ciphertext into single parameter uint256[24] memory cipherTextHashPreimage; // Commitment 0 cipherTextHashPreimage[0] = _commitmentsOut[0].senderPubKey[0]; cipherTextHashPreimage[1] = _commitmentsOut[0].senderPubKey[1]; cipherTextHashPreimage[2] = _commitmentsOut[0].ciphertext[0]; cipherTextHashPreimage[3] = _commitmentsOut[0].ciphertext[1]; cipherTextHashPreimage[4] = _commitmentsOut[0].ciphertext[2]; cipherTextHashPreimage[5] = _commitmentsOut[0].ciphertext[3]; cipherTextHashPreimage[6] = _commitmentsOut[0].ciphertext[4]; cipherTextHashPreimage[7] = _commitmentsOut[0].ciphertext[5]; // Commitment 1 cipherTextHashPreimage[8] = _commitmentsOut[1].senderPubKey[0]; cipherTextHashPreimage[9] = _commitmentsOut[1].senderPubKey[1]; cipherTextHashPreimage[10] = _commitmentsOut[1].ciphertext[0]; cipherTextHashPreimage[11] = _commitmentsOut[1].ciphertext[1]; cipherTextHashPreimage[12] = _commitmentsOut[1].ciphertext[2]; cipherTextHashPreimage[13] = _commitmentsOut[1].ciphertext[3]; cipherTextHashPreimage[14] = _commitmentsOut[1].ciphertext[4]; cipherTextHashPreimage[15] = _commitmentsOut[1].ciphertext[5]; // Commitment 2 cipherTextHashPreimage[16] = _commitmentsOut[2].senderPubKey[0]; cipherTextHashPreimage[17] = _commitmentsOut[2].senderPubKey[1]; cipherTextHashPreimage[18] = _commitmentsOut[2].ciphertext[0]; cipherTextHashPreimage[19] = _commitmentsOut[2].ciphertext[1]; cipherTextHashPreimage[20] = _commitmentsOut[2].ciphertext[2]; cipherTextHashPreimage[21] = _commitmentsOut[2].ciphertext[3]; cipherTextHashPreimage[22] = _commitmentsOut[2].ciphertext[4]; cipherTextHashPreimage[23] = _commitmentsOut[2].ciphertext[5]; uint256 cipherTextHash = uint256(sha256(abi.encodePacked(cipherTextHashPreimage))); // Hash all inputs into single parameter uint256[21] memory inputsHashPreimage; inputsHashPreimage[0] = adaptIDhash % SNARK_SCALAR_FIELD; inputsHashPreimage[1] = _depositAmount; inputsHashPreimage[2] = _withdrawAmount; inputsHashPreimage[3] = uint256(uint160(_tokenField)); inputsHashPreimage[4] = uint256(uint160(_outputEthAddress)); inputsHashPreimage[5] = _treeNumber; inputsHashPreimage[6] = _merkleRoot; inputsHashPreimage[7] = _nullifiers[0]; inputsHashPreimage[8] = _nullifiers[1]; inputsHashPreimage[9] = _nullifiers[2]; inputsHashPreimage[10] = _nullifiers[3]; inputsHashPreimage[11] = _nullifiers[4]; inputsHashPreimage[12] = _nullifiers[5]; inputsHashPreimage[13] = _nullifiers[6]; inputsHashPreimage[14] = _nullifiers[7]; inputsHashPreimage[15] = _nullifiers[8]; inputsHashPreimage[16] = _nullifiers[9]; inputsHashPreimage[17] = _commitmentsOut[0].hash; inputsHashPreimage[18] = _commitmentsOut[1].hash; inputsHashPreimage[19] = _commitmentsOut[2].hash; inputsHashPreimage[20] = cipherTextHash % SNARK_SCALAR_FIELD; return uint256(sha256(abi.encodePacked(inputsHashPreimage))); } /** * @notice Verify proof from a Large transaction * @dev This function won't check if the merkle root is stored in the contract, * the nullifiers haven't been seed before, or if the deposit or withdraw amounts aren't * larger than allowed. It only verifies the snark proof is valid and the ciphertext is bound to the * proof. * @param _proof - snark proof * @param _inputsHash - hash of inputs * @return valid */ function verifyLargeProof( SnarkProof memory _proof, uint256 _inputsHash ) private view returns (bool) { return Snark.verify( vKeyLarge, _proof, _inputsHash ); } /** * @notice Verify snark proof for either Small or Large * @dev This function won't check if the merkle root is stored in the contract, * the nullifiers haven't been seed before, or if the deposit or withdraw amounts aren't * larger than allowed. It only verifies the snark proof is valid and the ciphertext is bound to the * proof. * @param _proof - snark proof * @param _adaptIDcontract - contract address to this proof to (verified in RailgunLogic.sol) * @param _adaptIDparameters - hash of the contract parameters (verified by the calling contract) * @param _depositAmount - deposit amount * @param _withdrawAmount - withdraw amount * @param _tokenField - token ID to use if deposit/withdraw is requested * @param _outputEthAddress - eth address to use if withdraw is requested * @param _treeNumber - merkle tree number * @param _merkleRoot - merkle root to verify against * @param _nullifiers - nullifiers of commitments * @param _commitmentsOut - output commitments * @return valid */ function verifyProof( // Proof SnarkProof calldata _proof, // Shared address _adaptIDcontract, uint256 _adaptIDparameters, uint256 _depositAmount, uint256 _withdrawAmount, address _tokenField, address _outputEthAddress, // Join uint256 _treeNumber, uint256 _merkleRoot, uint256[] calldata _nullifiers, // Split Commitment[CIRCUIT_OUTPUTS] calldata _commitmentsOut ) public view returns (bool) { // Check all nullifiers are valid snark field elements for (uint256 i = 0; i < _nullifiers.length; i++) { require(_nullifiers[i] < SNARK_SCALAR_FIELD, "Verifier: Nullifier not a valid field element"); } // Check all commitment hashes are valid snark field elements for (uint256 i = 0; i < _commitmentsOut.length; i++) { require(_commitmentsOut[i].hash < SNARK_SCALAR_FIELD, "Verifier: Nullifier not a valid field element"); } if (_nullifiers.length == 2) { // Hash all inputs into single parameter uint256 inputsHash = hashSmallInputs( _adaptIDcontract, _adaptIDparameters, _depositAmount, _withdrawAmount, _tokenField, _outputEthAddress, _treeNumber, _merkleRoot, _nullifiers, _commitmentsOut ); // Verify proof return verifySmallProof(_proof, inputsHash % SNARK_SCALAR_FIELD); } else if (_nullifiers.length == 10) { // Hash all inputs into single parameter uint256 inputsHash = hashLargeInputs( _adaptIDcontract, _adaptIDparameters, _depositAmount, _withdrawAmount, _tokenField, _outputEthAddress, _treeNumber, _merkleRoot, _nullifiers, _commitmentsOut ); // Verify proof return verifyLargeProof(_proof, inputsHash % SNARK_SCALAR_FIELD); } else { // Fail if nullifiers length doesn't match return false; } } /** * @notice Changes snark verification key for small transaction circuit * @param _vKey - verification key to change to */ function setVKeySmall(VerifyingKey calldata _vKey) public onlyOwner { // Copy everything manually as solidity can't copy structs to storage // Alpha vKeySmall.alpha1.x = _vKey.alpha1.x; vKeySmall.alpha1.y = _vKey.alpha1.y; // Beta vKeySmall.beta2.x[0] = _vKey.beta2.x[0]; vKeySmall.beta2.x[1] = _vKey.beta2.x[1]; vKeySmall.beta2.y[0] = _vKey.beta2.y[0]; vKeySmall.beta2.y[1] = _vKey.beta2.y[1]; // Gamma vKeySmall.gamma2.x[0] = _vKey.gamma2.x[0]; vKeySmall.gamma2.x[1] = _vKey.gamma2.x[1]; vKeySmall.gamma2.y[0] = _vKey.gamma2.y[0]; vKeySmall.gamma2.y[1] = _vKey.gamma2.y[1]; // Delta vKeySmall.delta2.x[0] = _vKey.delta2.x[0]; vKeySmall.delta2.x[1] = _vKey.delta2.x[1]; vKeySmall.delta2.y[0] = _vKey.delta2.y[0]; vKeySmall.delta2.y[1] = _vKey.delta2.y[1]; // IC vKeySmall.ic[0].x = _vKey.ic[0].x; vKeySmall.ic[0].y = _vKey.ic[0].y; vKeySmall.ic[1].x = _vKey.ic[1].x; vKeySmall.ic[1].y = _vKey.ic[1].y; // Emit change event emit SmallVerificationKeyChange(_vKey); } /** * @notice Changes snark verification key for large transaction circuit * @param _vKey - verification key to change to */ function setVKeyLarge(VerifyingKey calldata _vKey) public onlyOwner { // Copy everything manually as solidity can't copy structs to storage // Alpha vKeyLarge.alpha1.x = _vKey.alpha1.x; vKeyLarge.alpha1.y = _vKey.alpha1.y; // Beta vKeyLarge.beta2.x[0] = _vKey.beta2.x[0]; vKeyLarge.beta2.x[1] = _vKey.beta2.x[1]; vKeyLarge.beta2.y[0] = _vKey.beta2.y[0]; vKeyLarge.beta2.y[1] = _vKey.beta2.y[1]; // Gamma vKeyLarge.gamma2.x[0] = _vKey.gamma2.x[0]; vKeyLarge.gamma2.x[1] = _vKey.gamma2.x[1]; vKeyLarge.gamma2.y[0] = _vKey.gamma2.y[0]; vKeyLarge.gamma2.y[1] = _vKey.gamma2.y[1]; // Delta vKeyLarge.delta2.x[0] = _vKey.delta2.x[0]; vKeyLarge.delta2.x[1] = _vKey.delta2.x[1]; vKeyLarge.delta2.y[0] = _vKey.delta2.y[0]; vKeyLarge.delta2.y[1] = _vKey.delta2.y[1]; // IC vKeyLarge.ic[0].x = _vKey.ic[0].x; vKeyLarge.ic[0].y = _vKey.ic[0].y; vKeyLarge.ic[1].x = _vKey.ic[1].x; vKeyLarge.ic[1].y = _vKey.ic[1].y; // Emit change event emit LargeVerificationKeyChange(_vKey); } uint256[50] private __gap; } // SPDX-License-Identifier: UNLICENSED // Based on code from MACI (https://github.com/appliedzkp/maci/blob/7f36a915244a6e8f98bacfe255f8bd44193e7919/contracts/sol/IncrementalMerkleTree.sol) pragma solidity ^0.8.0; pragma abicoder v2; // OpenZeppelin v4 import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import { Commitment, SNARK_SCALAR_FIELD, CIRCUIT_OUTPUTS, CIPHERTEXT_WORDS } from "./Globals.sol"; import { PoseidonT3, PoseidonT6 } from "./Poseidon.sol"; /** * @title Commitments * @author Railgun Contributors * @notice Batch Incremental Merkle Tree for commitments * @dev Publically accessible functions to be put in RailgunLogic * Relevent external contract calls should be in those functions, not here */ contract Commitments is Initializable { // NOTE: The order of instantiation MUST stay the same across upgrades // add new variables to the bottom of the list and decrement the __gap // variable at the end of this file // See https://docs.openzeppelin.com/learn/upgrading-smart-contracts#upgrading // Commitment added event event NewCommitment( uint256 indexed treeNumber, uint256 indexed position, uint256 hash, uint256[CIPHERTEXT_WORDS] ciphertext, // Ciphertext order: iv, recipient pubkey (2 x uint256), random, amount, token uint256[2] senderPubKey ); // Generated commitment added event event NewGeneratedCommitment( uint256 indexed treeNumber, uint256 indexed position, uint256 hash, uint256[2] pubkey, uint256 random, uint256 amount, address token ); // Commitment nullifiers mapping(uint256 => bool) public nullifiers; // The tree depth uint256 private constant TREE_DEPTH = 16; // Max number of leaves that can be inserted in a single batch uint256 internal constant MAX_BATCH_SIZE = CIRCUIT_OUTPUTS; // Tree zero value uint256 private constant ZERO_VALUE = uint256(keccak256("Railgun")) % SNARK_SCALAR_FIELD; // Next leaf index (number of inserted leaves in the current tree) uint256 private nextLeafIndex = 0; // The Merkle root uint256 public merkleRoot; // Store new tree root to quickly migrate to a new tree uint256 private newTreeRoot; // Tree number uint256 private treeNumber; // The Merkle path to the leftmost leaf upon initialisation. It *should // not* be modified after it has been set by the initialize function. // Caching these values is essential to efficient appends. uint256[TREE_DEPTH] private zeros; // Right-most elements at each level // Used for efficient upodates of the merkle tree uint256[TREE_DEPTH] private filledSubTrees; // Whether the contract has already seen a particular Merkle tree root // treeNumber => root => seen mapping(uint256 => mapping(uint256 => bool)) public rootHistory; /** * @notice Calculates initial values for Merkle Tree * @dev OpenZeppelin initializer ensures this can only be called once */ function initializeCommitments() internal initializer { /* To initialise the Merkle tree, we need to calculate the Merkle root assuming that each leaf is the zero value. H(H(a,b), H(c,d)) / \ H(a,b) H(c,d) / \ / \ a b c d `zeros` and `filledSubTrees` will come in handy later when we do inserts or updates. e.g when we insert a value in index 1, we will need to look up values from those arrays to recalculate the Merkle root. */ // Calculate zero values zeros[0] = ZERO_VALUE; // Store the current zero value for the level we just calculated it for uint256 currentZero = ZERO_VALUE; // Loop through each level for (uint256 i = 0; i < TREE_DEPTH; i++) { // Push it to zeros array zeros[i] = currentZero; // Calculate the zero value for this level currentZero = hashLeftRight(currentZero, currentZero); } // Set merkle root and store root to quickly retrieve later newTreeRoot = merkleRoot = currentZero; rootHistory[treeNumber][currentZero] = true; } /** * @notice Hash 2 uint256 values * @param _left - Left side of hash * @param _right - Right side of hash * @return hash result */ function hashLeftRight(uint256 _left, uint256 _right) private pure returns (uint256) { return PoseidonT3.poseidon([ _left, _right ]); } /** * @notice Calculates initial values for Merkle Tree * @dev OpenZeppelin initializer ensures this can only be called once. * Note: this function INTENTIONALLY causes side effects to save on gas. * _leafHashes and _count should never be reused. * @param _leafHashes - array of leaf hashes to be added to the merkle tree * @param _count - number of leaf hashes to be added to the merkle tree */ function insertLeaves(uint256[MAX_BATCH_SIZE] memory _leafHashes, uint256 _count) private { /* Loop through leafHashes at each level, if the leaf is on the left (index is even) then hash with zeros value and update subtree on this level, if the leaf is on the right (index is odd) then hash with subtree value. After calculating each hash push to relevent spot on leafHashes array. For gas efficiency we reuse the same array and use the count variable to loop to the right index each time. Example of updating a tree of depth 4 with elements 13, 14, and 15 [1,7,15] {1} 1 | [3,7,15] {1} 2-------------------3 | | [6,7,15] {2} 4---------5 6---------7 / \ / \ / \ / \ [13,14,15] {3} 08 09 10 11 12 13 14 15 [] = leafHashes array {} = count variable */ // Current index is the index at each level to insert the hash uint256 levelInsertionIndex = nextLeafIndex; // Update nextLeafIndex nextLeafIndex += _count; // Variables for starting point at next tree level uint256 nextLevelHashIndex; uint256 nextLevelStartIndex; // Loop through each level of the merkle tree and update for (uint256 level = 0; level < TREE_DEPTH; level++) { // Calculate the index to start at for the next level // >> is equivilent to / 2 rounded down nextLevelStartIndex = levelInsertionIndex >> 1; for (uint256 insertionElement = 0; insertionElement < _count; insertionElement++) { uint256 left; uint256 right; // Calculate left/right values if (levelInsertionIndex % 2 == 0) { // Leaf hash we're updating with is on the left left = _leafHashes[insertionElement]; right = zeros[level]; // We've created a new subtree at this level, update filledSubTrees[level] = _leafHashes[insertionElement]; } else { // Leaf hash we're updating with is on the right left = filledSubTrees[level]; right = _leafHashes[insertionElement]; } // Calculate index to insert hash into leafHashes[] // >> is equivilent to / 2 rounded down nextLevelHashIndex = (levelInsertionIndex >> 1) - nextLevelStartIndex; // Calculate the hash for the next level _leafHashes[nextLevelHashIndex] = hashLeftRight(left, right); // Increment level insertion index levelInsertionIndex++; } // Get starting levelInsertionIndex value for next level levelInsertionIndex = nextLevelStartIndex; // Get count of elements for next level _count = nextLevelHashIndex + 1; } // Update the Merkle tree root merkleRoot = _leafHashes[0]; rootHistory[treeNumber][merkleRoot] = true; } /** * @notice Creates new merkle tree */ function newTree() internal { // Restore merkleRoot to newTreeRoot merkleRoot = newTreeRoot; // Existing values in filledSubtrees will never be used so overwriting them is unnecessary // Reset next leaf index to 0 nextLeafIndex = 0; // Increment tree number treeNumber++; } /** * @notice Adds commitments to tree and emits events * @dev MAX_BATCH_SIZE trades off gas cost and batch size * @param _commitments - array of commitments to be added to merkle tree */ function addCommitments(Commitment[CIRCUIT_OUTPUTS] calldata _commitments) internal { // Create new tree if existing tree can't contain outputs // We insert all new commitment into a new tree to ensure they can be spent in the same transaction if ((nextLeafIndex + _commitments.length) > (uint256(2) ** TREE_DEPTH)) { newTree(); } // Build insertion array uint256[MAX_BATCH_SIZE] memory insertionLeaves; for (uint256 i = 0; i < _commitments.length; i++) { // Throw if leaf is invalid require( _commitments[i].hash < SNARK_SCALAR_FIELD, "Commitments: context.leafHash[] entries must be < SNARK_SCALAR_FIELD" ); // Push hash to insertion array insertionLeaves[i] = _commitments[i].hash; // Emit CommitmentAdded events (for wallets) for all the commitments emit NewCommitment(treeNumber, nextLeafIndex + i, _commitments[i].hash, _commitments[i].ciphertext, _commitments[i].senderPubKey); } // Push the leaf hashes into the Merkle tree insertLeaves(insertionLeaves, CIRCUIT_OUTPUTS); } /** * @notice Creates a commitment hash from supplied values and adds to tree * @dev This is for DeFi integrations where the resulting number of tokens to be added * can't be known in advance (eg. AMM trade where transaction ordering could cause toekn amounts to change) * @param _pubkey - pubkey of commitment * @param _random - randomness component of commitment * @param _amount - amount of commitment * @param _token - token ID of commitment */ function addGeneratedCommitment( uint256[2] memory _pubkey, uint256 _random, uint256 _amount, address _token ) internal { // Create new tree if current one can't contain existing tree // We insert all new commitment into a new tree to ensure they can be spent in the same transaction if ((nextLeafIndex + 1) >= (2 ** TREE_DEPTH)) { newTree(); } // Calculate commitment hash uint256 hash = PoseidonT6.poseidon([ _pubkey[0], _pubkey[1], _random, _amount, uint256(uint160(_token)) ]); // Emit GeneratedCommitmentAdded events (for wallets) for the commitments emit NewGeneratedCommitment(treeNumber, nextLeafIndex, hash, _pubkey, _random, _amount, _token); // Push the leaf hash into the Merkle tree uint256[CIRCUIT_OUTPUTS] memory insertionLeaves; insertionLeaves[0] = hash; insertLeaves(insertionLeaves, 1); } uint256[50] private __gap; } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; pragma abicoder v2; // OpenZeppelin v4 import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; /** * @title Token Whitelist * @author Railgun Contributors * @notice Whitelist of tokens allowed to be deposited in Railgun * @dev Tokens on this whitelist can be deposited to railgun. * Tokens can be removed from this whitelist but will still be transferrable * internally (as internal transactions have a shielded token ID) and * withdrawable (to prevent user funds from being locked) */ contract TokenWhitelist is Initializable, OwnableUpgradeable { // Events for offchain building of whitelist index event TokenListing(address indexed token); event TokeDelisting(address indexed token); // NOTE: The order of instantiation MUST stay the same across upgrades // add new variables to the bottom of the list and decrement the __gap // variable at the end of this file // See https://docs.openzeppelin.com/learn/upgrading-smart-contracts#upgrading mapping(address => bool) public tokenWhitelist; /** * @notice Adds initial set of tokens to whitelist. * @dev OpenZeppelin initializer ensures this can only be called once * @param _tokens - List of tokens to add to whitelist */ function initializeTokenWhitelist(address[] calldata _tokens) internal initializer { // Push initial token whitelist to map addToWhitelist(_tokens); } /** * @notice Adds tokens to whitelist, only callable by owner (governance contract) * @dev This function will ignore tokens that are already in the whitelist * no events will be emitted in this case * @param _tokens - List of tokens to add to whitelist */ function addToWhitelist(address[] calldata _tokens) public onlyOwner { // Loop through token array for (uint i = 0; i < _tokens.length; i++) { // Don't do anything if the token is already whitelisted if (!tokenWhitelist[_tokens[i]]) { // Set token address in whitelist map to true tokenWhitelist[_tokens[i]] = true; // Emit event for building index of whitelisted tokens offchain emit TokenListing(_tokens[i]); } } } /** * @notice Removes token from whitelist, only callable by owner (governance contract) * @dev This function will ignore tokens that aren't in the whitelist * no events will be emitted in this case * @param _tokens - List of tokens to remove from whitelist */ function removeFromWhitelist(address[] calldata _tokens) external onlyOwner { // Loop through token array for (uint i = 0; i < _tokens.length; i++) { // Don't do anything if the token isn't whitelisted if (tokenWhitelist[_tokens[i]]) { // Set token address in whitelist map to false (default value) delete tokenWhitelist[_tokens[i]]; // Emit event for building index of whitelisted tokens offchain emit TokeDelisting(_tokens[i]); } } } uint256[50] private __gap; } // 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; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; pragma abicoder v2; import { G1Point, G2Point, VerifyingKey, SnarkProof, SNARK_SCALAR_FIELD } from "./Globals.sol"; library Snark { uint256 private constant PRIME_Q = 21888242871839275222246405745257275088696311157297823662689037894645226208583; uint256 private constant PAIRING_INPUT_SIZE = 24; uint256 private constant PAIRING_INPUT_WIDTH = 768; // PAIRING_INPUT_SIZE * 32 /** * @notice Computes the negation of point p * @dev The negation of p, i.e. p.plus(p.negate()) should be zero. * @return result */ function negate(G1Point memory p) internal pure returns (G1Point memory) { if (p.x == 0 && p.y == 0) return G1Point(0, 0); // check for valid points y^2 = x^3 +3 % PRIME_Q uint256 rh = mulmod(p.x, p.x, PRIME_Q); //x^2 rh = mulmod(rh, p.x, PRIME_Q); //x^3 rh = addmod(rh, 3, PRIME_Q); //x^3 + 3 uint256 lh = mulmod(p.y, p.y, PRIME_Q); //y^2 require(lh == rh, "Snark: "); return G1Point(p.x, PRIME_Q - (p.y % PRIME_Q)); } /** * @notice Adds 2 G1 points * @return result */ function add(G1Point memory p1, G1Point memory p2) internal view returns (G1Point memory) { // Format inputs uint256[4] memory input; input[0] = p1.x; input[1] = p1.y; input[2] = p2.x; input[3] = p2.y; // Setup output variables bool success; G1Point memory result; // Add points // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(sub(gas(), 2000), 6, input, 0x80, result, 0x40) } // Check if operation succeeded require(success, "Pairing: Add Failed"); return result; } /** * @notice Scalar multiplies two G1 points p, s * @dev The product of a point on G1 and a scalar, i.e. * p == p.scalar_mul(1) and p.plus(p) == p.scalar_mul(2) for all * points p. */ function scalarMul(G1Point memory p, uint256 s) internal view returns (G1Point memory r) { uint256[3] memory input; input[0] = p.x; input[1] = p.y; input[2] = s; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(sub(gas(), 2000), 7, input, 0x60, r, 0x40) } // Check multiplication succeeded require(success, "Pairing: Scalar Multiplication Failed"); } /** * @notice Performs pairing check on points * @dev The result of computing the pairing check * e(p1[0], p2[0]) * .... * e(p1[n], p2[n]) == 1 * For example, * pairing([P1(), P1().negate()], [P2(), P2()]) should return true. * @return if pairing check passed */ function pairing( G1Point memory _a1, G2Point memory _a2, G1Point memory _b1, G2Point memory _b2, G1Point memory _c1, G2Point memory _c2, G1Point memory _d1, G2Point memory _d2 ) internal view returns (bool) { uint256[PAIRING_INPUT_SIZE] memory input = [ _a1.x, _a1.y, _a2.x[0], _a2.x[1], _a2.y[0], _a2.y[1], _b1.x, _b1.y, _b2.x[0], _b2.x[1], _b2.y[0], _b2.y[1], _c1.x, _c1.y, _c2.x[0], _c2.x[1], _c2.y[0], _c2.y[1], _d1.x, _d1.y, _d2.x[0], _d2.x[1], _d2.y[0], _d2.y[1] ]; uint256[1] memory out; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall( sub(gas(), 2000), 8, input, PAIRING_INPUT_WIDTH, out, 0x20 ) } // Check if operation succeeded require(success, "Pairing: Pairing Verification Failed"); return out[0] != 0; } /** * @notice Verifies snark proof against proving key * @param _vk - Verification Key * @param _proof - snark proof * @param _input - hash of inputs */ function verify( VerifyingKey memory _vk, SnarkProof memory _proof, uint256 _input ) internal view returns (bool) { // Compute the linear combination vkX G1Point memory vkX = G1Point(0, 0); // Make sure input is less than SNARK_SCALAR_FIELD require(_input < SNARK_SCALAR_FIELD, "Snark: Input gte SNARK_SCALAR_FIELD"); // Compute vkX vkX = add(vkX, scalarMul(_vk.ic[1], _input)); vkX = add(vkX, _vk.ic[0]); // Verify pairing and return return pairing( negate(_proof.a), _proof.b, _vk.alpha1, _vk.beta2, vkX, _vk.gamma2, _proof.c, _vk.delta2 ); } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; pragma abicoder v2; /* Functions here are stubs for the solidity compiler to generate the right interface. The deployed library is generated bytecode from the circomlib toolchain */ library PoseidonT3 { // solhint-disable-next-line no-empty-blocks function poseidon(uint256[2] memory input) public pure returns (uint256) {} } library PoseidonT6 { // solhint-disable-next-line no-empty-blocks function poseidon(uint256[5] memory input) public pure returns (uint256) {} }
solhint-disable-next-line no-empty-blocks
library PoseidonT6 { function poseidon(uint256[5] memory input) public pure returns (uint256) {} }
6,141,309
[ 1, 18281, 11317, 17, 8394, 17, 4285, 17, 1369, 1158, 17, 5531, 17, 7996, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 453, 2584, 350, 265, 56, 26, 288, 203, 225, 445, 26948, 350, 265, 12, 11890, 5034, 63, 25, 65, 3778, 810, 13, 1071, 16618, 1135, 261, 11890, 5034, 13, 2618, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0-or-later // hevm: flattened sources of contracts/LoanFactory.sol pragma solidity =0.6.11 >=0.6.0 <0.8.0 >=0.6.2 <0.8.0; ////// contracts/interfaces/ICollateralLocker.sol /* pragma solidity 0.6.11; */ interface ICollateralLocker { function collateralAsset() external view returns (address); function loan() external view returns (address); function pull(address, uint256) external; } ////// contracts/interfaces/ICollateralLockerFactory.sol /* pragma solidity 0.6.11; */ interface ICollateralLockerFactory { function owner(address) external view returns (address); function isLocker(address) external view returns (bool); function factoryType() external view returns (uint8); function newLocker(address) external returns (address); } ////// lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol /* pragma solidity >=0.6.0 <0.8.0; */ /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } ////// contracts/interfaces/IERC20Details.sol /* pragma solidity 0.6.11; */ /* import "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol"; */ interface IERC20Details is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint256); } ////// contracts/interfaces/IFundingLocker.sol /* pragma solidity 0.6.11; */ interface IFundingLocker { function liquidityAsset() external view returns (address); function loan() external view returns (address); function pull(address, uint256) external; function drain() external; } ////// contracts/interfaces/IFundingLockerFactory.sol /* pragma solidity 0.6.11; */ interface IFundingLockerFactory { function owner(address) external view returns (address); function isLocker(address) external view returns (bool); function factoryType() external view returns (uint8); function newLocker(address) external returns (address); } ////// contracts/interfaces/ILateFeeCalc.sol /* pragma solidity 0.6.11; */ interface ILateFeeCalc { function calcType() external view returns (uint8); function name() external view returns (bytes32); function lateFee() external view returns (uint256); function getLateFee(uint256) external view returns (uint256); } ////// contracts/interfaces/ILiquidityLocker.sol /* pragma solidity 0.6.11; */ interface ILiquidityLocker { function pool() external view returns (address); function liquidityAsset() external view returns (address); function transfer(address, uint256) external; function fundLoan(address, address, uint256) external; } ////// contracts/interfaces/ILoanFactory.sol /* pragma solidity 0.6.11; */ interface ILoanFactory { function CL_FACTORY() external view returns (uint8); function FL_FACTORY() external view returns (uint8); function INTEREST_CALC_TYPE() external view returns (uint8); function LATEFEE_CALC_TYPE() external view returns (uint8); function PREMIUM_CALC_TYPE() external view returns (uint8); function globals() external view returns (address); function loansCreated() external view returns (uint256); function loans(uint256) external view returns (address); function isLoan(address) external view returns (bool); function loanFactoryAdmins(address) external view returns (bool); function setGlobals(address) external; function createLoan(address, address, address, address, uint256[5] memory, address[3] memory) external returns (address); function setLoanFactoryAdmin(address, bool) external; function pause() external; function unpause() external; } ////// contracts/interfaces/IMapleGlobals.sol /* pragma solidity 0.6.11; */ interface IMapleGlobals { function pendingGovernor() external view returns (address); function governor() external view returns (address); function globalAdmin() external view returns (address); function mpl() external view returns (address); function mapleTreasury() external view returns (address); function isValidBalancerPool(address) external view returns (bool); function treasuryFee() external view returns (uint256); function investorFee() external view returns (uint256); function defaultGracePeriod() external view returns (uint256); function fundingPeriod() external view returns (uint256); function swapOutRequired() external view returns (uint256); function isValidLiquidityAsset(address) external view returns (bool); function isValidCollateralAsset(address) external view returns (bool); function isValidPoolDelegate(address) external view returns (bool); function validCalcs(address) external view returns (bool); function isValidCalc(address, uint8) external view returns (bool); function getLpCooldownParams() external view returns (uint256, uint256); function isValidLoanFactory(address) external view returns (bool); function isValidSubFactory(address, address, uint8) external view returns (bool); function isValidPoolFactory(address) external view returns (bool); function getLatestPrice(address) external view returns (uint256); function defaultUniswapPath(address, address) external view returns (address); function minLoanEquity() external view returns (uint256); function maxSwapSlippage() external view returns (uint256); function protocolPaused() external view returns (bool); function stakerCooldownPeriod() external view returns (uint256); function lpCooldownPeriod() external view returns (uint256); function stakerUnstakeWindow() external view returns (uint256); function lpWithdrawWindow() external view returns (uint256); function oracleFor(address) external view returns (address); function validSubFactories(address, address) external view returns (bool); function setStakerCooldownPeriod(uint256) external; function setLpCooldownPeriod(uint256) external; function setStakerUnstakeWindow(uint256) external; function setLpWithdrawWindow(uint256) external; function setMaxSwapSlippage(uint256) external; function setGlobalAdmin(address) external; function setValidBalancerPool(address, bool) external; function setProtocolPause(bool) external; function setValidPoolFactory(address, bool) external; function setValidLoanFactory(address, bool) external; function setValidSubFactory(address, address, bool) external; function setDefaultUniswapPath(address, address, address) external; function setPoolDelegateAllowlist(address, bool) external; function setCollateralAsset(address, bool) external; function setLiquidityAsset(address, bool) external; function setCalc(address, bool) external; function setInvestorFee(uint256) external; function setTreasuryFee(uint256) external; function setMapleTreasury(address) external; function setDefaultGracePeriod(uint256) external; function setMinLoanEquity(uint256) external; function setFundingPeriod(uint256) external; function setSwapOutRequired(uint256) external; function setPriceOracle(address, address) external; function setPendingGovernor(address) external; function acceptGovernor() external; } ////// contracts/token/interfaces/IBaseFDT.sol /* pragma solidity 0.6.11; */ interface IBaseFDT { /** @dev Returns the total amount of funds a given address is able to withdraw currently. @param owner Address of FDT holder. @return A uint256 representing the available funds for a given account. */ function withdrawableFundsOf(address owner) external view returns (uint256); /** @dev Withdraws all available funds for a FDT holder. */ function withdrawFunds() external; /** @dev This event emits when new funds are distributed. @param by The address of the sender that distributed funds. @param fundsDistributed The amount of funds received for distribution. */ event FundsDistributed(address indexed by, uint256 fundsDistributed); /** @dev This event emits when distributed funds are withdrawn by a token holder. @param by The address of the receiver of funds. @param fundsWithdrawn The amount of funds that were withdrawn. @param totalWithdrawn The total amount of funds that were withdrawn. */ event FundsWithdrawn(address indexed by, uint256 fundsWithdrawn, uint256 totalWithdrawn); } ////// contracts/token/interfaces/IBasicFDT.sol /* pragma solidity 0.6.11; */ /* import "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol"; */ /* import "./IBaseFDT.sol"; */ interface IBasicFDT is IBaseFDT, IERC20 { event PointsPerShareUpdated(uint256); event PointsCorrectionUpdated(address indexed, int256); function withdrawnFundsOf(address) external view returns (uint256); function accumulativeFundsOf(address) external view returns (uint256); function updateFundsReceived() external; } ////// contracts/token/interfaces/IExtendedFDT.sol /* pragma solidity 0.6.11; */ /* import "./IBasicFDT.sol"; */ interface IExtendedFDT is IBasicFDT { event LossesPerShareUpdated(uint256); event LossesCorrectionUpdated(address indexed, int256); event LossesDistributed(address indexed, uint256); event LossesRecognized(address indexed, uint256, uint256); function lossesPerShare() external view returns (uint256); function recognizableLossesOf(address) external view returns (uint256); function recognizedLossesOf(address) external view returns (uint256); function accumulativeLossesOf(address) external view returns (uint256); function updateLossesReceived() external; } ////// contracts/token/interfaces/IPoolFDT.sol /* pragma solidity 0.6.11; */ /* import "./IExtendedFDT.sol"; */ interface IPoolFDT is IExtendedFDT { function interestSum() external view returns (uint256); function poolLosses() external view returns (uint256); function interestBalance() external view returns (uint256); function lossesBalance() external view returns (uint256); } ////// contracts/interfaces/IPool.sol /* pragma solidity 0.6.11; */ /* import "../token/interfaces/IPoolFDT.sol"; */ interface IPool is IPoolFDT { function poolDelegate() external view returns (address); function poolAdmins(address) external view returns (bool); function deposit(uint256) external; function increaseCustodyAllowance(address, uint256) external; function transferByCustodian(address, address, uint256) external; function poolState() external view returns (uint256); function deactivate() external; function finalize() external; function claim(address, address) external returns (uint256[7] memory); function setLockupPeriod(uint256) external; function setStakingFee(uint256) external; function setPoolAdmin(address, bool) external; function fundLoan(address, address, uint256) external; function withdraw(uint256) external; function superFactory() external view returns (address); function triggerDefault(address, address) external; function isPoolFinalized() external view returns (bool); function setOpenToPublic(bool) external; function setAllowList(address, bool) external; function allowedLiquidityProviders(address) external view returns (bool); function openToPublic() external view returns (bool); function intendToWithdraw() external; function DL_FACTORY() external view returns (uint8); function liquidityAsset() external view returns (address); function liquidityLocker() external view returns (address); function stakeAsset() external view returns (address); function stakeLocker() external view returns (address); function stakingFee() external view returns (uint256); function delegateFee() external view returns (uint256); function principalOut() external view returns (uint256); function liquidityCap() external view returns (uint256); function lockupPeriod() external view returns (uint256); function depositDate(address) external view returns (uint256); function debtLockers(address, address) external view returns (address); function withdrawCooldown(address) external view returns (uint256); function setLiquidityCap(uint256) external; function cancelWithdraw() external; function reclaimERC20(address) external; function BPTVal(address, address, address, address) external view returns (uint256); function isDepositAllowed(uint256) external view returns (bool); function getInitialStakeRequirements() external view returns (uint256, uint256, bool, uint256, uint256); } ////// contracts/interfaces/IPoolFactory.sol /* pragma solidity 0.6.11; */ interface IPoolFactory { function LL_FACTORY() external view returns (uint8); function SL_FACTORY() external view returns (uint8); function poolsCreated() external view returns (uint256); function globals() external view returns (address); function pools(uint256) external view returns (address); function isPool(address) external view returns (bool); function poolFactoryAdmins(address) external view returns (bool); function setGlobals(address) external; function createPool(address, address, address, address, uint256, uint256, uint256) external returns (address); function setPoolFactoryAdmin(address, bool) external; function pause() external; function unpause() external; } ////// contracts/interfaces/IPremiumCalc.sol /* pragma solidity 0.6.11; */ interface IPremiumCalc { function calcType() external view returns (uint8); function name() external view returns (bytes32); function premiumFee() external view returns (uint256); function getPremiumPayment(address) external view returns (uint256, uint256, uint256); } ////// contracts/interfaces/IRepaymentCalc.sol /* pragma solidity 0.6.11; */ interface IRepaymentCalc { function calcType() external view returns (uint8); function name() external view returns (bytes32); function getNextPayment(address) external view returns (uint256, uint256, uint256); } ////// contracts/interfaces/IUniswapRouter.sol /* pragma solidity 0.6.11; */ interface IUniswapRouter { function swapExactTokensForTokens( 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 WETH() external pure returns (address); } ////// lib/openzeppelin-contracts/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; } } ////// contracts/library/Util.sol /* pragma solidity 0.6.11; */ /* import "../interfaces/IERC20Details.sol"; */ /* import "../interfaces/IMapleGlobals.sol"; */ /* import "lib/openzeppelin-contracts/contracts/math/SafeMath.sol"; */ /// @title Util is a library that contains utility functions. library Util { using SafeMath for uint256; /** @dev Calculates the minimum amount from a swap (adjustable for price slippage). @param globals Instance of a MapleGlobals. @param fromAsset Address of ERC-20 that will be swapped. @param toAsset Address of ERC-20 that will returned from swap. @param swapAmt Amount of `fromAsset` to be swapped. @return Expected amount of `toAsset` to receive from swap based on current oracle prices. */ function calcMinAmount(IMapleGlobals globals, address fromAsset, address toAsset, uint256 swapAmt) external view returns (uint256) { return swapAmt .mul(globals.getLatestPrice(fromAsset)) // Convert from `fromAsset` value. .mul(10 ** IERC20Details(toAsset).decimals()) // Convert to `toAsset` decimal precision. .div(globals.getLatestPrice(toAsset)) // Convert to `toAsset` value. .div(10 ** IERC20Details(fromAsset).decimals()); // Convert from `fromAsset` decimal precision. } } ////// lib/openzeppelin-contracts/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); } } } } ////// lib/openzeppelin-contracts/contracts/token/ERC20/SafeERC20.sol /* 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"); } } } ////// contracts/library/LoanLib.sol /* pragma solidity 0.6.11; */ /* import "../interfaces/ICollateralLocker.sol"; */ /* import "../interfaces/ICollateralLockerFactory.sol"; */ /* import "../interfaces/IERC20Details.sol"; */ /* import "../interfaces/IFundingLocker.sol"; */ /* import "../interfaces/IFundingLockerFactory.sol"; */ /* import "../interfaces/IMapleGlobals.sol"; */ /* import "../interfaces/ILateFeeCalc.sol"; */ /* import "../interfaces/ILoanFactory.sol"; */ /* import "../interfaces/IPremiumCalc.sol"; */ /* import "../interfaces/IRepaymentCalc.sol"; */ /* import "../interfaces/IUniswapRouter.sol"; */ /* import "../library/Util.sol"; */ /* import "lib/openzeppelin-contracts/contracts/token/ERC20/SafeERC20.sol"; */ /* import "lib/openzeppelin-contracts/contracts/math/SafeMath.sol"; */ /// @title LoanLib is a library of utility functions used by Loan. library LoanLib { using SafeMath for uint256; using SafeERC20 for IERC20; address public constant UNISWAP_ROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; /********************************/ /*** Lender Utility Functions ***/ /********************************/ /** @dev Performs sanity checks on the data passed in Loan constructor. @param globals Instance of a MapleGlobals. @param liquidityAsset Contract address of the Liquidity Asset. @param collateralAsset Contract address of the Collateral Asset. @param specs Contains specifications for this Loan. */ function loanSanityChecks(IMapleGlobals globals, address liquidityAsset, address collateralAsset, uint256[5] calldata specs) external view { require(globals.isValidLiquidityAsset(liquidityAsset), "L:INVALID_LIQ_ASSET"); require(globals.isValidCollateralAsset(collateralAsset), "L:INVALID_COL_ASSET"); require(specs[2] != uint256(0), "L:ZERO_PID"); require(specs[1].mod(specs[2]) == uint256(0), "L:INVALID_TERM_DAYS"); require(specs[3] > uint256(0), "L:ZERO_REQUEST_AMT"); } /** @dev Returns capital to Lenders, if the Borrower has not drawn down the Loan past the grace period. @param liquidityAsset IERC20 of the Liquidity Asset. @param fundingLocker Address of FundingLocker. @param createdAt Timestamp of Loan instantiation. @param fundingPeriod Duration of the funding period, after which funds can be reclaimed. @return excessReturned Amount of Liquidity Asset that was returned to the Loan from the FundingLocker. */ function unwind(IERC20 liquidityAsset, address fundingLocker, uint256 createdAt, uint256 fundingPeriod) external returns (uint256 excessReturned) { // Only callable if Loan funding period has elapsed. require(block.timestamp > createdAt.add(fundingPeriod), "L:STILL_FUNDING_PERIOD"); // Account for existing balance in Loan. uint256 preBal = liquidityAsset.balanceOf(address(this)); // Drain funding from FundingLocker, transfers all the Liquidity Asset to this Loan. IFundingLocker(fundingLocker).drain(); return liquidityAsset.balanceOf(address(this)).sub(preBal); } /** @dev Liquidates a Borrower's collateral, via Uniswap, when a default is triggered. Only the Loan can call this function. @param collateralAsset IERC20 of the Collateral Asset. @param liquidityAsset Address of Liquidity Asset. @param superFactory Factory that instantiated Loan. @param collateralLocker Address of CollateralLocker. @return amountLiquidated Amount of Collateral Asset that was liquidated. @return amountRecovered Amount of Liquidity Asset that was returned to the Loan from the liquidation. */ function liquidateCollateral( IERC20 collateralAsset, address liquidityAsset, address superFactory, address collateralLocker ) external returns ( uint256 amountLiquidated, uint256 amountRecovered ) { // Get the liquidation amount from CollateralLocker. uint256 liquidationAmt = collateralAsset.balanceOf(address(collateralLocker)); // Pull the Collateral Asset from CollateralLocker. ICollateralLocker(collateralLocker).pull(address(this), liquidationAmt); if (address(collateralAsset) == liquidityAsset || liquidationAmt == uint256(0)) return (liquidationAmt, liquidationAmt); collateralAsset.safeApprove(UNISWAP_ROUTER, uint256(0)); collateralAsset.safeApprove(UNISWAP_ROUTER, liquidationAmt); IMapleGlobals globals = _globals(superFactory); // Get minimum amount of loan asset get after swapping collateral asset. uint256 minAmount = Util.calcMinAmount(globals, address(collateralAsset), liquidityAsset, liquidationAmt); // Generate Uniswap path. address uniswapAssetForPath = globals.defaultUniswapPath(address(collateralAsset), liquidityAsset); bool middleAsset = uniswapAssetForPath != liquidityAsset && uniswapAssetForPath != address(0); address[] memory path = new address[](middleAsset ? 3 : 2); path[0] = address(collateralAsset); path[1] = middleAsset ? uniswapAssetForPath : liquidityAsset; if (middleAsset) path[2] = liquidityAsset; // Swap collateralAsset for Liquidity Asset. uint256[] memory returnAmounts = IUniswapRouter(UNISWAP_ROUTER).swapExactTokensForTokens( liquidationAmt, minAmount.sub(minAmount.mul(globals.maxSwapSlippage()).div(10_000)), path, address(this), block.timestamp ); return(returnAmounts[0], returnAmounts[path.length - 1]); } /**********************************/ /*** Governor Utility Functions ***/ /**********************************/ /** @dev Transfers any locked funds to the Governor. Only the Governor can call this function. @param token Address of the token to be reclaimed. @param liquidityAsset Address of token that is used by the loan for drawdown and payments. @param globals Instance of a MapleGlobals. */ function reclaimERC20(address token, address liquidityAsset, IMapleGlobals globals) external { require(msg.sender == globals.governor(), "L:NOT_GOV"); require(token != liquidityAsset && token != address(0), "L:INVALID_TOKEN"); IERC20(token).safeTransfer(msg.sender, IERC20(token).balanceOf(address(this))); } /************************/ /*** Getter Functions ***/ /************************/ /** @dev Returns if a default can be triggered. @param nextPaymentDue Timestamp of when payment is due. @param defaultGracePeriod Amount of time after the next payment is due that a Borrower has before a liquidation can occur. @param superFactory Factory that instantiated Loan. @param balance LoanFDT balance of account trying to trigger a default. @param totalSupply Total supply of LoanFDT. @return Boolean indicating if default can be triggered. */ function canTriggerDefault(uint256 nextPaymentDue, uint256 defaultGracePeriod, address superFactory, uint256 balance, uint256 totalSupply) external view returns (bool) { bool pastDefaultGracePeriod = block.timestamp > nextPaymentDue.add(defaultGracePeriod); // Check if the Loan is past the default grace period and that the account triggering the default has a percentage of total LoanFDTs // that is greater than the minimum equity needed (specified in globals) return pastDefaultGracePeriod && balance >= ((totalSupply * _globals(superFactory).minLoanEquity()) / 10_000); } /** @dev Returns information on next payment amount. @param repaymentCalc Address of RepaymentCalc. @param nextPaymentDue Timestamp of when payment is due. @param lateFeeCalc Address of LateFeeCalc. @return total Entitled total amount needed to be paid in the next payment (Principal + Interest only when the next payment is last payment of the Loan). @return principal Entitled principal amount needed to be paid in the next payment. @return interest Entitled interest amount needed to be paid in the next payment. @return _nextPaymentDue Payment Due Date. @return paymentLate Whether payment is late. */ function getNextPayment( address repaymentCalc, uint256 nextPaymentDue, address lateFeeCalc ) external view returns ( uint256 total, uint256 principal, uint256 interest, uint256 _nextPaymentDue, bool paymentLate ) { _nextPaymentDue = nextPaymentDue; // Get next payment amounts from RepaymentCalc. (total, principal, interest) = IRepaymentCalc(repaymentCalc).getNextPayment(address(this)); paymentLate = block.timestamp > _nextPaymentDue; // If payment is late, add late fees. if (paymentLate) { uint256 lateFee = ILateFeeCalc(lateFeeCalc).getLateFee(interest); total = total.add(lateFee); interest = interest.add(lateFee); } } /** @dev Returns information on full payment amount. @param repaymentCalc Address of RepaymentCalc. @param nextPaymentDue Timestamp of when payment is due. @param lateFeeCalc Address of LateFeeCalc. @param premiumCalc Address of PremiumCalc. @return total Principal + Interest for the full payment. @return principal Entitled principal amount needed to be paid in the full payment. @return interest Entitled interest amount needed to be paid in the full payment. */ function getFullPayment( address repaymentCalc, uint256 nextPaymentDue, address lateFeeCalc, address premiumCalc ) external view returns ( uint256 total, uint256 principal, uint256 interest ) { (total, principal, interest) = IPremiumCalc(premiumCalc).getPremiumPayment(address(this)); if (block.timestamp <= nextPaymentDue) return (total, principal, interest); // If payment is late, calculate and add late fees using interest amount from regular payment. (,, uint256 regInterest) = IRepaymentCalc(repaymentCalc).getNextPayment(address(this)); uint256 lateFee = ILateFeeCalc(lateFeeCalc).getLateFee(regInterest); total = total.add(lateFee); interest = interest.add(lateFee); } /** @dev Calculates collateral required to drawdown amount. @param collateralAsset IERC20 of the Collateral Asset. @param liquidityAsset IERC20 of the Liquidity Asset. @param collateralRatio Percentage of drawdown value that must be posted as collateral. @param superFactory Factory that instantiated Loan. @param amt Drawdown amount. @return Amount of Collateral Asset required to post in CollateralLocker for given drawdown amount. */ function collateralRequiredForDrawdown( IERC20Details collateralAsset, IERC20Details liquidityAsset, uint256 collateralRatio, address superFactory, uint256 amt ) external view returns (uint256) { IMapleGlobals globals = _globals(superFactory); uint256 wad = _toWad(amt, liquidityAsset); // Convert to WAD precision. // Fetch current value of Liquidity Asset and Collateral Asset (Chainlink oracles provide 8 decimal precision). uint256 liquidityAssetPrice = globals.getLatestPrice(address(liquidityAsset)); uint256 collateralPrice = globals.getLatestPrice(address(collateralAsset)); // Calculate collateral required. uint256 collateralRequiredUSD = wad.mul(liquidityAssetPrice).mul(collateralRatio).div(10_000); // 18 + 8 = 26 decimals uint256 collateralRequiredWAD = collateralRequiredUSD.div(collateralPrice); // 26 - 8 = 18 decimals return collateralRequiredWAD.mul(10 ** collateralAsset.decimals()).div(10 ** 18); // 18 + collateralAssetDecimals - 18 = collateralAssetDecimals } /************************/ /*** Helper Functions ***/ /************************/ function _globals(address loanFactory) internal view returns (IMapleGlobals) { return IMapleGlobals(ILoanFactory(loanFactory).globals()); } function _toWad(uint256 amt, IERC20Details liquidityAsset) internal view returns (uint256) { return amt.mul(10 ** 18).div(10 ** liquidityAsset.decimals()); } } ////// contracts/math/SafeMathInt.sol /* pragma solidity 0.6.11; */ library SafeMathInt { function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0, "SMI:NEG"); return uint256(a); } } ////// contracts/math/SafeMathUint.sol /* pragma solidity 0.6.11; */ library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256 b) { b = int256(a); require(b >= 0, "SMU:OOB"); } } ////// lib/openzeppelin-contracts/contracts/math/SignedSafeMath.sol /* pragma solidity >=0.6.0 <0.8.0; */ /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } ////// lib/openzeppelin-contracts/contracts/GSN/Context.sol /* pragma solidity >=0.6.0 <0.8.0; */ /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } ////// lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol /* pragma solidity >=0.6.0 <0.8.0; */ /* import "../../GSN/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 returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _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 { } } ////// contracts/token/BasicFDT.sol /* pragma solidity 0.6.11; */ /* import "lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol"; */ /* import "lib/openzeppelin-contracts/contracts/math/SafeMath.sol"; */ /* import "lib/openzeppelin-contracts/contracts/math/SignedSafeMath.sol"; */ /* import "./interfaces/IBaseFDT.sol"; */ /* import "../math/SafeMathUint.sol"; */ /* import "../math/SafeMathInt.sol"; */ /// @title BasicFDT implements base level FDT functionality for accounting for revenues. abstract contract BasicFDT is IBaseFDT, ERC20 { using SafeMath for uint256; using SafeMathUint for uint256; using SignedSafeMath for int256; using SafeMathInt for int256; uint256 internal constant pointsMultiplier = 2 ** 128; uint256 internal pointsPerShare; mapping(address => int256) internal pointsCorrection; mapping(address => uint256) internal withdrawnFunds; event PointsPerShareUpdated(uint256 pointsPerShare); event PointsCorrectionUpdated(address indexed account, int256 pointsCorrection); constructor(string memory name, string memory symbol) ERC20(name, symbol) public { } /** @dev Distributes funds to token holders. @dev It reverts if the total supply of tokens is 0. @dev It emits a `FundsDistributed` event if the amount of received funds is greater than 0. @dev It emits a `PointsPerShareUpdated` event if the amount of received funds is greater than 0. About undistributed funds: In each distribution, there is a small amount of funds which do not get distributed, which is `(value pointsMultiplier) % totalSupply()`. With a well-chosen `pointsMultiplier`, the amount funds that are not getting distributed in a distribution can be less than 1 (base unit). We can actually keep track of the undistributed funds in a distribution and try to distribute it in the next distribution. */ function _distributeFunds(uint256 value) internal { require(totalSupply() > 0, "FDT:ZERO_SUPPLY"); if (value == 0) return; pointsPerShare = pointsPerShare.add(value.mul(pointsMultiplier) / totalSupply()); emit FundsDistributed(msg.sender, value); emit PointsPerShareUpdated(pointsPerShare); } /** @dev Prepares the withdrawal of funds. @dev It emits a `FundsWithdrawn` event if the amount of withdrawn funds is greater than 0. @return withdrawableDividend The amount of dividend funds that can be withdrawn. */ function _prepareWithdraw() internal returns (uint256 withdrawableDividend) { withdrawableDividend = withdrawableFundsOf(msg.sender); uint256 _withdrawnFunds = withdrawnFunds[msg.sender].add(withdrawableDividend); withdrawnFunds[msg.sender] = _withdrawnFunds; emit FundsWithdrawn(msg.sender, withdrawableDividend, _withdrawnFunds); } /** @dev Returns the amount of funds that an account can withdraw. @param _owner The address of a token holder. @return The amount funds that `_owner` can withdraw. */ function withdrawableFundsOf(address _owner) public view override returns (uint256) { return accumulativeFundsOf(_owner).sub(withdrawnFunds[_owner]); } /** @dev Returns the amount of funds that an account has withdrawn. @param _owner The address of a token holder. @return The amount of funds that `_owner` has withdrawn. */ function withdrawnFundsOf(address _owner) external view returns (uint256) { return withdrawnFunds[_owner]; } /** @dev Returns the amount of funds that an account has earned in total. @dev accumulativeFundsOf(_owner) = withdrawableFundsOf(_owner) + withdrawnFundsOf(_owner) = (pointsPerShare * balanceOf(_owner) + pointsCorrection[_owner]) / pointsMultiplier @param _owner The address of a token holder. @return The amount of funds that `_owner` has earned in total. */ function accumulativeFundsOf(address _owner) public view returns (uint256) { return pointsPerShare .mul(balanceOf(_owner)) .toInt256Safe() .add(pointsCorrection[_owner]) .toUint256Safe() / pointsMultiplier; } /** @dev Transfers tokens from one account to another. Updates pointsCorrection to keep funds unchanged. @dev It emits two `PointsCorrectionUpdated` events, one for the sender and one for the receiver. @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 virtual override { super._transfer(from, to, value); int256 _magCorrection = pointsPerShare.mul(value).toInt256Safe(); int256 pointsCorrectionFrom = pointsCorrection[from].add(_magCorrection); pointsCorrection[from] = pointsCorrectionFrom; int256 pointsCorrectionTo = pointsCorrection[to].sub(_magCorrection); pointsCorrection[to] = pointsCorrectionTo; emit PointsCorrectionUpdated(from, pointsCorrectionFrom); emit PointsCorrectionUpdated(to, pointsCorrectionTo); } /** @dev Mints tokens to an account. Updates pointsCorrection to keep funds unchanged. @param account The account that will receive the created tokens. @param value The amount that will be created. */ function _mint(address account, uint256 value) internal virtual override { super._mint(account, value); int256 _pointsCorrection = pointsCorrection[account].sub( (pointsPerShare.mul(value)).toInt256Safe() ); pointsCorrection[account] = _pointsCorrection; emit PointsCorrectionUpdated(account, _pointsCorrection); } /** @dev Burns an amount of the token of a given account. Updates pointsCorrection to keep funds unchanged. @dev It emits a `PointsCorrectionUpdated` event. @param account The account whose tokens will be burnt. @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal virtual override { super._burn(account, value); int256 _pointsCorrection = pointsCorrection[account].add( (pointsPerShare.mul(value)).toInt256Safe() ); pointsCorrection[account] = _pointsCorrection; emit PointsCorrectionUpdated(account, _pointsCorrection); } /** @dev Withdraws all available funds for a token holder. */ function withdrawFunds() public virtual override {} /** @dev Updates the current `fundsToken` balance and returns the difference of the new and previous `fundsToken` balance. @return A int256 representing the difference of the new and previous `fundsToken` balance. */ function _updateFundsTokenBalance() internal virtual returns (int256) {} /** @dev Registers a payment of funds in tokens. May be called directly after a deposit is made. @dev Calls _updateFundsTokenBalance(), whereby the contract computes the delta of the new and previous `fundsToken` balance and increments the total received funds (cumulative), by delta, by calling _distributeFunds(). */ function updateFundsReceived() public virtual { int256 newFunds = _updateFundsTokenBalance(); if (newFunds <= 0) return; _distributeFunds(newFunds.toUint256Safe()); } } ////// contracts/token/LoanFDT.sol /* pragma solidity 0.6.11; */ /* import "lib/openzeppelin-contracts/contracts/token/ERC20/SafeERC20.sol"; */ /* import "./BasicFDT.sol"; */ /// @title LoanFDT inherits BasicFDT and uses the original ERC-2222 logic. abstract contract LoanFDT is BasicFDT { using SafeMath for uint256; using SafeMathUint for uint256; using SignedSafeMath for int256; using SafeMathInt for int256; using SafeERC20 for IERC20; IERC20 public immutable fundsToken; // The `fundsToken` (dividends). uint256 public fundsTokenBalance; // The amount of `fundsToken` (Liquidity Asset) currently present and accounted for in this contract. constructor(string memory name, string memory symbol, address _fundsToken) BasicFDT(name, symbol) public { fundsToken = IERC20(_fundsToken); } /** @dev Withdraws all available funds for a token holder. */ function withdrawFunds() public virtual override { uint256 withdrawableFunds = _prepareWithdraw(); if (withdrawableFunds > uint256(0)) { fundsToken.safeTransfer(msg.sender, withdrawableFunds); _updateFundsTokenBalance(); } } /** @dev Updates the current `fundsToken` balance and returns the difference of the new and previous `fundsToken` balance. @return A int256 representing the difference of the new and previous `fundsToken` balance. */ function _updateFundsTokenBalance() internal virtual override returns (int256) { uint256 _prevFundsTokenBalance = fundsTokenBalance; fundsTokenBalance = fundsToken.balanceOf(address(this)); return int256(fundsTokenBalance).sub(int256(_prevFundsTokenBalance)); } } ////// lib/openzeppelin-contracts/contracts/utils/Pausable.sol /* pragma solidity >=0.6.0 <0.8.0; */ /* import "../GSN/Context.sol"; */ /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view 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()); } } ////// contracts/Loan.sol /* pragma solidity 0.6.11; */ /* import "lib/openzeppelin-contracts/contracts/utils/Pausable.sol"; */ /* import "lib/openzeppelin-contracts/contracts/token/ERC20/SafeERC20.sol"; */ /* import "./interfaces/ICollateralLocker.sol"; */ /* import "./interfaces/ICollateralLockerFactory.sol"; */ /* import "./interfaces/IERC20Details.sol"; */ /* import "./interfaces/IFundingLocker.sol"; */ /* import "./interfaces/IFundingLockerFactory.sol"; */ /* import "./interfaces/IMapleGlobals.sol"; */ /* import "./interfaces/ILateFeeCalc.sol"; */ /* import "./interfaces/ILiquidityLocker.sol"; */ /* import "./interfaces/ILoanFactory.sol"; */ /* import "./interfaces/IPool.sol"; */ /* import "./interfaces/IPoolFactory.sol"; */ /* import "./interfaces/IPremiumCalc.sol"; */ /* import "./interfaces/IRepaymentCalc.sol"; */ /* import "./interfaces/IUniswapRouter.sol"; */ /* import "./library/Util.sol"; */ /* import "./library/LoanLib.sol"; */ /* import "./token/LoanFDT.sol"; */ /// @title Loan maintains all accounting and functionality related to Loans. contract Loan is LoanFDT, Pausable { using SafeMathInt for int256; using SignedSafeMath for int256; using SafeMath for uint256; using SafeERC20 for IERC20; /** Ready = The Loan has been initialized and is ready for funding (assuming funding period hasn't ended) Active = The Loan has been drawdown and the Borrower is making payments Matured = The Loan is fully paid off and has "matured" Expired = The Loan did not initiate, and all funding was returned to Lenders Liquidated = The Loan has been liquidated */ enum State { Ready, Active, Matured, Expired, Liquidated } State public loanState; // The current state of this Loan, as defined in the State enum below. IERC20 public immutable liquidityAsset; // The asset deposited by Lenders into the FundingLocker, when funding this Loan. IERC20 public immutable collateralAsset; // The asset deposited by Borrower into the CollateralLocker, for collateralizing this Loan. address public immutable fundingLocker; // The FundingLocker that holds custody of Loan funds before drawdown. address public immutable flFactory; // The FundingLockerFactory. address public immutable collateralLocker; // The CollateralLocker that holds custody of Loan collateral. address public immutable clFactory; // The CollateralLockerFactory. address public immutable borrower; // The Borrower of this Loan, responsible for repayments. address public immutable repaymentCalc; // The RepaymentCalc for this Loan. address public immutable lateFeeCalc; // The LateFeeCalc for this Loan. address public immutable premiumCalc; // The PremiumCalc for this Loan. address public immutable superFactory; // The LoanFactory that deployed this Loan. mapping(address => bool) public loanAdmins; // Admin addresses that have permission to do certain operations in case of disaster management. uint256 public nextPaymentDue; // The unix timestamp due date of the next payment. // Loan specifications uint256 public immutable apr; // The APR in basis points. uint256 public paymentsRemaining; // The number of payments remaining on the Loan. uint256 public immutable termDays; // The total length of the Loan term in days. uint256 public immutable paymentIntervalSeconds; // The time between Loan payments in seconds. uint256 public immutable requestAmount; // The total requested amount for Loan. uint256 public immutable collateralRatio; // The percentage of value of the drawdown amount to post as collateral in basis points. uint256 public immutable createdAt; // The timestamp of when Loan was instantiated. uint256 public immutable fundingPeriod; // The time for a Loan to be funded in seconds. uint256 public immutable defaultGracePeriod; // The time a Borrower has, after a payment is due, to make a payment before a liquidation can occur. // Accounting variables uint256 public principalOwed; // The amount of principal owed (initially the drawdown amount). uint256 public principalPaid; // The amount of principal that has been paid by the Borrower since the Loan instantiation. uint256 public interestPaid; // The amount of interest that has been paid by the Borrower since the Loan instantiation. uint256 public feePaid; // The amount of fees that have been paid by the Borrower since the Loan instantiation. uint256 public excessReturned; // The amount of excess that has been returned to the Lenders after the Loan drawdown. // Liquidation variables uint256 public amountLiquidated; // The amount of Collateral Asset that has been liquidated after default. uint256 public amountRecovered; // The amount of Liquidity Asset that has been recovered after default. uint256 public defaultSuffered; // The difference between `amountRecovered` and `principalOwed` after liquidation. uint256 public liquidationExcess; // If `amountRecovered > principalOwed`, this is the amount of Liquidity Asset that is to be returned to the Borrower. event LoanFunded(address indexed fundedBy, uint256 amountFunded); event BalanceUpdated(address indexed account, address indexed token, uint256 balance); event Drawdown(uint256 drawdownAmount); event LoanStateChanged(State state); event LoanAdminSet(address indexed loanAdmin, bool allowed); event PaymentMade( uint256 totalPaid, uint256 principalPaid, uint256 interestPaid, uint256 paymentsRemaining, uint256 principalOwed, uint256 nextPaymentDue, bool latePayment ); event Liquidation( uint256 collateralSwapped, uint256 liquidityAssetReturned, uint256 liquidationExcess, uint256 defaultSuffered ); /** @dev Constructor for a Loan. @dev It emits a `LoanStateChanged` event. @param _borrower Will receive the funding when calling `drawdown()`. Is also responsible for repayments. @param _liquidityAsset The asset the Borrower is requesting funding in. @param _collateralAsset The asset provided as collateral by the Borrower. @param _flFactory Factory to instantiate FundingLocker with. @param _clFactory Factory to instantiate CollateralLocker with. @param specs Contains specifications for this Loan. specs[0] = apr specs[1] = termDays specs[2] = paymentIntervalDays (aka PID) specs[3] = requestAmount specs[4] = collateralRatio @param calcs The calculators used for this Loan. calcs[0] = repaymentCalc calcs[1] = lateFeeCalc calcs[2] = premiumCalc */ constructor( address _borrower, address _liquidityAsset, address _collateralAsset, address _flFactory, address _clFactory, uint256[5] memory specs, address[3] memory calcs ) LoanFDT("Maple Loan Token", "MPL-LOAN", _liquidityAsset) public { IMapleGlobals globals = _globals(msg.sender); // Perform validity cross-checks. LoanLib.loanSanityChecks(globals, _liquidityAsset, _collateralAsset, specs); borrower = _borrower; liquidityAsset = IERC20(_liquidityAsset); collateralAsset = IERC20(_collateralAsset); flFactory = _flFactory; clFactory = _clFactory; createdAt = block.timestamp; // Update state variables. apr = specs[0]; termDays = specs[1]; paymentsRemaining = specs[1].div(specs[2]); paymentIntervalSeconds = specs[2].mul(1 days); requestAmount = specs[3]; collateralRatio = specs[4]; fundingPeriod = globals.fundingPeriod(); defaultGracePeriod = globals.defaultGracePeriod(); repaymentCalc = calcs[0]; lateFeeCalc = calcs[1]; premiumCalc = calcs[2]; superFactory = msg.sender; // Deploy lockers. collateralLocker = ICollateralLockerFactory(_clFactory).newLocker(_collateralAsset); fundingLocker = IFundingLockerFactory(_flFactory).newLocker(_liquidityAsset); emit LoanStateChanged(State.Ready); } /**************************/ /*** Borrower Functions ***/ /**************************/ /** @dev Draws down funding from FundingLocker, posts collateral, and transitions the Loan state from `Ready` to `Active`. Only the Borrower can call this function. @dev It emits four `BalanceUpdated` events. @dev It emits a `LoanStateChanged` event. @dev It emits a `Drawdown` event. @param amt Amount of Liquidity Asset the Borrower draws down. Remainder is returned to the Loan where it can be claimed back by LoanFDT holders. */ function drawdown(uint256 amt) external { _whenProtocolNotPaused(); _isValidBorrower(); _isValidState(State.Ready); IMapleGlobals globals = _globals(superFactory); IFundingLocker _fundingLocker = IFundingLocker(fundingLocker); require(amt >= requestAmount, "L:AMT_LT_REQUEST_AMT"); require(amt <= _getFundingLockerBalance(), "L:AMT_GT_FUNDED_AMT"); // Update accounting variables for the Loan. principalOwed = amt; nextPaymentDue = block.timestamp.add(paymentIntervalSeconds); loanState = State.Active; // Transfer the required amount of collateral for drawdown from the Borrower to the CollateralLocker. collateralAsset.safeTransferFrom(borrower, collateralLocker, collateralRequiredForDrawdown(amt)); // Transfer funding amount from the FundingLocker to the Borrower, then drain remaining funds to the Loan. uint256 treasuryFee = globals.treasuryFee(); uint256 investorFee = globals.investorFee(); address treasury = globals.mapleTreasury(); uint256 _feePaid = feePaid = amt.mul(investorFee).div(10_000); // Update fees paid for `claim()`. uint256 treasuryAmt = amt.mul(treasuryFee).div(10_000); // Calculate amount to send to the MapleTreasury. _transferFunds(_fundingLocker, treasury, treasuryAmt); // Send the treasury fee directly to the MapleTreasury. _transferFunds(_fundingLocker, borrower, amt.sub(treasuryAmt).sub(_feePaid)); // Transfer drawdown amount to the Borrower. // Update excessReturned for `claim()`. excessReturned = _getFundingLockerBalance().sub(_feePaid); // Drain remaining funds from the FundingLocker (amount equal to `excessReturned` plus `feePaid`) _fundingLocker.drain(); // Call `updateFundsReceived()` update LoanFDT accounting with funds received from fees and excess returned. updateFundsReceived(); _emitBalanceUpdateEventForCollateralLocker(); _emitBalanceUpdateEventForFundingLocker(); _emitBalanceUpdateEventForLoan(); emit BalanceUpdated(treasury, address(liquidityAsset), liquidityAsset.balanceOf(treasury)); emit LoanStateChanged(State.Active); emit Drawdown(amt); } /** @dev Makes a payment for this Loan. Amounts are calculated for the Borrower. */ function makePayment() external { _whenProtocolNotPaused(); _isValidState(State.Active); (uint256 total, uint256 principal, uint256 interest,, bool paymentLate) = getNextPayment(); --paymentsRemaining; _makePayment(total, principal, interest, paymentLate); } /** @dev Makes the full payment for this Loan (a.k.a. "calling" the Loan). This requires the Borrower to pay a premium fee. */ function makeFullPayment() external { _whenProtocolNotPaused(); _isValidState(State.Active); (uint256 total, uint256 principal, uint256 interest) = getFullPayment(); paymentsRemaining = uint256(0); _makePayment(total, principal, interest, false); } /** @dev Updates the payment variables and transfers funds from the Borrower into the Loan. @dev It emits one or two `BalanceUpdated` events (depending if payments remaining). @dev It emits a `LoanStateChanged` event if no payments remaining. @dev It emits a `PaymentMade` event. */ function _makePayment(uint256 total, uint256 principal, uint256 interest, bool paymentLate) internal { // Caching to reduce `SLOADs`. uint256 _paymentsRemaining = paymentsRemaining; // Update internal accounting variables. interestPaid = interestPaid.add(interest); if (principal > uint256(0)) principalPaid = principalPaid.add(principal); if (_paymentsRemaining > uint256(0)) { // Update info related to next payment and, if needed, decrement principalOwed. nextPaymentDue = nextPaymentDue.add(paymentIntervalSeconds); if (principal > uint256(0)) principalOwed = principalOwed.sub(principal); } else { // Update info to close loan. principalOwed = uint256(0); loanState = State.Matured; nextPaymentDue = uint256(0); // Transfer all collateral back to the Borrower. ICollateralLocker(collateralLocker).pull(borrower, _getCollateralLockerBalance()); _emitBalanceUpdateEventForCollateralLocker(); emit LoanStateChanged(State.Matured); } // Loan payer sends funds to the Loan. liquidityAsset.safeTransferFrom(msg.sender, address(this), total); // Update FDT accounting with funds received from interest payment. updateFundsReceived(); emit PaymentMade( total, principal, interest, _paymentsRemaining, principalOwed, _paymentsRemaining > 0 ? nextPaymentDue : 0, paymentLate ); _emitBalanceUpdateEventForLoan(); } /************************/ /*** Lender Functions ***/ /************************/ /** @dev Funds this Loan and mints LoanFDTs for `mintTo` (DebtLocker in the case of Pool funding). Only LiquidityLocker using valid/approved Pool can call this function. @dev It emits a `LoanFunded` event. @dev It emits a `BalanceUpdated` event. @param amt Amount to fund the Loan. @param mintTo Address that LoanFDTs are minted to. */ function fundLoan(address mintTo, uint256 amt) whenNotPaused external { _whenProtocolNotPaused(); _isValidState(State.Ready); _isValidPool(); _isWithinFundingPeriod(); liquidityAsset.safeTransferFrom(msg.sender, fundingLocker, amt); uint256 wad = _toWad(amt); // Convert to WAD precision. _mint(mintTo, wad); // Mint LoanFDTs to `mintTo` (i.e DebtLocker contract). emit LoanFunded(mintTo, amt); _emitBalanceUpdateEventForFundingLocker(); } /** @dev Handles returning capital to the Loan, where it can be claimed back by LoanFDT holders, if the Borrower has not drawn down on the Loan past the drawdown grace period. @dev It emits a `LoanStateChanged` event. */ function unwind() external { _whenProtocolNotPaused(); _isValidState(State.Ready); // Update accounting for `claim()` and transfer funds from FundingLocker to Loan. excessReturned = LoanLib.unwind(liquidityAsset, fundingLocker, createdAt, fundingPeriod); updateFundsReceived(); // Transition state to `Expired`. loanState = State.Expired; emit LoanStateChanged(State.Expired); } /** @dev Triggers a default if the Loan meets certain default conditions, liquidating all collateral and updating accounting. Only the an account with sufficient LoanFDTs of this Loan can call this function. @dev It emits a `BalanceUpdated` event. @dev It emits a `Liquidation` event. @dev It emits a `LoanStateChanged` event. */ function triggerDefault() external { _whenProtocolNotPaused(); _isValidState(State.Active); require(LoanLib.canTriggerDefault(nextPaymentDue, defaultGracePeriod, superFactory, balanceOf(msg.sender), totalSupply()), "L:FAILED_TO_LIQ"); // Pull the Collateral Asset from the CollateralLocker, swap to the Liquidity Asset, and hold custody of the resulting Liquidity Asset in the Loan. (amountLiquidated, amountRecovered) = LoanLib.liquidateCollateral(collateralAsset, address(liquidityAsset), superFactory, collateralLocker); _emitBalanceUpdateEventForCollateralLocker(); // Decrement `principalOwed` by `amountRecovered`, set `defaultSuffered` to the difference (shortfall from the liquidation). if (amountRecovered <= principalOwed) { principalOwed = principalOwed.sub(amountRecovered); defaultSuffered = principalOwed; } // Set `principalOwed` to zero and return excess value from the liquidation back to the Borrower. else { liquidationExcess = amountRecovered.sub(principalOwed); principalOwed = 0; liquidityAsset.safeTransfer(borrower, liquidationExcess); // Send excess to the Borrower. } // Update LoanFDT accounting with funds received from the liquidation. updateFundsReceived(); // Transition `loanState` to `Liquidated` loanState = State.Liquidated; emit Liquidation( amountLiquidated, // Amount of Collateral Asset swapped. amountRecovered, // Amount of Liquidity Asset recovered from swap. liquidationExcess, // Amount of Liquidity Asset returned to borrower. defaultSuffered // Remaining losses after the liquidation. ); emit LoanStateChanged(State.Liquidated); } /***********************/ /*** Admin Functions ***/ /***********************/ /** @dev Triggers paused state. Halts functionality for certain functions. Only the Borrower or a Loan Admin can call this function. */ function pause() external { _isValidBorrowerOrLoanAdmin(); super._pause(); } /** @dev Triggers unpaused state. Restores functionality for certain functions. Only the Borrower or a Loan Admin can call this function. */ function unpause() external { _isValidBorrowerOrLoanAdmin(); super._unpause(); } /** @dev Sets a Loan Admin. Only the Borrower can call this function. @dev It emits a `LoanAdminSet` event. @param loanAdmin An address being allowed or disallowed as a Loan Admin. @param allowed Status of a Loan Admin. */ function setLoanAdmin(address loanAdmin, bool allowed) external { _whenProtocolNotPaused(); _isValidBorrower(); loanAdmins[loanAdmin] = allowed; emit LoanAdminSet(loanAdmin, allowed); } /**************************/ /*** Governor Functions ***/ /**************************/ /** @dev Transfers any locked funds to the Governor. Only the Governor can call this function. @param token Address of the token to be reclaimed. */ function reclaimERC20(address token) external { LoanLib.reclaimERC20(token, address(liquidityAsset), _globals(superFactory)); } /*********************/ /*** FDT Functions ***/ /*********************/ /** @dev Withdraws all available funds earned through LoanFDT for a token holder. @dev It emits a `BalanceUpdated` event. */ function withdrawFunds() public override { _whenProtocolNotPaused(); super.withdrawFunds(); emit BalanceUpdated(address(this), address(fundsToken), fundsToken.balanceOf(address(this))); } /************************/ /*** Getter Functions ***/ /************************/ /** @dev Returns the expected amount of Liquidity Asset to be recovered from a liquidation based on current oracle prices. @return The minimum amount of Liquidity Asset that can be expected by swapping Collateral Asset. */ function getExpectedAmountRecovered() external view returns (uint256) { uint256 liquidationAmt = _getCollateralLockerBalance(); return Util.calcMinAmount(_globals(superFactory), address(collateralAsset), address(liquidityAsset), liquidationAmt); } /** @dev Returns information of the next payment amount. @return [0] = Entitled interest of the next payment (Principal + Interest only when the next payment is last payment of the Loan) [1] = Entitled principal amount needed to be paid in the next payment [2] = Entitled interest amount needed to be paid in the next payment [3] = Payment Due Date [4] = Is Payment Late */ function getNextPayment() public view returns (uint256, uint256, uint256, uint256, bool) { return LoanLib.getNextPayment(repaymentCalc, nextPaymentDue, lateFeeCalc); } /** @dev Returns the information of a full payment amount. @return total Principal and interest owed, combined. @return principal Principal owed. @return interest Interest owed. */ function getFullPayment() public view returns (uint256 total, uint256 principal, uint256 interest) { (total, principal, interest) = LoanLib.getFullPayment(repaymentCalc, nextPaymentDue, lateFeeCalc, premiumCalc); } /** @dev Calculates the collateral required to draw down amount. @param amt The amount of the Liquidity Asset to draw down from the FundingLocker. @return The amount of the Collateral Asset required to post in the CollateralLocker for a given drawdown amount. */ function collateralRequiredForDrawdown(uint256 amt) public view returns (uint256) { return LoanLib.collateralRequiredForDrawdown( IERC20Details(address(collateralAsset)), IERC20Details(address(liquidityAsset)), collateralRatio, superFactory, amt ); } /************************/ /*** Helper Functions ***/ /************************/ /** @dev Checks that the protocol is not in a paused state. */ function _whenProtocolNotPaused() internal view { require(!_globals(superFactory).protocolPaused(), "L:PROTO_PAUSED"); } /** @dev Checks that `msg.sender` is the Borrower or a Loan Admin. */ function _isValidBorrowerOrLoanAdmin() internal view { require(msg.sender == borrower || loanAdmins[msg.sender], "L:NOT_BORROWER_OR_ADMIN"); } /** @dev Converts to WAD precision. */ function _toWad(uint256 amt) internal view returns (uint256) { return amt.mul(10 ** 18).div(10 ** IERC20Details(address(liquidityAsset)).decimals()); } /** @dev Returns the MapleGlobals instance. */ function _globals(address loanFactory) internal view returns (IMapleGlobals) { return IMapleGlobals(ILoanFactory(loanFactory).globals()); } /** @dev Returns the CollateralLocker balance. */ function _getCollateralLockerBalance() internal view returns (uint256) { return collateralAsset.balanceOf(collateralLocker); } /** @dev Returns the FundingLocker balance. */ function _getFundingLockerBalance() internal view returns (uint256) { return liquidityAsset.balanceOf(fundingLocker); } /** @dev Checks that the current state of the Loan matches the provided state. @param _state Enum of desired Loan state. */ function _isValidState(State _state) internal view { require(loanState == _state, "L:INVALID_STATE"); } /** @dev Checks that `msg.sender` is the Borrower. */ function _isValidBorrower() internal view { require(msg.sender == borrower, "L:NOT_BORROWER"); } /** @dev Checks that `msg.sender` is a Lender (LiquidityLocker) that is using an approved Pool to fund the Loan. */ function _isValidPool() internal view { address pool = ILiquidityLocker(msg.sender).pool(); address poolFactory = IPool(pool).superFactory(); require( _globals(superFactory).isValidPoolFactory(poolFactory) && IPoolFactory(poolFactory).isPool(pool), "L:INVALID_LENDER" ); } /** @dev Checks that "now" is currently within the funding period. */ function _isWithinFundingPeriod() internal view { require(block.timestamp <= createdAt.add(fundingPeriod), "L:PAST_FUNDING_PERIOD"); } /** @dev Transfers funds from the FundingLocker. @param from Instance of the FundingLocker. @param to Address to send funds to. @param value Amount to send. */ function _transferFunds(IFundingLocker from, address to, uint256 value) internal { from.pull(to, value); } /** @dev Emits a `BalanceUpdated` event for the Loan. @dev It emits a `BalanceUpdated` event. */ function _emitBalanceUpdateEventForLoan() internal { emit BalanceUpdated(address(this), address(liquidityAsset), liquidityAsset.balanceOf(address(this))); } /** @dev Emits a `BalanceUpdated` event for the FundingLocker. @dev It emits a `BalanceUpdated` event. */ function _emitBalanceUpdateEventForFundingLocker() internal { emit BalanceUpdated(fundingLocker, address(liquidityAsset), _getFundingLockerBalance()); } /** @dev Emits a `BalanceUpdated` event for the CollateralLocker. @dev It emits a `BalanceUpdated` event. */ function _emitBalanceUpdateEventForCollateralLocker() internal { emit BalanceUpdated(collateralLocker, address(collateralAsset), _getCollateralLockerBalance()); } } ////// contracts/LoanFactory.sol /* pragma solidity 0.6.11; */ /* import "lib/openzeppelin-contracts/contracts/utils/Pausable.sol"; */ /* import "./Loan.sol"; */ /// @title LoanFactory instantiates Loans. contract LoanFactory is Pausable { using SafeMath for uint256; uint8 public constant CL_FACTORY = 0; // Factory type of `CollateralLockerFactory`. uint8 public constant FL_FACTORY = 2; // Factory type of `FundingLockerFactory`. uint8 public constant INTEREST_CALC_TYPE = 10; // Calc type of `RepaymentCalc`. uint8 public constant LATEFEE_CALC_TYPE = 11; // Calc type of `LateFeeCalc`. uint8 public constant PREMIUM_CALC_TYPE = 12; // Calc type of `PremiumCalc`. IMapleGlobals public globals; // Instance of the MapleGlobals. uint256 public loansCreated; // Incrementor for number of Loans created. mapping(uint256 => address) public loans; // Loans address mapping. mapping(address => bool) public isLoan; // True only if a Loan was created by this factory. mapping(address => bool) public loanFactoryAdmins; // The LoanFactory Admin addresses that have permission to do certain operations in case of disaster management. event LoanFactoryAdminSet(address indexed loanFactoryAdmin, bool allowed); event LoanCreated( address loan, address indexed borrower, address indexed liquidityAsset, address collateralAsset, address collateralLocker, address fundingLocker, uint256[5] specs, address[3] calcs, string name, string symbol ); constructor(address _globals) public { globals = IMapleGlobals(_globals); } /** @dev Sets MapleGlobals. Only the Governor can call this function. @param newGlobals Address of new MapleGlobals. */ function setGlobals(address newGlobals) external { _isValidGovernor(); globals = IMapleGlobals(newGlobals); } /** @dev Create a new Loan. @dev It emits a `LoanCreated` event. @param liquidityAsset Asset the Loan will raise funding in. @param collateralAsset Asset the Loan will use as collateral. @param flFactory The factory to instantiate a FundingLocker from. @param clFactory The factory to instantiate a CollateralLocker from. @param specs Contains specifications for this Loan. specs[0] = apr specs[1] = termDays specs[2] = paymentIntervalDays specs[3] = requestAmount specs[4] = collateralRatio @param calcs The calculators used for this Loan. calcs[0] = repaymentCalc calcs[1] = lateFeeCalc calcs[2] = premiumCalc @return loanAddress Address of the instantiated Loan. */ function createLoan( address liquidityAsset, address collateralAsset, address flFactory, address clFactory, uint256[5] memory specs, address[3] memory calcs ) external whenNotPaused returns (address loanAddress) { _whenProtocolNotPaused(); IMapleGlobals _globals = globals; // Perform validity checks. require(_globals.isValidSubFactory(address(this), flFactory, FL_FACTORY), "LF:INVALID_FLF"); require(_globals.isValidSubFactory(address(this), clFactory, CL_FACTORY), "LF:INVALID_CLF"); require(_globals.isValidCalc(calcs[0], INTEREST_CALC_TYPE), "LF:INVALID_INT_C"); require(_globals.isValidCalc(calcs[1], LATEFEE_CALC_TYPE), "LF:INVALID_LATE_FEE_C"); require(_globals.isValidCalc(calcs[2], PREMIUM_CALC_TYPE), "LF:INVALID_PREM_C"); // Deploy new Loan. Loan loan = new Loan( msg.sender, liquidityAsset, collateralAsset, flFactory, clFactory, specs, calcs ); // Update the LoanFactory identification mappings. loanAddress = address(loan); loans[loansCreated] = loanAddress; isLoan[loanAddress] = true; ++loansCreated; emit LoanCreated( loanAddress, msg.sender, liquidityAsset, collateralAsset, loan.collateralLocker(), loan.fundingLocker(), specs, calcs, loan.name(), loan.symbol() ); } /** @dev Sets a LoanFactory Admin. Only the Governor can call this function. @dev It emits a `LoanFactoryAdminSet` event. @param loanFactoryAdmin An address being allowed or disallowed as a LoanFactory Admin. @param allowed Status of a LoanFactory Admin. */ function setLoanFactoryAdmin(address loanFactoryAdmin, bool allowed) external { _isValidGovernor(); loanFactoryAdmins[loanFactoryAdmin] = allowed; emit LoanFactoryAdminSet(loanFactoryAdmin, allowed); } /** @dev Triggers paused state. Halts functionality for certain functions. Only the Governor or a LoanFactory Admin can call this function. */ function pause() external { _isValidGovernorOrLoanFactoryAdmin(); super._pause(); } /** @dev Triggers unpaused state. Restores functionality for certain functions. Only the Governor or a LoanFactory Admin can call this function. */ function unpause() external { _isValidGovernorOrLoanFactoryAdmin(); super._unpause(); } /** @dev Checks that `msg.sender` is the Governor. */ function _isValidGovernor() internal view { require(msg.sender == globals.governor(), "LF:NOT_GOV"); } /** @dev Checks that `msg.sender` is the Governor or a LoanFactory Admin. */ function _isValidGovernorOrLoanFactoryAdmin() internal view { require(msg.sender == globals.governor() || loanFactoryAdmins[msg.sender], "LF:NOT_GOV_OR_ADMIN"); } /** @dev Checks that the protocol is not in a paused state. */ function _whenProtocolNotPaused() internal view { require(!globals.protocolPaused(), "LF:PROTO_PAUSED"); } }
Calc type of `RepaymentCalc`.
uint8 public constant INTEREST_CALC_TYPE = 10;
13,742,093
[ 1, 25779, 618, 434, 1375, 426, 9261, 25779, 8338, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 28, 1071, 5381, 11391, 11027, 67, 7913, 39, 67, 2399, 273, 1728, 31, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xe6F4d9711121e5304b30aC2Aae57E3b085ad3c4d/sources/src/libraries/external/LPActions.sol
* @notice See `IPoolLPActions` for descriptions @dev === Write state === @dev decrement `LP` allowances @dev === Emit events === @dev - `RevokeLPAllowance`/
function revokeLPAllowance( mapping(uint256 => uint256) storage allowances_, address spender_, uint256[] calldata indexes_ ) external { uint256 indexesLength = indexes_.length; uint256 index; for (uint256 i = 0; i < indexesLength; ) { index = indexes_[i]; allowances_[index] = 0; } emit RevokeLPAllowance( msg.sender, spender_, indexes_ ); }
3,630,464
[ 1, 9704, 1375, 2579, 1371, 14461, 6100, 68, 364, 15550, 1377, 757, 2598, 919, 757, 1377, 15267, 1375, 14461, 68, 1699, 6872, 1377, 757, 16008, 2641, 757, 1377, 300, 1375, 29196, 14461, 7009, 1359, 68, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18007, 14461, 7009, 1359, 12, 203, 3639, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 2502, 1699, 6872, 67, 16, 203, 3639, 1758, 17571, 264, 67, 16, 203, 3639, 2254, 5034, 8526, 745, 892, 5596, 67, 203, 565, 262, 3903, 288, 203, 3639, 2254, 5034, 5596, 1782, 273, 5596, 27799, 2469, 31, 203, 3639, 2254, 5034, 770, 31, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 5596, 1782, 31, 262, 288, 203, 5411, 770, 273, 5596, 67, 63, 77, 15533, 203, 203, 5411, 1699, 6872, 67, 63, 1615, 65, 273, 374, 31, 203, 203, 3639, 289, 203, 203, 3639, 3626, 23863, 14461, 7009, 1359, 12, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 17571, 264, 67, 16, 203, 5411, 5596, 67, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-08-13 */ ////////PleaseBuy $PBUY///////////// // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; 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; } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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; } } library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = now + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(now > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // Contract implementarion contract PleaseBuy is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; mapping (address => bool) private _isWhitelist; mapping (address => uint256) private _lockedTime; mapping (address => uint256) private _lockedAmount; mapping (address => uint256) private _antiBot; mapping (address => uint256) private _lockPreSale; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000 * 10**6 *10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = 'PleaseBuy'; string private _symbol = 'pBuy'; uint8 private _decimals = 9; uint256 public _taxFee = 0; uint256 public _marketingFee = 8; uint256 public _liquidityPoolFee = 8; uint256 private _previousTaxFee = _taxFee; uint256 private _previousmarketingFee = _marketingFee; uint256 private _previousLiquidityPoolFee = _liquidityPoolFee; bool public _isAntiDumpEnabled = false; uint256 public antiDumpTime; address public _marketingWalletAddress; address public _liquidityPool; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwap = false; bool public swapEnabled = true; uint256 private _maxTxAmount = 10000000000 * 10**9; uint256 private _numOfTokensToExchangeForSwap = 5 * 10**6 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapEnabledUpdated(bool enabled); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor (address payable marketingWalletAddress) public { _marketingWalletAddress = marketingWalletAddress; _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; // Exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function setExcludeFromFee(address account, bool excluded) external onlyOwner() { _isExcludedFromFee[account] = excluded; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeAccount(address account) external onlyOwner() { require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function removeAllFee() private { if(_taxFee == 0 && _marketingFee == 0 && _liquidityPoolFee == 0) return; _previousTaxFee = _taxFee; _previousmarketingFee = _marketingFee; _previousLiquidityPoolFee = _liquidityPoolFee; _taxFee = 0; _marketingFee = 0; _liquidityPoolFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _marketingFee = _previousmarketingFee; _liquidityPoolFee = _previousLiquidityPoolFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(_isAntiDumpEnabled == true && sender != owner() && recipient != owner()){ if(sender == uniswapV2Pair){ uint256 timePassed = block.timestamp - _antiBot[recipient]; require(timePassed > antiDumpTime,'You must wait between trades'); _antiBot[recipient] = block.timestamp; } else if(recipient == uniswapV2Pair){ uint256 timePassed = block.timestamp - _antiBot[sender]; require(timePassed > antiDumpTime,'You must wait between trades'); _antiBot[sender] = block.timestamp; } else if(sender != uniswapV2Pair && recipient != uniswapV2Pair){ uint256 timePassed1 = block.timestamp - _antiBot[sender]; uint256 timePassed2 = block.timestamp - _antiBot[recipient]; require(timePassed1 > antiDumpTime && timePassed2 > antiDumpTime, 'You must wait between transfers'); _antiBot[sender] = block.timestamp; _antiBot[recipient] = block.timestamp; } } //If sender has purchased during presale, must wait lockPreSale to transfer. if(_isWhitelist[sender] == true) { uint256 time_since_purchase = block.timestamp - _lockedTime[sender]; if(time_since_purchase < _lockPreSale[sender]){ require((balanceOf(sender) - amount) >= _lockedAmount[sender], 'You must wait time from purchase'); } else { _isWhitelist[sender] == false; } } if(sender != owner() && recipient != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap? // also, don't get caught in a circular marketing event. // also, don't swap if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForSwap; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { // We need to swap the current tokens to ETH and send to the marketing wallet swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } //transfer amount, it will take tax and marketing fee _tokenTransfer(sender,recipient,amount,takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{ // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { uint256 swapFee = _marketingFee.add(_liquidityPoolFee); payable(_marketingWalletAddress).transfer(amount.div(swapFee).mul(_marketingFee)); payable(_liquidityPool).transfer(amount.div(swapFee).mul(_liquidityPoolFee)); } // We are exposing these functions to be able to manual swap and send // in case the token is highly valued and 5M becomes too much function manualSwap() external onlyOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualSend() external onlyOwner() { uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function setSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tSwap) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeSwapFee(tSwap); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tSwap) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeSwapFee(tSwap); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tSwap) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeSwapFee(tSwap); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tSwap) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeSwapFee(tSwap); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeSwapFee(uint256 tSwap) private { uint256 currentRate = _getRate(); uint256 rSwap = tSwap.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rSwap); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tSwap); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tSwap) = _getTValues(tAmount, _taxFee, _marketingFee, _liquidityPoolFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tSwap); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 marketingFee, uint256 liquidityPoolFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tSwap = tAmount.mul(marketingFee.add(liquidityPoolFee)).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tSwap); return (tTransferAmount, tFee, tSwap); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _getTaxFee() private view returns(uint256) { return _taxFee; } function _getMaxTxAmount() private view returns(uint256) { return _maxTxAmount; } function _getETHBalance() public view returns(uint256 balance) { return address(this).balance; } function _setTaxFee(uint256 taxFee) external onlyOwner() { _taxFee = taxFee; } function _setmarketingFee(uint256 marketingFee) external onlyOwner() { _marketingFee = marketingFee; } function _setmarketingWallet(address payable marketingWalletAddress) external onlyOwner() { _marketingWalletAddress = marketingWalletAddress; } function setLiquidityPool(address liquidityPool) external onlyOwner{ _liquidityPool = liquidityPool; } function distTokens(address[] memory recipients, uint256[] memory amounts, uint256 time) external onlyOwner{ require(recipients.length == amounts.length, 'Arrays must have same size'); for(uint i = 0; i< recipients.length; i++){ _isWhitelist[recipients[i]] = true; _lockedTime[recipients[i]] = block.timestamp; _lockPreSale[recipients[i]] = time * 1 hours; uint256 amt = amounts[i].mul(10**9); _lockedAmount[recipients[i]] = amt; _tokenTransfer(msg.sender, recipients[i], amt, false); } } function setLockPreSaleTime(address _address, uint256 hour) external onlyOwner{ _lockPreSale[_address] = hour * 1 hours; } function setAntiDumpEnabled(bool value, uint256 time) external onlyOwner{ _isAntiDumpEnabled = value; antiDumpTime = time * 1 minutes; } function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { _maxTxAmount = maxTxAmount; } }
If sender has purchased during presale, must wait lockPreSale to transfer. We need to swap the current tokens to ETH and send to the marketing walletif any account belongs to _isExcludedFromFee account then remove the fee
function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(_isAntiDumpEnabled == true && sender != owner() && recipient != owner()){ if(sender == uniswapV2Pair){ uint256 timePassed = block.timestamp - _antiBot[recipient]; require(timePassed > antiDumpTime,'You must wait between trades'); _antiBot[recipient] = block.timestamp; } else if(recipient == uniswapV2Pair){ uint256 timePassed = block.timestamp - _antiBot[sender]; require(timePassed > antiDumpTime,'You must wait between trades'); _antiBot[sender] = block.timestamp; } else if(sender != uniswapV2Pair && recipient != uniswapV2Pair){ uint256 timePassed1 = block.timestamp - _antiBot[sender]; uint256 timePassed2 = block.timestamp - _antiBot[recipient]; require(timePassed1 > antiDumpTime && timePassed2 > antiDumpTime, 'You must wait between transfers'); _antiBot[sender] = block.timestamp; _antiBot[recipient] = block.timestamp; } } if(_isWhitelist[sender] == true) { uint256 time_since_purchase = block.timestamp - _lockedTime[sender]; if(time_since_purchase < _lockPreSale[sender]){ require((balanceOf(sender) - amount) >= _lockedAmount[sender], 'You must wait time from purchase'); } else { _isWhitelist[sender] == false; } } if(sender != owner() && recipient != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForSwap; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } }
1,976,590
[ 1, 2047, 5793, 711, 5405, 343, 8905, 4982, 4075, 5349, 16, 1297, 2529, 2176, 1386, 30746, 358, 7412, 18, 1660, 1608, 358, 7720, 326, 783, 2430, 358, 512, 2455, 471, 1366, 358, 326, 13667, 310, 9230, 430, 1281, 2236, 11081, 358, 389, 291, 16461, 1265, 14667, 2236, 1508, 1206, 326, 14036, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 445, 389, 13866, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 3238, 288, 203, 5411, 2583, 12, 15330, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 5411, 2583, 12, 8949, 405, 374, 16, 315, 5912, 3844, 1297, 506, 6802, 2353, 3634, 8863, 203, 5411, 309, 24899, 291, 14925, 77, 10628, 1526, 422, 638, 597, 5793, 480, 3410, 1435, 597, 8027, 480, 3410, 10756, 95, 203, 7734, 309, 12, 15330, 422, 640, 291, 91, 438, 58, 22, 4154, 15329, 203, 10792, 2254, 5034, 813, 22530, 273, 1203, 18, 5508, 300, 389, 970, 77, 6522, 63, 20367, 15533, 203, 10792, 2583, 12, 957, 22530, 405, 30959, 10628, 950, 11189, 6225, 1297, 2529, 3086, 1284, 5489, 8284, 203, 10792, 389, 970, 77, 6522, 63, 20367, 65, 273, 1203, 18, 5508, 31, 203, 7734, 289, 203, 7734, 469, 309, 12, 20367, 422, 640, 291, 91, 438, 58, 22, 4154, 15329, 203, 10792, 2254, 5034, 813, 22530, 273, 1203, 18, 5508, 300, 389, 970, 77, 6522, 63, 15330, 15533, 203, 10792, 2583, 12, 957, 22530, 405, 30959, 10628, 950, 11189, 6225, 1297, 2529, 3086, 1284, 5489, 8284, 203, 10792, 389, 970, 77, 6522, 63, 15330, 65, 273, 1203, 18, 5508, 31, 203, 7734, 289, 203, 7734, 469, 309, 12, 15330, 480, 640, 291, 91, 438, 58, 22, 4154, 597, 8027, 480, 640, 291, 91, 438, 58, 22, 4154, 15329, 203, 10792, 2254, 5034, 813, 22530, 21, 273, 1203, 18, 5508, 300, 389, 970, 77, 6522, 63, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "./interfaces/IOniiChainDescriptor.sol"; import "./interfaces/IOniiChain.sol"; import "./libraries/NFTDescriptor.sol"; import "./libraries/DetailHelper.sol"; import "base64-sol/base64.sol"; /// @title Describes Onii /// @notice Produces a string containing the data URI for a JSON metadata string contract OniiChainDescriptor is IOniiChainDescriptor { /// @dev Max value for defining probabilities uint256 internal constant MAX = 100000; uint256[] internal BACKGROUND_ITEMS = [4000, 3400, 3080, 2750, 2400, 1900, 1200, 0]; uint256[] internal SKIN_ITEMS = [2000, 1000, 0]; uint256[] internal NOSE_ITEMS = [10, 0]; uint256[] internal MARK_ITEMS = [50000, 40000, 31550, 24550, 18550, 13550, 9050, 5550, 2550, 550, 50, 10, 0]; uint256[] internal EYEBROW_ITEMS = [65000, 40000, 20000, 10000, 4000, 0]; uint256[] internal MASK_ITEMS = [20000, 14000, 10000, 6000, 2000, 1000, 100, 0]; uint256[] internal EARRINGS_ITEMS = [50000, 38000, 28000, 20000, 13000, 8000, 5000, 2900, 1000, 100, 30, 0]; uint256[] internal ACCESSORY_ITEMS = [ 50000, 43000, 36200, 29700, 23400, 17400, 11900, 7900, 4400, 1400, 400, 200, 11, 1, 0 ]; uint256[] internal MOUTH_ITEMS = [ 80000, 63000, 48000, 36000, 27000, 19000, 12000, 7000, 4000, 2000, 1000, 500, 50, 0 ]; uint256[] internal HAIR_ITEMS = [ 97000, 94000, 91000, 88000, 85000, 82000, 79000, 76000, 73000, 70000, 67000, 64000, 61000, 58000, 55000, 52000, 49000, 46000, 43000, 40000, 37000, 34000, 31000, 28000, 25000, 22000, 19000, 16000, 13000, 10000, 3000, 1000, 0 ]; uint256[] internal EYE_ITEMS = [ 98000, 96000, 94000, 92000, 90000, 88000, 86000, 84000, 82000, 80000, 78000, 76000, 74000, 72000, 70000, 68000, 60800, 53700, 46700, 39900, 33400, 27200, 21200, 15300, 10600, 6600, 3600, 2600, 1700, 1000, 500, 100, 10, 0 ]; /// @inheritdoc IOniiChainDescriptor function tokenURI(IOniiChain oniiChain, uint256 tokenId) external view override returns (string memory) { NFTDescriptor.SVGParams memory params = getSVGParams(oniiChain, tokenId); params.background = getBackgroundId(params); string memory image = Base64.encode(bytes(NFTDescriptor.generateSVGImage(params))); string memory name = NFTDescriptor.generateName(params, tokenId); string memory description = NFTDescriptor.generateDescription(params); string memory attributes = NFTDescriptor.generateAttributes(params); return string( abi.encodePacked( "data:application/json;base64,", Base64.encode( bytes( abi.encodePacked( '{"name":"', name, '", "description":"', description, '", "attributes":', attributes, ', "image": "', "data:image/svg+xml;base64,", image, '"}' ) ) ) ) ); } /// @inheritdoc IOniiChainDescriptor function generateHairId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, HAIR_ITEMS, this.generateHairId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateEyeId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, EYE_ITEMS, this.generateEyeId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateEyebrowId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, EYEBROW_ITEMS, this.generateEyebrowId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateNoseId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, NOSE_ITEMS, this.generateNoseId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateMouthId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, MOUTH_ITEMS, this.generateMouthId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateMarkId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, MARK_ITEMS, this.generateMarkId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateEarringsId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, EARRINGS_ITEMS, this.generateEarringsId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateAccessoryId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, ACCESSORY_ITEMS, this.generateAccessoryId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateMaskId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, MASK_ITEMS, this.generateMaskId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateSkinId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, SKIN_ITEMS, this.generateSkinId.selector, tokenId); } /// @dev Get SVGParams from OniiChain.Detail function getSVGParams(IOniiChain oniiChain, uint256 tokenId) private view returns (NFTDescriptor.SVGParams memory) { IOniiChain.Detail memory detail = oniiChain.details(tokenId); return NFTDescriptor.SVGParams({ hair: detail.hair, eye: detail.eye, eyebrow: detail.eyebrow, nose: detail.nose, mouth: detail.mouth, mark: detail.mark, earring: detail.earrings, accessory: detail.accessory, mask: detail.mask, skin: detail.skin, original: detail.original, background: 0, timestamp: detail.timestamp, creator: detail.creator }); } function getBackgroundId(NFTDescriptor.SVGParams memory params) private view returns (uint8) { uint256 score = itemScorePosition(params.hair, HAIR_ITEMS) + itemScoreProba(params.accessory, ACCESSORY_ITEMS) + itemScoreProba(params.earring, EARRINGS_ITEMS) + itemScoreProba(params.mask, MASK_ITEMS) + itemScorePosition(params.mouth, MOUTH_ITEMS) + (itemScoreProba(params.skin, SKIN_ITEMS) / 2) + itemScoreProba(params.skin, SKIN_ITEMS) + itemScoreProba(params.nose, NOSE_ITEMS) + itemScoreProba(params.mark, MARK_ITEMS) + itemScorePosition(params.eye, EYE_ITEMS) + itemScoreProba(params.eyebrow, EYEBROW_ITEMS); return DetailHelper.pickItems(score, BACKGROUND_ITEMS); } /// @dev Get item score based on his probability function itemScoreProba(uint8 item, uint256[] memory ITEMS) private pure returns (uint256) { uint256 raw = ((item == 1 ? MAX : ITEMS[item - 2]) - ITEMS[item - 1]); return ((raw >= 1000) ? raw * 6 : raw) / 1000; } /// @dev Get item score based on his index function itemScorePosition(uint8 item, uint256[] memory ITEMS) private pure returns (uint256) { uint256 raw = ITEMS[item - 1]; return ((raw >= 1000) ? raw * 6 : raw) / 1000; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "./IOniiChain.sol"; /// @title Describes Onii via URI interface IOniiChainDescriptor { /// @notice Produces the URI describing a particular Onii (token id) /// @dev Note this URI may be a data: URI with the JSON contents directly inlined /// @param oniiChain The OniiChain contract /// @param tokenId The ID of the token for which to produce a description /// @return The URI of the ERC721-compliant metadata function tokenURI(IOniiChain oniiChain, uint256 tokenId) external view returns (string memory); /// @notice Generate randomly an ID for the hair item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the hair item id function generateHairId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the eye item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the eye item id function generateEyeId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the eyebrow item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the eyebrow item id function generateEyebrowId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the nose item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the nose item id function generateNoseId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the mouth item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the mouth item id function generateMouthId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the mark item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the mark item id function generateMarkId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the earrings item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the earrings item id function generateEarringsId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the accessory item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the accessory item id function generateAccessoryId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the mask item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the mask item id function generateMaskId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly the skin colors /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the skin item id function generateSkinId(uint256 tokenId, uint256 seed) external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; /// @title OniiChain NFTs Interface interface IOniiChain { /// @notice Details about the Onii struct Detail { uint8 hair; uint8 eye; uint8 eyebrow; uint8 nose; uint8 mouth; uint8 mark; uint8 earrings; uint8 accessory; uint8 mask; uint8 skin; bool original; uint256 timestamp; address creator; } /// @notice Returns the details associated with a given token ID. /// @dev Throws if the token ID is not valid. /// @param tokenId The ID of the token that represents the Onii /// @return detail memory function details(uint256 tokenId) external view returns (Detail memory detail); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "./details/BackgroundDetail.sol"; import "./details/BodyDetail.sol"; import "./details/HairDetail.sol"; import "./details/MouthDetail.sol"; import "./details/NoseDetail.sol"; import "./details/EyesDetail.sol"; import "./details/EyebrowDetail.sol"; import "./details/MarkDetail.sol"; import "./details/AccessoryDetail.sol"; import "./details/EarringsDetail.sol"; import "./details/MaskDetail.sol"; import "./DetailHelper.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; /// @notice Helper to generate SVGs library NFTDescriptor { struct SVGParams { uint8 hair; uint8 eye; uint8 eyebrow; uint8 nose; uint8 mouth; uint8 mark; uint8 earring; uint8 accessory; uint8 mask; uint8 background; uint8 skin; bool original; uint256 timestamp; address creator; } /// @dev Combine all the SVGs to generate the final image function generateSVGImage(SVGParams memory params) internal view returns (string memory) { return string( abi.encodePacked( generateSVGHead(), DetailHelper.getDetailSVG(address(BackgroundDetail), params.background), generateSVGFace(params), DetailHelper.getDetailSVG(address(EarringsDetail), params.earring), DetailHelper.getDetailSVG(address(HairDetail), params.hair), DetailHelper.getDetailSVG(address(MaskDetail), params.mask), DetailHelper.getDetailSVG(address(AccessoryDetail), params.accessory), generateCopy(params.original), "</svg>" ) ); } /// @dev Combine face items function generateSVGFace(SVGParams memory params) private view returns (string memory) { return string( abi.encodePacked( DetailHelper.getDetailSVG(address(BodyDetail), params.skin), DetailHelper.getDetailSVG(address(MarkDetail), params.mark), DetailHelper.getDetailSVG(address(MouthDetail), params.mouth), DetailHelper.getDetailSVG(address(NoseDetail), params.nose), DetailHelper.getDetailSVG(address(EyesDetail), params.eye), DetailHelper.getDetailSVG(address(EyebrowDetail), params.eyebrow) ) ); } /// @dev generate Json Metadata name function generateName(SVGParams memory params, uint256 tokenId) internal pure returns (string memory) { return string( abi.encodePacked( BackgroundDetail.getItemNameById(params.background), " Onii ", Strings.toString(tokenId) ) ); } /// @dev generate Json Metadata description function generateDescription(SVGParams memory params) internal pure returns (string memory) { return string( abi.encodePacked( "Generated by ", Strings.toHexString(uint256(uint160(params.creator))), " at ", Strings.toString(params.timestamp) ) ); } /// @dev generate SVG header function generateSVGHead() private pure returns (string memory) { return string( abi.encodePacked( '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px"', ' viewBox="0 0 420 420" style="enable-background:new 0 0 420 420;" xml:space="preserve">' ) ); } /// @dev generate the "Copy" SVG if the onii is not the original function generateCopy(bool original) private pure returns (string memory) { return !original ? string( abi.encodePacked( '<g id="Copy">', '<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M239.5,300.6c-4.9,1.8-5.9,8.1,1.3,4.1"/>', '<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M242.9,299.5c-2.6,0.8-1.8,4.3,0.8,4.2 C246.3,303.1,245.6,298.7,242.9,299.5"/>', '<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M247.5,302.9c0.2-1.6-1.4-4-0.8-5.4 c0.4-1.2,2.5-1.4,3.2-0.3c0.1,1.5-0.9,2.7-2.3,2.5"/>', '<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M250.6,295.4c1.1-0.1,2.2,0,3.3,0.1 c0.5-0.8,0.7-1.7,0.5-2.7"/>', '<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M252.5,299.1c0.5-1.2,1.2-2.3,1.4-3.5"/>', "</g>" ) ) : ""; } /// @dev generate Json Metadata attributes function generateAttributes(SVGParams memory params) internal pure returns (string memory) { return string( abi.encodePacked( "[", getJsonAttribute("Body", BodyDetail.getItemNameById(params.skin), false), getJsonAttribute("Hair", HairDetail.getItemNameById(params.hair), false), getJsonAttribute("Mouth", MouthDetail.getItemNameById(params.mouth), false), getJsonAttribute("Nose", NoseDetail.getItemNameById(params.nose), false), getJsonAttribute("Eyes", EyesDetail.getItemNameById(params.eye), false), getJsonAttribute("Eyebrow", EyebrowDetail.getItemNameById(params.eyebrow), false), abi.encodePacked( getJsonAttribute("Mark", MarkDetail.getItemNameById(params.mark), false), getJsonAttribute("Accessory", AccessoryDetail.getItemNameById(params.accessory), false), getJsonAttribute("Earrings", EarringsDetail.getItemNameById(params.earring), false), getJsonAttribute("Mask", MaskDetail.getItemNameById(params.mask), false), getJsonAttribute("Background", BackgroundDetail.getItemNameById(params.background), false), getJsonAttribute("Original", params.original ? "true" : "false", true), "]" ) ) ); } /// @dev Get the json attribute as /// { /// "trait_type": "Skin", /// "value": "Human" /// } function getJsonAttribute( string memory trait, string memory value, bool end ) private pure returns (string memory json) { return string(abi.encodePacked('{ "trait_type" : "', trait, '", "value" : "', value, '" }', end ? "" : ",")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; /// @title Helper for details generation library DetailHelper { /// @notice Call the library item function /// @param lib The library address /// @param id The item ID function getDetailSVG(address lib, uint8 id) internal view returns (string memory) { (bool success, bytes memory data) = lib.staticcall( abi.encodeWithSignature(string(abi.encodePacked("item_", Strings.toString(id), "()"))) ); require(success); return abi.decode(data, (string)); } /// @notice Generate a random number and return the index from the /// corresponding interval. /// @param max The maximum value to generate /// @param seed Used for the initialization of the number generator /// @param intervals the intervals /// @param selector Caller selector /// @param tokenId the current tokenId function generate( uint256 max, uint256 seed, uint256[] memory intervals, bytes4 selector, uint256 tokenId ) internal view returns (uint8) { uint256 generated = generateRandom(max, seed, tokenId, selector); return pickItems(generated, intervals); } /// @notice Generate random number between 1 and max /// @param max Maximum value of the random number /// @param seed Used for the initialization of the number generator /// @param tokenId Current tokenId used as seed /// @param selector Caller selector used as seed function generateRandom( uint256 max, uint256 seed, uint256 tokenId, bytes4 selector ) private view returns (uint256) { return (uint256( keccak256( abi.encodePacked(block.difficulty, block.number, tx.origin, tx.gasprice, selector, seed, tokenId) ) ) % (max + 1)) + 1; } /// @notice Pick an item for the given random value /// @param val The random value /// @param intervals The intervals for the corresponding items /// @return the item ID where : intervals[] index + 1 = item ID function pickItems(uint256 val, uint256[] memory intervals) internal pure returns (uint8) { for (uint256 i; i < intervals.length; i++) { if (val > intervals[i]) { return SafeCast.toUint8(i + 1); } } revert("DetailHelper::pickItems: No item"); } } // SPDX-License-Identifier: MIT /// @title Base64 /// @author Brecht Devos - <[email protected]> /// @notice Provides a function for encoding some bytes in base64 library Base64 { string internal constant TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; // load the table into memory string memory table = TABLE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { dataPtr := add(dataPtr, 3) // read 3 bytes let input := mload(dataPtr) // write 4 characters mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and( input, 0x3F))))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Background SVG generator library BackgroundDetail { /// @dev background N°1 => Ordinary function item_1() public pure returns (string memory) { return base("636363", "CFCFCF", "ABABAB"); } /// @dev background N°2 => Unusual function item_2() public pure returns (string memory) { return base("004A06", "61E89B", "12B55F"); } /// @dev background N°3 => Surprising function item_3() public pure returns (string memory) { return base("1A4685", "6BF0E3", "00ADC7"); } /// @dev background N°4 => Impressive function item_4() public pure returns (string memory) { return base("380113", "D87AE6", "8A07BA"); } /// @dev background N°5 => Extraordinary function item_5() public pure returns (string memory) { return base("A33900", "FAF299", "FF9121"); } /// @dev background N°6 => Phenomenal function item_6() public pure returns (string memory) { return base("000000", "C000E8", "DED52C"); } /// @dev background N°7 => Artistic function item_7() public pure returns (string memory) { return base("FF00E3", "E8E18B", "00C4AD"); } /// @dev background N°8 => Unreal function item_8() public pure returns (string memory) { return base("CCCC75", "54054D", "001E2E"); } /// @notice Return the background name of the given id /// @param id The background Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Ordinary"; } else if (id == 2) { name = "Unusual"; } else if (id == 3) { name = "Surprising"; } else if (id == 4) { name = "Impressive"; } else if (id == 5) { name = "Extraordinary"; } else if (id == 6) { name = "Phenomenal"; } else if (id == 7) { name = "Artistic"; } else if (id == 8) { name = "Unreal"; } } /// @dev The base SVG for the backgrounds function base( string memory stop1, string memory stop2, string memory stop3 ) private pure returns (string memory) { return string( abi.encodePacked( '<g id="Background">', '<radialGradient id="gradient" cx="210" cy="-134.05" r="210.025" gradientTransform="matrix(1 0 0 -1 0 76)" gradientUnits="userSpaceOnUse">', "<style>", ".color-anim {animation: col 6s infinite;animation-timing-function: ease-in-out;}", "@keyframes col {0%,51% {stop-color:none} 52% {stop-color:#FFBAF7} 53%,100% {stop-color:none}}", "</style>", "<stop offset='0' class='color-anim' style='stop-color:#", stop1, "'/>", "<stop offset='0.66' style='stop-color:#", stop2, "'><animate attributeName='offset' dur='18s' values='0.54;0.8;0.54' repeatCount='indefinite' keyTimes='0;.4;1'/></stop>", "<stop offset='1' style='stop-color:#", stop3, "'><animate attributeName='offset' dur='18s' values='0.86;1;0.86' repeatCount='indefinite'/></stop>", abi.encodePacked( "</radialGradient>", '<path fill="url(#gradient)" d="M390,420H30c-16.6,0-30-13.4-30-30V30C0,13.4,13.4,0,30,0h360c16.6,0,30,13.4,30,30v360C420,406.6,406.6,420,390,420z"/>', '<path id="Border" opacity="0.4" fill="none" stroke="#FFFFFF" stroke-width="2" stroke-miterlimit="10" d="M383.4,410H36.6C21.9,410,10,398.1,10,383.4V36.6C10,21.9,21.9,10,36.6,10h346.8c14.7,0,26.6,11.9,26.6,26.6v346.8 C410,398.1,398.1,410,383.4,410z"/>', '<path id="Mask" opacity="0.1" fill="#48005E" d="M381.4,410H38.6C22.8,410,10,397.2,10,381.4V38.6 C10,22.8,22.8,10,38.6,10h342.9c15.8,0,28.6,12.8,28.6,28.6v342.9C410,397.2,397.2,410,381.4,410z"/>', "</g>" ) ) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Body SVG generator library BodyDetail { /// @dev Body N°1 => Human function item_1() public pure returns (string memory) { return base("FFEBB4", "FFBE94"); } /// @dev Body N°2 => Shadow function item_2() public pure returns (string memory) { return base("2d2d2d", "000000"); } /// @dev Body N°3 => Light function item_3() public pure returns (string memory) { return base("ffffff", "696969"); } /// @notice Return the skin name of the given id /// @param id The skin Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Human"; } else if (id == 2) { name = "Shadow"; } else if (id == 3) { name = "Light"; } } /// @dev The base SVG for the body function base(string memory skin, string memory shadow) private pure returns (string memory) { string memory pathBase = "<path fill-rule='evenodd' clip-rule='evenodd' fill='#"; string memory strokeBase = "' stroke='#000000' stroke-linecap='round' stroke-miterlimit='10'"; return string( abi.encodePacked( '<g id="Body">', pathBase, skin, strokeBase, " d='M177.1,287.1c0.8,9.6,0.3,19.3-1.5,29.2c-0.5,2.5-2.1,4.7-4.5,6c-15.7,8.5-41.1,16.4-68.8,24.2c-7.8,2.2-9.1,11.9-2,15.7c69,37,140.4,40.9,215.4,6.7c6.9-3.2,7-12.2,0.1-15.4c-21.4-9.9-42.1-19.7-53.1-26.2c-2.5-1.5-4-3.9-4.3-6.5c-0.7-7.4-0.9-16.1-0.3-25.5c0.7-10.8,2.5-20.3,4.4-28.2'/>", abi.encodePacked( pathBase, shadow, "' d='M177.1,289c0,0,23.2,33.7,39.3,29.5s40.9-20.5,40.9-20.5c1.2-8.7,2.4-17.5,3.5-26.2c-4.6,4.7-10.9,10.2-19,15.3c-10.8,6.8-21,10.4-28.5,12.4L177.1,289z'/>", pathBase, skin, strokeBase, " d='M301.3,193.6c2.5-4.6,10.7-68.1-19.8-99.1c-29.5-29.9-96-34-128.1-0.3s-23.7,105.6-23.7,105.6s12.4,59.8,24.2,72c0,0,32.3,24.8,40.7,29.5c8.4,4.8,16.4,2.2,16.4,2.2c15.4-5.7,25.1-10.9,33.3-17.4'/>", pathBase ), skin, strokeBase, " d='M141.8,247.2c0.1,1.1-11.6,7.4-12.9-7.1c-1.3-14.5-3.9-18.2-9.3-34.5s9.1-8.4,9.1-8.4'/>", abi.encodePacked( pathBase, skin, strokeBase, " d='M254.8,278.1c7-8.6,13.9-17.2,20.9-25.8c1.2-1.4,2.9-2.1,4.6-1.7c3.9,0.8,11.2,1.2,12.8-6.7c2.3-11,6.5-23.5,12.3-33.6c3.2-5.7,0.7-11.4-2.2-15.3c-2.1-2.8-6.1-2.7-7.9,0.2c-2.6,4-5,7.9-7.6,11.9'/>", "<polygon fill-rule='evenodd' clip-rule='evenodd' fill='#", skin, "' points='272,237.4 251.4,270.4 260.9,268.6 276.9,232.4'/>", "<path d='M193.3,196.4c0.8,5.1,1,10.2,1,15.4c0,2.6-0.1,5.2-0.4,7.7c-0.3,2.6-0.7,5.1-1.3,7.6h-0.1c0.1-2.6,0.3-5.1,0.4-7.7c0.2-2.5,0.4-5.1,0.6-7.6c0.1-2.6,0.2-5.1,0.1-7.7C193.5,201.5,193.4,198.9,193.3,196.4L193.3,196.4z'/>", "<path fill='#", shadow ), "' d='M197.8,242.8l-7.9-3.5c-0.4-0.2-0.5-0.7-0.2-1.1l3.2-3.3c0.4-0.4,1-0.5,1.5-0.3l12.7,4.6c0.6,0.2,0.6,1.1-0.1,1.3l-8.7,2.4C198.1,242.9,197.9,242.9,197.8,242.8z'/>", "</g>" ) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; import "./constants/Colors.sol"; /// @title Hair SVG generator library HairDetail { /// @dev Hair N°1 => Classic Brown function item_1() public pure returns (string memory) { return base(classicHairs(Colors.BROWN)); } /// @dev Hair N°2 => Classic Black function item_2() public pure returns (string memory) { return base(classicHairs(Colors.BLACK)); } /// @dev Hair N°3 => Classic Gray function item_3() public pure returns (string memory) { return base(classicHairs(Colors.GRAY)); } /// @dev Hair N°4 => Classic White function item_4() public pure returns (string memory) { return base(classicHairs(Colors.WHITE)); } /// @dev Hair N°5 => Classic Blue function item_5() public pure returns (string memory) { return base(classicHairs(Colors.BLUE)); } /// @dev Hair N°6 => Classic Yellow function item_6() public pure returns (string memory) { return base(classicHairs(Colors.YELLOW)); } /// @dev Hair N°7 => Classic Pink function item_7() public pure returns (string memory) { return base(classicHairs(Colors.PINK)); } /// @dev Hair N°8 => Classic Red function item_8() public pure returns (string memory) { return base(classicHairs(Colors.RED)); } /// @dev Hair N°9 => Classic Purple function item_9() public pure returns (string memory) { return base(classicHairs(Colors.PURPLE)); } /// @dev Hair N°10 => Classic Green function item_10() public pure returns (string memory) { return base(classicHairs(Colors.GREEN)); } /// @dev Hair N°11 => Classic Saiki function item_11() public pure returns (string memory) { return base(classicHairs(Colors.SAIKI)); } /// @dev Hair N°12 => Classic 2 Brown function item_12() public pure returns (string memory) { return base(classicTwoHairs(Colors.BROWN)); } /// @dev Hair N°13 => Classic 2 Black function item_13() public pure returns (string memory) { return base(classicTwoHairs(Colors.BLACK)); } /// @dev Hair N°14 => Classic 2 Gray function item_14() public pure returns (string memory) { return base(classicTwoHairs(Colors.GRAY)); } /// @dev Hair N°15 => Classic 2 White function item_15() public pure returns (string memory) { return base(classicTwoHairs(Colors.WHITE)); } /// @dev Hair N°16 => Classic 2 Blue function item_16() public pure returns (string memory) { return base(classicTwoHairs(Colors.BLUE)); } /// @dev Hair N°17 => Classic 2 Yellow function item_17() public pure returns (string memory) { return base(classicTwoHairs(Colors.YELLOW)); } /// @dev Hair N°18 => Classic 2 Pink function item_18() public pure returns (string memory) { return base(classicTwoHairs(Colors.PINK)); } /// @dev Hair N°19 => Classic 2 Red function item_19() public pure returns (string memory) { return base(classicTwoHairs(Colors.RED)); } /// @dev Hair N°20 => Classic 2 Purple function item_20() public pure returns (string memory) { return base(classicTwoHairs(Colors.PURPLE)); } /// @dev Hair N°21 => Classic 2 Green function item_21() public pure returns (string memory) { return base(classicTwoHairs(Colors.GREEN)); } /// @dev Hair N°22 => Classic 2 Saiki function item_22() public pure returns (string memory) { return base(classicTwoHairs(Colors.SAIKI)); } /// @dev Hair N°23 => Short Black function item_23() public pure returns (string memory) { return base(shortHairs(Colors.BLACK)); } /// @dev Hair N°24 => Short Blue function item_24() public pure returns (string memory) { return base(shortHairs(Colors.BLUE)); } /// @dev Hair N°25 => Short Pink function item_25() public pure returns (string memory) { return base(shortHairs(Colors.PINK)); } /// @dev Hair N°26 => Short White function item_26() public pure returns (string memory) { return base(shortHairs(Colors.WHITE)); } /// @dev Hair N°27 => Spike Black function item_27() public pure returns (string memory) { return base(spike(Colors.BLACK)); } /// @dev Hair N°28 => Spike Blue function item_28() public pure returns (string memory) { return base(spike(Colors.BLUE)); } /// @dev Hair N°29 => Spike Pink function item_29() public pure returns (string memory) { return base(spike(Colors.PINK)); } /// @dev Hair N°30 => Spike White function item_30() public pure returns (string memory) { return base(spike(Colors.WHITE)); } /// @dev Hair N°31 => Monk function item_31() public pure returns (string memory) { return base(monk()); } /// @dev Hair N°32 => Nihon function item_32() public pure returns (string memory) { return base( string( abi.encodePacked( monk(), '<path opacity="0.36" fill="#6E5454" stroke="#8A8A8A" stroke-width="0.5" stroke-miterlimit="10" d=" M287.5,206.8c0,0,0.1-17.4-2.9-20.3c-3.1-2.9-7.3-8.7-7.3-8.7s0.6-24.8-2.9-31.8c-3.6-7-3.9-24.3-35-23.6 c-30.3,0.7-42.5,5.4-42.5,5.4s-14.2-8.2-43-3.8c-19.3,4.9-17.2,50.1-17.2,50.1s-5.6,9.5-6.2,14.8c-0.6,5.3-0.3,8.3-0.3,8.3 S111,72.1,216.8,70.4c108.4-1.7,87.1,121.7,85.1,122.4C295.4,190.1,293.9,197.7,287.5,206.8z"/>', '<g opacity="0.33">', '<ellipse transform="matrix(0.7071 -0.7071 0.7071 0.7071 0.367 227.089)" fill="#FFFFFF" cx="274.3" cy="113.1" rx="1.4" ry="5.3"/>', '<ellipse transform="matrix(0.5535 -0.8328 0.8328 0.5535 32.4151 255.0608)" fill="#FFFFFF" cx="254.1" cy="97.3" rx="4.2" ry="16.3"/>', "</g>", '<path fill="#FFFFFF" stroke="#2B232B" stroke-miterlimit="10" d="M136.2,125.1c0,0,72,9.9,162.2,0c0,0,4.4,14.9,4.8,26.6 c0,0-125.4,20.9-172.6-0.3C129.5,151.3,132.9,130.3,136.2,125.1z"/>', '<polygon fill="#FFFFFF" stroke="#2B232B" stroke-miterlimit="10" points="306.2,138 324.2,168.1 330,160"/>', '<path fill="#FFFFFF" stroke="#2B232B" stroke-miterlimit="10" d="M298.4,125.1l34.2,54.6l-18,15.5l-10.7-43.5 C302.3,142.2,299.9,128.8,298.4,125.1z"/>', '<ellipse opacity="0.87" fill="#FF0039" cx="198.2" cy="144.1" rx="9.9" ry="10.8"/>' ) ) ); } /// @dev Hair N°33 => Bald function item_33() public pure returns (string memory) { return base( string( abi.encodePacked( '<ellipse transform="matrix(0.7071 -0.7071 0.7071 0.7071 0.1733 226.5807)" fill="#FFFFFF" cx="273.6" cy="113.1" rx="1.4" ry="5.3"/>', '<ellipse transform="matrix(0.5535 -0.8328 0.8328 0.5535 32.1174 254.4671)" fill="#FFFFFF" cx="253.4" cy="97.3" rx="4.2" ry="16.3"/>' ) ) ); } /// @dev Generate classic hairs with the given color function classicHairs(string memory hairsColor) private pure returns (string memory) { return string( abi.encodePacked( "<path fill='#", hairsColor, "' stroke='#000000' stroke-width='0.5' stroke-miterlimit='10' d='M252.4,71.8c0,0-15.1-13.6-42.6-12.3l15.6,8.8c0,0-12.9-0.9-28.4-1.3c-6.1-0.2-21.8,3.3-38.3-1.4c0,0,7.3,7.2,9.4,7.7c0,0-30.6,13.8-47.3,34.2c0,0,10.7-8.9,16.7-10.9c0,0-26,25.2-31.5,70c0,0,9.2-28.6,15.5-34.2c0,0-10.7,27.4-5.3,48.2c0,0,2.4-14.5,4.9-19.2c-1,14.1,2.4,33.9,13.8,47.8c0,0-3.3-15.8-2.2-21.9l8.8-17.9c0.1,4.1,1.3,8.1,3.1,12.3c0,0,13-36.1,19.7-43.9c0,0-2.9,15.4-1.1,29.6c0,0,6.8-23.5,16.9-36.8c0,0-4.6,15.6-2.7,31.9c0,0,9.4-26.2,10.4-28.2l-2.7,9.2c0,0,4.1,21.6,3.8,25.3c0,0,8.4-10.3,21.2-52l-2.9,12c0,0,9.8,20.3,10.3,22.2s-1.3-13.9-1.3-13.9s12.4,21.7,13.5,26c0,0,5.5-20.8,3.4-35.7l1.1,9.6c0,0,15,20.3,16.4,30.1s-0.1-23.4-0.1-23.4s13.8,30.6,17,39.4c0,0,1.9-17,1.4-19.4s8.5,34.6,4.4,46c0,0,11.7-16.4,11.5-21.4c1.4,0.8-1.3,22.6-4,26.3c0,0,3.2-0.3,8.4-9.3c0,0,11.1-13.4,11.8-11.7c0.7,1.7,1.8-2.9,5.5,10.2l2.6-7.6c0,0-0.4,15.4-3.3,21.4c0,0,14.3-32.5,10.4-58.7c0,0,3.7,9.3,4.4,16.9s3.1-32.8-7.7-51.4c0,0,6.9,3.9,10.8,4.8c0,0-12.6-12.5-13.6-15.9c0,0-14.1-25.7-39.1-34.6c0,0,9.3-3.2,15.6,0.2C286.5,78.8,271.5,66.7,252.4,71.8z'/>", '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M286,210c0,0,8.5-10.8,8.6-18.7"/>', '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-miterlimit="10" d="M132.5,190.4c0,0-1.3-11.3,0.3-16.9"/>', '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-miterlimit="10" d="M141.5,170c0,0-1-6.5,1.6-20.4"/>', '<path opacity="0.2" d="M267.7,151.7l-0.3,30.9c0,0,1.9-18.8,1.8-19.3s8.6,43.5,3.9,47.2c0,0,11.9-18.8,12.1-21.5s0,22-3.9,25c0,0,6-4.4,8.6-10.1c0,0,6.1-7,9.9-10.7c0,0,3.9-1,6.8,8.2l2.8-6.9c0,0,0.1,13.4-1.3,16.1c0,0,10.5-28.2,7.9-52.9c0,0,4.7,8.3,4.9,17.1c0.1,8.8,1.7-8.6,0.2-17.8c0,0-6.5-13.9-8.2-15.4c0,0,2.2,14.9,1.3,18.4c0,0-8.2-15.1-11.4-17.3c0,0,1.2,41-1.6,46.1c0,0-6.8-22.7-11.4-26.5c0,0,0.7,17.4-3.6,23.2C284.5,183.3,280.8,169.9,267.7,151.7z"/>', '<path opacity="0.2" d="M234.3,137.1c0,0,17.1,23.2,16.7,30.2s-0.2-13.3-0.2-13.3s-11.7-22-17.6-26.2L234.3,137.1z"/>', '<polygon opacity="0.2" points="250.7,143.3 267.5,162.9 267.3,181.9"/>', '<path opacity="0.2" d="M207.4,129.2l9.7,20.7l-1-13.7c0,0,11.6,21,13.5,25.4l1.4-5l-17.6-27.4l1,7.5l-6-12.6L207.4,129.2z"/>', '<path opacity="0.2" d="M209.2,118c0,0-13.7,36.6-18.5,40.9c-1.7-7.2-1.9-7.9-4.2-20.3c0,0-0.1,2.7-1.4,5.3c0.7,8.2,4.1,24.4,4,24.5S206.4,136.6,209.2,118z"/>', '<path opacity="0.2" d="M187.6,134.7c0,0-9.6,25.5-10,26.9l-0.4-3.6C177.1,158.1,186.8,135.8,187.6,134.7z"/>', '<path opacity="0.2" fill-rule="evenodd" clip-rule="evenodd" d="M180.7,129.6c0,0-16.7,22.3-17.7,24.2s0,12.4,0.3,12.8S165.9,153,180.7,129.6z"/>', '<path opacity="0.2" fill-rule="evenodd" clip-rule="evenodd" d="M180.4,130.6c0,0-0.2,20.5-0.6,21.5c-0.4,0.9-2.6,5.8-2.6,5.8S176.1,147.1,180.4,130.6z"/>', abi.encodePacked( '<path opacity="0.2" d="M163.9,138c0,0-16.3,25.3-17.9,26.3c0,0-3.8-12.8-3-14.7s-9.6,10.3-9.9,17c0,0-8.4-0.6-11-7.4c-1-2.5,1.4-9.1,2.1-12.2c0,0-6.5,7.9-9.4,22.5c0,0,0.6,8.8,1.1,10c0,0,3.5-14.8,4.9-17.7c0,0-0.3,33.3,13.6,46.7c0,0-3.7-18.6-2.6-21l9.4-18.6c0,0,2.1,10.5,3.1,12.3l13.9-33.1L163.9,138z"/>', '<path fill="#FFFFFF" d="M204,82.3c0,0-10.3,24.4-11.5,30.4c0,0,11.1-20.6,12.6-20.8c0,0,11.4,20.4,12,22.2C217.2,114.1,208.2,88.2,204,82.3z"/>', '<path fill="#FFFFFF" d="M185.6,83.5c0,0-1,29.2,0,39.2c0,0-4-21.4-3.6-25.5c0.4-4-13.5,19.6-16,23.9c0,0,7.5-20.6,10.5-25.8c0,0-14.4,9.4-22,21.3C154.6,116.7,170.1,93.4,185.6,83.5z"/>', '<path fill="#FFFFFF" d="M158.6,96.2c0,0-12,15.3-14.7,23.2"/>', '<path fill="#FFFFFF" d="M125.8,125.9c0,0,9.5-20.6,23.5-27.7"/>', '<path fill="#FFFFFF" d="M296.5,121.6c0,0-9.5-20.6-23.5-27.7"/>', '<path fill="#FFFFFF" d="M216.1,88.5c0,0,10.9,19.9,11.6,23.6s3.7-5.5-10.6-23.6"/>', '<path fill="#FFFFFF" d="M227,92c0,0,21.1,25.4,22,27.4s-4.9-23.8-12.9-29.5c0,0,9.5,20.7,9.9,21.9C246.3,113,233.1,94.1,227,92z"/>', '<path fill="#FFFFFF" d="M263.1,119.5c0,0-9.5-26.8-10.6-28.3s15.5,14.1,16.2,22.5c0,0-11.1-16.1-11.8-16.9C256.1,96,264.3,114.1,263.1,119.5z"/>' ) ) ); } /// @dev Generate classic 2 hairs with the given color function classicTwoHairs(string memory hairsColor) private pure returns (string memory) { return string( abi.encodePacked( "<polygon fill='#", hairsColor, "' points='188.2,124.6 198.3,128.1 211.2,124.3 197.8,113.2'/>", '<polygon opacity="0.5" points="188.4,124.7 198.3,128.1 211.7,124.2 197.7,113.6"/>', "<path fill='#", hairsColor, "' stroke='#000000' stroke-width='0.5' stroke-miterlimit='10' d='M274,209.6c1,0.9,10.1-12.8,10.5-18.3 c1.1,3.2-0.2,16.8-2.9,20.5c0,0,3.7-0.7,8.3-6.5c0,0,11.1-13.4,11.8-11.7c0.7,1.7,1.8-2.9,5.5,10.2l2.6-7.6 c0,0-0.4,15.4-3.3,21.4c0,0,14.3-32.5,10.4-58.7c0,0,3.7,9.3,4.4,16.9s3.1-32.8-7.7-51.4c0,0,6.9,3.9,10.8,4.8 c0,0-12.6-12.5-13.6-15.9c0,0-14.1-25.7-39.1-34.6c0,0,9.3-3.2,15.6,0.2c-0.1-0.1-15.1-12.2-34.2-7.1c0,0-15.1-13.6-42.6-12.3 l15.6,8.8c0,0-12.9-0.9-28.4-1.3c-6.1-0.2-21.8,3.3-38.3-1.4c0,0,7.3,7.2,9.4,7.7c0,0-30.6,13.8-47.3,34.2 c0,0,10.7-8.9,16.7-10.9c0,0-26,25.2-31.5,70c0,0,9.2-28.6,15.5-34.2c0,0-10.7,27.4-5.3,48.2c0,0,2.4-14.5,4.9-19.2 c-1,14.1,2.4,33.9,13.8,47.8c0,0-3.3-15.8-2.2-21.9l8.8-17.9c0.1,4.1,1.3,8.1,3.1,12.3c0,0,13-36.1,19.7-43.9 c0,0-2.9,15.4-1.1,29.6c0,0,7.2-26.8,17.3-40.1c0,0,0.8,0.1,17.6-7.6c6.3,3.1,8,1.4,17.9,7.7c4.1,5.3,13.8,31.9,15.6,41.5 c3.4-7.3,5.6-19,5.2-29.5c2.7,3.7,8.9,19.9,9.6,34.3c0,0,7.9-15.9,5.9-29c0-0.2,0.2,14.5,0.3,14.3c0,0,12.1,19.9,14.9,19.7 c0-0.8-1.7-12.9-1.7-12.8c1.3,5.8,2.8,23.3,3.1,27.1l5-9.5C276.2,184,276.8,204.9,274,209.6z'/>", '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M286.7,210c0,0,8.5-10.8,8.6-18.7"/>', '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-miterlimit="10" d="M133.2,190.4 c0,0-1.3-11.3,0.3-16.9"/>', abi.encodePacked( '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-miterlimit="10" d="M142.2,170 c0,0-1-6.5,1.6-20.4"/>', '<path opacity="0.2" fill-rule="evenodd" clip-rule="evenodd" d="M180.6,128.2 c0,0-15.9,23.7-16.9,25.6s0,12.4,0.3,12.8S165.8,151.6,180.6,128.2z"/>', '<path opacity="0.2" d="M164.6,138c0,0-16.3,25.3-17.9,26.3c0,0-3.8-12.8-3-14.7s-9.6,10.3-9.9,17 c0,0-8.4-0.6-11-7.4c-1-2.5,1.4-9.1,2.1-12.2c0,0-6.5,7.9-9.4,22.5c0,0,0.6,8.8,1.1,10c0,0,3.5-14.8,4.9-17.7 c0,0-0.3,33.3,13.6,46.7c0,0-3.7-18.6-2.6-21l9.4-18.6c0,0,2.1,10.5,3.1,12.3l13.9-33.1L164.6,138z"/>', '<path opacity="0.16" d="M253.3,155.9c0.8,4.4,8.1,12.1,13.1,11.7l1.6,11c0,0-5.2-3.9-14.7-19.9 V155.9z"/>', '<path opacity="0.16" d="M237.6,139.4c0,0,4.4,3,13.9,21.7c0,0-4.3,12-4.6,12.4 C246.6,173.9,248.5,162.8,237.6,139.4z"/>', '<path opacity="0.17" d="M221,136.7c0,0,5.2,4,14.4,23c0,0-1.2,4.6-3.1,8.9 C227.7,152.4,227.1,149.9,221,136.7z"/>', '<path opacity="0.2" d="M272.1,152.6c-2.4,8.1-3.6,13.8-4.9,17.9c0,0,1.3,12.8,2.1,22.2 c4.7-8.4,5.4-8.8,5.4-9c-0.1-0.5,3.6,11.2-0.7,25.9c1.6,1,13.3-16.9,11.9-20.6c-1-2.5-0.4,19.8-4.3,22.8c0,0,6.4-2.2,9-7.9 c0,0,6.1-7,9.9-10.7c0,0,3.9-1,6.8,8.2l2.8-6.9c0,0,0.1,13.4-1.3,16.1c0,0,10.5-28.2,7.9-52.9c0,0,4.7,8.3,4.9,17.1 c0.1,8.8,1.7-8.6,0.2-17.8c0,0-6.5-13.9-8.2-15.4c0,0,2.2,14.9,1.3,18.4c0,0-8.2-15.1-11.4-17.3c0,0,1.2,41-1.6,46.1 c0,0-6.8-22.7-11.4-26.5c0,0-1.8,15.7-5,22.9C283.7,183,280.5,166.7,272.1,152.6z"/>' ), abi.encodePacked( '<path opacity="0.14" d="M198.2,115.2c-0.9-3.9,3.2-35.1,34.7-36C227.6,78.5,198.9,99.8,198.2,115.2z"/>', '<g opacity="0.76">', '<path fill="#FFFFFF" d="M153,105.9c0,0-12,15.3-14.7,23.2"/>', '<path fill="#FFFFFF" d="M126.5,125.9c0,0,9.5-20.6,23.5-27.7"/>', '<path fill="#FFFFFF" d="M297.2,121.6c0,0-9.5-20.6-23.5-27.7"/>', '<path fill="#FFFFFF" d="M241.9,109.4c0,0,10.9,19.9,11.6,23.6s3.7-5.5-10.6-23.6"/>', '<path fill="#FFFFFF" d="M155.1,117.3c0,0-10.9,19.9-11.6,23.6s-3.7-5.5,10.6-23.6"/>', '<path fill="#FFFFFF" d="M256.1,101.5c0,0,21.1,25.4,22,27.4c0.9,2-4.9-23.8-12.9-29.5c0,0,9.5,20.7,9.9,21.9 C275.4,122.5,262.2,103.6,256.1,101.5z"/>', '<path fill="#FFFFFF" d="M230,138.5c0,0-12.9-24.9-14.1-26.4c-1.2-1.4,18.2,11.9,19.3,20.2c0,0-11.9-13-12.7-13.7 C221.8,117.9,230.9,133,230,138.5z"/>', '<path fill="#FFFFFF" d="M167,136.6c0,0,15.5-24.5,17-25.8c1.5-1.2-19.1,10.6-21.6,18.8c0,0,15-13.5,15.8-14.2 C179.2,114.8,166.8,130.9,167,136.6z"/>', "</g>" ) ) ); } /// @dev Generate mohawk with the given color function spike(string memory hairsColor) private pure returns (string memory) { return string( abi.encodePacked( "<path fill='#", hairsColor, "' d='M287.3,207.1c0,0-0.4-17.7-3.4-20.6c-3.1-2.9-7.3-8.7-7.3-8.7s0.6-24.8-2.9-31.8c-3.6-7-3.9-24.3-35-23.6c-30.3,0.7-42.5,5.4-42.5,5.4s-14.2-8.2-43-3.8c-19.3,4.9-17.2,50.1-17.2,50.1s-5.6,9.5-6.2,14.8c-0.6,5.3-0.3,8.3-0.3,8.3c0.9-0.2-19.1-126.3,86.7-126.8c108.4-0.3,87.1,121.7,85.1,122.4C294.5,191.6,293.7,198,287.3,207.1z'/>", '<path fill-rule="evenodd" clip-rule="evenodd" fill="#212121" stroke="#000000" stroke-miterlimit="10" d="M196,124.6c0,0-30.3-37.5-20.6-77.7c0,0,0.7,18,12,25.1c0,0-8.6-13.4-0.3-33.4c0,0,2.7,15.8,10.7,23.4c0,0-2.7-18.4,2.2-29.6c0,0,9.7,23.2,13.9,26.3c0,0-6.5-17.2,5.4-27.7c0,0-0.8,18.6,9.8,25.4c0,0-2.7-11,4-18.9c0,0,1.2,25.1,6.6,29.4c0,0-2.7-12,2.1-20c0,0,6,24,8.6,28.5c-9.1-2.6-17.9-3.2-26.6-3C223.7,72.3,198,80.8,196,124.6z"/>', crop() ) ); } function shortHairs(string memory hairsColor) private pure returns (string memory) { return string( abi.encodePacked( "<path fill='#", hairsColor, "' d='M287.3,207.1c0,0-0.4-17.7-3.4-20.6c-3.1-2.9-7.3-8.7-7.3-8.7s0.6-24.8-2.9-31.8c-3.6-7-3.9-24.3-35-23.6c-30.3,0.7-42.5,5.4-42.5,5.4s-14.2-8.2-43-3.8c-19.3,4.9-17.2,50.1-17.2,50.1s-5.6,9.5-6.2,14.8c-0.6,5.3-0.3,8.3-0.3,8.3c0.9-0.2-19.1-126.3,86.7-126.8c108.4-0.3,87.1,121.7,85.1,122.4C294.5,191.6,293.7,198,287.3,207.1z'/>", '<path fill="#212121" stroke="#000000" stroke-miterlimit="10" d="M134.9,129.3c1-8.7,2.8-19.9,2.6-24.1 c1.1,2,4.4,6.1,4.7,6.9c2-15.1,3.9-18.6,6.6-28.2c0.1,5.2,0.4,6.1,4.6,11.9c0.1-7,4.5-17.6,8.8-24.3c0.6,3,4,8.2,5.8,10.7 c2.4-7,8.6-13.4,14.5-17.9c-0.3,3.4-0.1,6.8,0.7,10.1c4.9-5.1,7.1-8.7,15.6-15.4c-0.2,4.5,1.8,9,5.1,12c4.1-3.7,7.7-8,10.6-12.7 c0.6,3.7,1.4,7.3,2.5,10.8c2.6-4.6,7.9-8.4,12.4-11.3c1.5,3.5,1.3,11,5.9,11.7c7.1,1.1,10-3.3,11.4-10.1 c2.2,6.6,4.8,12.5,9.4,17.7c4.2,0.5,5.7-5.6,4.2-9c4.2,5.8,8.4,11.6,12.5,17.4c0.7-2.9,0.9-5.9,0.6-8.8 c3.4,7.6,9.1,16.7,13.6,23.6c0-1.9,1.8-8.5,1.8-10.4c2.6,7.3,7.7,17.9,10.3,36.6c0.2,1.1-23.8,7.5-28.8,10.1 c-1.2-2.3-2.2-4.3-6.2-8c-12.1-5.7-35.6-7.9-54.5-2.2c-16.3,4.8-21.5-2.3-31.3-3.1c-11.8-1.8-31.1-1.7-36.2,10.7 C139.6,133.6,137.9,132.2,134.9,129.3z"/>', '<polygon fill="#212121" points="270.7,138.4 300.2,129 300.7,131.1 271.3,139.9"/>', '<polygon fill="#212121" points="141.1,137 134,131.7 133.8,132.9 140.8,137.7 "/>', crop() ) ); } /// @dev Generate crop SVG function crop() private pure returns (string memory) { return string( abi.encodePacked( '<g id="Light" opacity="0.14">', '<ellipse transform="matrix(0.7071 -0.7071 0.7071 0.7071 0.1603 226.5965)" fill="#FFFFFF" cx="273.6" cy="113.1" rx="1.4" ry="5.3"/>', '<ellipse transform="matrix(0.5535 -0.8328 0.8328 0.5535 32.0969 254.4865)" fill="#FFFFFF" cx="253.4" cy="97.3" rx="4.2" ry="16.3"/>', "</g>", '<path opacity="0.05" fill-rule="evenodd" clip-rule="evenodd" d="M276.4,163.7c0,0,0.2-1.9,0.2,14.1c0,0,6.5,7.5,8.5,11s2.6,17.8,2.6,17.8l7-11.2c0,0,1.8-3.2,6.6-2.6c0,0,5.6-13.1,2.2-42.2C303.5,150.6,294.2,162.1,276.4,163.7z"/>', '<path opacity="0.1" fill-rule="evenodd" clip-rule="evenodd" d="M129.2,194.4c0,0-0.7-8.9,6.8-20.3c0,0-0.2-21.2,1.3-22.9c-3.7,0-6.7-0.5-7.7-2.4C129.6,148.8,125.8,181.5,129.2,194.4z"/>' ) ); } /// @dev Generate monk SVG function monk() private pure returns (string memory) { return string( abi.encodePacked( '<path opacity="0.36" fill="#6E5454" stroke="#8A8A8A" stroke-width="0.5" stroke-miterlimit="10" d="M286.8,206.8c0,0,0.1-17.4-2.9-20.3c-3.1-2.9-7.3-8.7-7.3-8.7s0.6-24.8-2.9-31.8c-3.6-7-3.9-24.3-35-23.6c-30.3,0.7-42.5,5.4-42.5,5.4s-14.2-8.2-43-3.8c-19.3,4.9-17.2,50.1-17.2,50.1s-5.6,9.5-6.2,14.8c-0.6,5.3-0.3,8.3-0.3,8.3S110.3,72.1,216.1,70.4c108.4-1.7,87.1,121.7,85.1,122.4C294.7,190.1,293.2,197.7,286.8,206.8z"/>', '<g id="Bald" opacity="0.33">', '<ellipse transform="matrix(0.7071 -0.7071 0.7071 0.7071 0.1603 226.5965)" fill="#FFFFFF" cx="273.6" cy="113.1" rx="1.4" ry="5.3"/>', '<ellipse transform="matrix(0.5535 -0.8328 0.8328 0.5535 32.0969 254.4865)" fill="#FFFFFF" cx="253.4" cy="97.3" rx="4.2" ry="16.3"/>', "</g>" ) ); } /// @notice Return the hair cut name of the given id /// @param id The hair Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Classic Brown"; } else if (id == 2) { name = "Classic Black"; } else if (id == 3) { name = "Classic Gray"; } else if (id == 4) { name = "Classic White"; } else if (id == 5) { name = "Classic Blue"; } else if (id == 6) { name = "Classic Yellow"; } else if (id == 7) { name = "Classic Pink"; } else if (id == 8) { name = "Classic Red"; } else if (id == 9) { name = "Classic Purple"; } else if (id == 10) { name = "Classic Green"; } else if (id == 11) { name = "Classic Saiki"; } else if (id == 12) { name = "Classic Brown"; } else if (id == 13) { name = "Classic 2 Black"; } else if (id == 14) { name = "Classic 2 Gray"; } else if (id == 15) { name = "Classic 2 White"; } else if (id == 16) { name = "Classic 2 Blue"; } else if (id == 17) { name = "Classic 2 Yellow"; } else if (id == 18) { name = "Classic 2 Pink"; } else if (id == 19) { name = "Classic 2 Red"; } else if (id == 20) { name = "Classic 2 Purple"; } else if (id == 21) { name = "Classic 2 Green"; } else if (id == 22) { name = "Classic 2 Saiki"; } else if (id == 23) { name = "Short Black"; } else if (id == 24) { name = "Short Blue"; } else if (id == 25) { name = "Short Pink"; } else if (id == 26) { name = "Short White"; } else if (id == 27) { name = "Spike Black"; } else if (id == 28) { name = "Spike Blue"; } else if (id == 29) { name = "Spike Pink"; } else if (id == 30) { name = "Spike White"; } else if (id == 31) { name = "Monk"; } else if (id == 32) { name = "Nihon"; } else if (id == 33) { name = "Bald"; } } /// @dev The base SVG for the hair function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Hair">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Mouth SVG generator library MouthDetail { /// @dev Mouth N°1 => Neutral function item_1() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M178.3,262.7c3.3-0.2,6.6-0.1,9.9,0c3.3,0.1,6.6,0.3,9.8,0.8c-3.3,0.3-6.6,0.3-9.9,0.2C184.8,263.6,181.5,263.3,178.3,262.7z"/>', '<path d="M201.9,263.4c1.2-0.1,2.3-0.1,3.5-0.2l3.5-0.2l6.9-0.3c2.3-0.1,4.6-0.2,6.9-0.4c1.2-0.1,2.3-0.2,3.5-0.3l1.7-0.2c0.6-0.1,1.1-0.2,1.7-0.2c-2.2,0.8-4.5,1.1-6.8,1.4s-4.6,0.5-7,0.6c-2.3,0.1-4.6,0.2-7,0.1C206.6,263.7,204.3,263.6,201.9,263.4z"/>', '<path d="M195.8,271.8c0.8,0.5,1.8,0.8,2.7,1s1.8,0.4,2.7,0.5s1.8,0,2.8-0.1c0.9-0.1,1.8-0.5,2.8-0.8c-0.7,0.7-1.6,1.3-2.6,1.6c-1,0.3-2,0.5-3,0.4s-2-0.3-2.9-0.8C197.3,273.2,196.4,272.7,195.8,271.8z"/>' ) ) ); } /// @dev Mouth N°2 => Smile function item_2() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M178.2,259.6c1.6,0.5,3.3,0.9,4.9,1.3c1.6,0.4,3.3,0.8,4.9,1.1c1.6,0.4,3.3,0.6,4.9,0.9c1.7,0.3,3.3,0.4,5,0.6c-1.7,0.2-3.4,0.3-5.1,0.2c-1.7-0.1-3.4-0.3-5.1-0.7C184.5,262.3,181.2,261.2,178.2,259.6z"/>', '<path d="M201.9,263.4l7-0.6c2.3-0.2,4.7-0.4,7-0.7c2.3-0.2,4.6-0.6,6.9-1c0.6-0.1,1.2-0.2,1.7-0.3l1.7-0.4l1.7-0.5l1.6-0.7c-0.5,0.3-1,0.7-1.5,0.9l-1.6,0.8c-1.1,0.4-2.2,0.8-3.4,1.1c-2.3,0.6-4.6,1-7,1.3s-4.7,0.4-7.1,0.5C206.7,263.6,204.3,263.6,201.9,263.4z"/>', '<path d="M195.8,271.8c0.8,0.5,1.8,0.8,2.7,1s1.8,0.4,2.7,0.5s1.8,0,2.8-0.1c0.9-0.1,1.8-0.5,2.8-0.8c-0.7,0.7-1.6,1.3-2.6,1.6c-1,0.3-2,0.5-3,0.4s-2-0.3-2.9-0.8C197.3,273.2,196.4,272.7,195.8,271.8z"/>' ) ) ); } /// @dev Mouth N°3 => Sulk function item_3() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M179.2,263.2c0,0,24.5,3.1,43.3-0.6"/>', '<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M176.7,256.8c0,0,6.7,6.8-0.6,11"/>', '<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M225.6,256.9c0,0-6.5,7,1,11"/>' ) ) ); } /// @dev Mouth N°4 => Poker function item_4() public pure returns (string memory) { return base( string( abi.encodePacked( '<line id="Poker" fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="180" y1="263" x2="226" y2="263"/>' ) ) ); } /// @dev Mouth N°5 => Angry function item_5() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M207.5,257.1c-7,1.4-17.3,0.3-21-0.9c-4-1.2-7.7,3.1-8.6,7.2c-0.5,2.5-1.2,7.4,3.4,10.1c5.9,2.4,5.6,0.1,9.2-1.9c3.4-2,10-1.1,15.3,1.9c5.4,3,13.4,2.2,17.9-0.4c2.9-1.7,3.3-7.6-4.2-14.1C217.3,257.2,215.5,255.5,207.5,257.1"/>', '<path fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M205.9,265.5l4.1-2.2c0,0,3.7,2.9,5,3s4.9-3.2,4.9-3.2l3.9,1.4"/>', '<polyline fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" points="177.8,265.3 180.2,263.4 183.3,265.5 186,265.4"/>' ) ) ); } /// @dev Mouth N°6 => Big Smile function item_6() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FFFFFF" stroke="#000000" stroke-miterlimit="10" d="M238.1,255.9c-26.1,4-68.5,0.3-68.5,0.3C170.7,256.3,199.6,296.4,238.1,255.9"/>', '<path fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M176.4,262.7c0,0,7.1,2.2,12,2.1"/>', '<path fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M230.6,262.8c0,0-10.4,2.1-17.7,1.8"/>' ) ) ); } /// @dev Mouth N°7 => Evil function item_7() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FFFFFF" stroke="#000000" stroke-miterlimit="10" d="M174.7,261.7c0,0,16.1-1.1,17.5-1.5s34.5,6.3,36.5,5.5s4.6-1.9,4.6-1.9s-14.1,8-43.6,7.9c0,0-3.9-0.7-4.7-1.8S177.1,262.1,174.7,261.7z"/>', '<polyline fill="none" stroke="#000000" stroke-miterlimit="10" points="181.6,266.7 185.5,265.3 189.1,266.5 190.3,265.9"/>', '<polyline fill="none" stroke="#000000" stroke-miterlimit="10" points="198.2,267 206.3,266.2 209.6,267.7 213.9,266.3 216.9,267.5 225.3,267"/>' ) ) ); } /// @dev Mouth N°8 => Tongue function item_8() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FF155D" d="M206.5,263.1c0,0,4,11.2,12.5,9.8c11.3-1.8,6.3-11.8,6.3-11.8L206.5,263.1z"/>', '<line fill="none" stroke="#73093E" stroke-miterlimit="10" x1="216.7" y1="262.5" x2="218.5" y2="267.3"/>', '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M201.9,263.4c0,0,20.7,0.1,27.7-4.3"/>', '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M178.2,259.6c0,0,9.9,4.2,19.8,3.9"/>' ) ) ); } /// @dev Mouth N°9 => Drool function item_9() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FEBCA6" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M190.4,257.5c2.5,0.6,5.1,0.8,7.7,0.5l17-2.1c0,0,13.3-1.8,12,3.6c-1.3,5.4-2.4,9.3-5.3,9.8c0,0,3.2,9.7-2.9,9c-3.7-0.4-2.4-7.7-2.4-7.7s-15.4,4.6-33.1-1.7c-1.8-0.6-3.6-2.6-4.4-3.9c-5.1-7.7-2-9.5-2-9.5S175.9,253.8,190.4,257.5z"/>' ) ) ); } /// @dev Mouth N°10 => O function item_10() public pure returns (string memory) { return base( string( abi.encodePacked( '<ellipse transform="matrix(0.9952 -9.745440e-02 9.745440e-02 0.9952 -24.6525 20.6528)" opacity="0.84" fill-rule="evenodd" clip-rule="evenodd" cx="199.1" cy="262.7" rx="3.2" ry="4.6"/>' ) ) ); } /// @dev Mouth N°11 => Dubu function item_11() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="none" stroke="#000000" stroke-width="0.75" stroke-linecap="round" stroke-miterlimit="10" d="M204.2,262c-8.9-7-25.1-3.5-4.6,6.6c-22-3.8-3.2,11.9,4.8,6"/>' ) ) ); } /// @dev Mouth N°12 => Stitch function item_12() public pure returns (string memory) { return base( string( abi.encodePacked( '<g opacity="0.84" fill-rule="evenodd" clip-rule="evenodd">', '<ellipse transform="matrix(0.9994 -3.403963e-02 3.403963e-02 0.9994 -8.8992 6.2667)" cx="179.6" cy="264.5" rx="2.3" ry="4.3"/>', '<ellipse transform="matrix(0.9996 -2.866329e-02 2.866329e-02 0.9996 -7.485 5.0442)" cx="172.2" cy="263.6" rx="1.5" ry="2.9"/>', '<ellipse transform="matrix(0.9996 -2.866329e-02 2.866329e-02 0.9996 -7.4594 6.6264)" cx="227.4" cy="263.5" rx="1.5" ry="2.9"/>', '<ellipse transform="matrix(0.9994 -3.403963e-02 3.403963e-02 0.9994 -8.8828 7.6318)" cx="219.7" cy="264.7" rx="2.5" ry="4.7"/>', '<ellipse transform="matrix(0.9994 -3.403963e-02 3.403963e-02 0.9994 -8.9179 6.57)" cx="188.5" cy="265.2" rx="2.9" ry="5.4"/>', '<ellipse transform="matrix(0.9994 -3.403963e-02 3.403963e-02 0.9994 -8.9153 7.3225)" cx="210.6" cy="265.5" rx="2.9" ry="5.4"/>', '<ellipse transform="matrix(0.9992 -3.983298e-02 3.983298e-02 0.9992 -10.4094 8.1532)" cx="199.4" cy="265.3" rx="4" ry="7.2"/>', "</g>" ) ) ); } /// @dev Mouth N°13 => Uwu function item_13() public pure returns (string memory) { return base( string( abi.encodePacked( '<polyline fill="#FFFFFF" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" points="212.7,262.9 216,266.5 217.5,261.7"/>', '<path fill="none" stroke="#000000" stroke-width="0.75" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M176.4,256c0,0,5.7,13.4,23.1,4.2"/>', '<path fill="none" stroke="#000000" stroke-width="0.75" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M224.7,254.8c0,0-9.5,15-25.2,5.4"/>' ) ) ); } /// @dev Mouth N°14 => Monster function item_14() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FFFFFF" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M161.4,255c0,0,0.5,0.1,1.3,0.3 c4.2,1,39.6,8.5,84.8-0.7C247.6,254.7,198.9,306.9,161.4,255z"/>', '<polyline fill="none" stroke="#000000" stroke-width="0.75" stroke-linejoin="round" stroke-miterlimit="10" points="165.1,258.9 167,256.3 170.3,264.6 175.4,257.7 179.2,271.9 187,259.1 190.8,276.5 197,259.7 202.1,277.5 207.8,259.1 213.8,275.4 217.9,258.7 224.1,271.2 226.5,257.9 232.7,266.2 235.1,256.8 238.6,262.1 241.3,255.8 243.8,257.6"/>' ) ) ); } /// @notice Return the mouth name of the given id /// @param id The mouth Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Neutral"; } else if (id == 2) { name = "Smile"; } else if (id == 3) { name = "Sulk"; } else if (id == 4) { name = "Poker"; } else if (id == 5) { name = "Angry"; } else if (id == 6) { name = "Big Smile"; } else if (id == 7) { name = "Evil"; } else if (id == 8) { name = "Tongue"; } else if (id == 9) { name = "Drool"; } else if (id == 10) { name = "O"; } else if (id == 11) { name = "Dubu"; } else if (id == 12) { name = "Stitch"; } else if (id == 13) { name = "Uwu"; } else if (id == 14) { name = "Monster"; } } /// @dev The base SVG for the mouth function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Mouth">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Nose SVG generator library NoseDetail { /// @dev Nose N°1 => Classic function item_1() public pure returns (string memory) { return ""; } /// @dev Nose N°2 => Bleeding function item_2() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#E90000" d="M205.8,254.1C205.8,254.1,205.9,254.1,205.8,254.1c0.1,0,0.1,0.1,0.1,0.1c0,0.2,0,0.5-0.2,0.7c-0.1,0.1-0.3,0.1-0.4,0.1c-0.4,0-0.8,0.1-1.2,0.1c-0.2,0-0.7,0.2-0.8,0s0.1-0.4,0.2-0.5c0.3-0.2,0.7-0.2,1-0.3C204.9,254.3,205.4,254.1,205.8,254.1z"/>', '<path fill="#E90000" d="M204.3,252.8c0.3-0.1,0.6-0.2,0.9-0.1c0.1,0.2,0.1,0.4,0.2,0.6c0,0.1,0,0.1,0,0.2c0,0.1-0.1,0.1-0.2,0.1c-0.7,0.2-1.4,0.3-2.1,0.5c-0.2,0-0.3,0.1-0.4-0.1c0-0.1-0.1-0.2,0-0.3c0.1-0.2,0.4-0.3,0.6-0.4C203.6,253.1,203.9,252.9,204.3,252.8z"/>', '<path fill="#FF0000" d="M204.7,240.2c0.3,1.1,0.1,2.3-0.1,3.5c-0.3,2-0.5,4.1,0,6.1c0.1,0.4,0.3,0.9,0.2,1.4c-0.2,0.9-1.1,1.3-2,1.6c-0.1,0-0.2,0.1-0.4,0.1c-0.3-0.1-0.4-0.5-0.4-0.8c-0.1-1.9,0.5-3.9,0.8-5.8c0.3-1.7,0.3-3.2-0.1-4.8c-0.1-0.5-0.3-0.9,0.1-1.3C203.4,239.7,204.6,239.4,204.7,240.2z"/>' ) ) ); } /// @notice Return the nose name of the given id /// @param id The nose Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Classic"; } else if (id == 2) { name = "Bleeding"; } } /// @dev The base SVG for the Nose function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Nose bonus">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; import "./constants/Colors.sol"; /// @title Eyes SVG generator library EyesDetail { /// @dev Eyes N°1 => Color White/Brown function item_1() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.BROWN); } /// @dev Eyes N°2 => Color White/Gray function item_2() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.GRAY); } /// @dev Eyes N°3 => Color White/Blue function item_3() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.BLUE); } /// @dev Eyes N°4 => Color White/Green function item_4() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.GREEN); } /// @dev Eyes N°5 => Color White/Black function item_5() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.BLACK_DEEP); } /// @dev Eyes N°6 => Color White/Yellow function item_6() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.YELLOW); } /// @dev Eyes N°7 => Color White/Red function item_7() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.RED); } /// @dev Eyes N°8 => Color White/Purple function item_8() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.PURPLE); } /// @dev Eyes N°9 => Color White/Pink function item_9() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.PINK); } /// @dev Eyes N°10 => Color White/White function item_10() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.WHITE); } /// @dev Eyes N°11 => Color Black/Blue function item_11() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.BLACK, Colors.BLUE); } /// @dev Eyes N°12 => Color Black/Yellow function item_12() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.BLACK, Colors.YELLOW); } /// @dev Eyes N°13 => Color Black/White function item_13() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.BLACK, Colors.WHITE); } /// @dev Eyes N°14 => Color Black/Red function item_14() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.BLACK, Colors.RED); } /// @dev Eyes N°15 => Blank White/White function item_15() public pure returns (string memory) { return eyesNoFillAndBlankPupils(Colors.WHITE, Colors.WHITE); } /// @dev Eyes N°16 => Blank Black/White function item_16() public pure returns (string memory) { return eyesNoFillAndBlankPupils(Colors.BLACK_DEEP, Colors.WHITE); } /// @dev Eyes N°17 => Shine (no-fill) function item_17() public pure returns (string memory) { return base( string( abi.encodePacked( eyesNoFill(Colors.WHITE), '<path fill="#FFEE00" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M161.4,195.1c1.4,7.4,1.4,7.3,8.8,8.8 c-7.4,1.4-7.3,1.4-8.8,8.8c-1.4-7.4-1.4-7.3-8.8-8.8C160,202.4,159.9,202.5,161.4,195.1z"/>', '<path fill="#FFEE00" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M236.1,194.9c1.4,7.4,1.4,7.3,8.8,8.8 c-7.4,1.4-7.3,1.4-8.8,8.8c-1.4-7.4-1.4-7.3-8.8-8.8C234.8,202.3,234.7,202.3,236.1,194.9z"/>' ) ) ); } /// @dev Eyes N°18 => Stun (no-fill) function item_18() public pure returns (string memory) { return base( string( abi.encodePacked( eyesNoFill(Colors.WHITE), '<path d="M233.6,205.2c0.2-0.8,0.6-1.7,1.3-2.3c0.4-0.3,0.9-0.5,1.3-0.4c0.5,0.1,0.9,0.4,1.2,0.8c0.5,0.8,0.6,1.8,0.6,2.7c0,0.9-0.4,1.9-1.1,2.6c-0.7,0.7-1.7,1.1-2.7,1c-1-0.1-1.8-0.7-2.5-1.2c-0.7-0.5-1.4-1.2-1.9-2c-0.5-0.8-0.8-1.8-0.7-2.8c0.1-1,0.5-1.9,1.1-2.6c0.6-0.7,1.4-1.3,2.2-1.7c1.7-0.8,3.6-1,5.3-0.6c0.9,0.2,1.8,0.5,2.5,1.1c0.7,0.6,1.2,1.5,1.3,2.4c0.3,1.8-0.3,3.7-1.4,4.9c1-1.4,1.4-3.2,1-4.8c-0.2-0.8-0.6-1.5-1.3-2c-0.6-0.5-1.4-0.8-2.2-0.9c-1.6-0.2-3.4,0-4.8,0.7c-1.4,0.7-2.7,2-2.8,3.5c-0.2,1.5,0.9,3,2.2,4c0.7,0.5,1.3,1,2.1,1.1c0.7,0.1,1.5-0.2,2.1-0.7c0.6-0.5,0.9-1.3,1-2.1c0.1-0.8,0-1.7-0.4-2.3c-0.2-0.3-0.5-0.6-0.8-0.7c-0.4-0.1-0.8,0-1.1,0.2C234.4,203.6,233.9,204.4,233.6,205.2z"/>', '<path d="M160.2,204.8c0.7-0.4,1.6-0.8,2.5-0.7c0.4,0,0.9,0.3,1.2,0.7c0.3,0.4,0.3,0.9,0.2,1.4c-0.2,0.9-0.8,1.7-1.5,2.3c-0.7,0.6-1.6,1.1-2.6,1c-1,0-2-0.4-2.6-1.2c-0.7-0.8-0.8-1.8-1-2.6c-0.1-0.9-0.1-1.8,0.1-2.8c0.2-0.9,0.7-1.8,1.5-2.4c0.8-0.6,1.7-1,2.7-1c0.9-0.1,1.9,0.1,2.7,0.4c1.7,0.6,3.2,1.8,4.2,3.3c0.5,0.7,0.9,1.6,1,2.6c0.1,0.9-0.2,1.9-0.8,2.6c-1.1,1.5-2.8,2.4-4.5,2.5c1.7-0.3,3.3-1.3,4.1-2.7c0.4-0.7,0.6-1.5,0.5-2.3c-0.1-0.8-0.5-1.5-1-2.2c-1-1.3-2.4-2.4-3.9-2.9c-1.5-0.5-3.3-0.5-4.5,0.5c-1.2,1-1.5,2.7-1.3,4.3c0.1,0.8,0.2,1.6,0.7,2.2c0.4,0.6,1.2,0.9,1.9,1c0.8,0,1.5-0.2,2.2-0.8c0.6-0.5,1.2-1.2,1.4-1.9c0.1-0.4,0.1-0.8-0.1-1.1c-0.2-0.3-0.5-0.6-0.9-0.6C161.9,204.2,161,204.4,160.2,204.8z"/>' ) ) ); } /// @dev Eyes N°19 => Squint (no-fill) function item_19() public pure returns (string memory) { return base( string( abi.encodePacked( eyesNoFill(Colors.WHITE), '<path d="M167.3,203.7c0.1,7.7-12,7.7-11.9,0C155.3,196,167.4,196,167.3,203.7z"/>', '<path d="M244.8,205.6c-1.3,7.8-13.5,5.6-12-2.2C234.2,195.6,246.4,197.9,244.8,205.6z"/>' ) ) ); } /// @dev Eyes N°20 => Shock (no-fill) function item_20() public pure returns (string memory) { return base( string( abi.encodePacked( eyesNoFill(Colors.WHITE), '<path fill-rule="evenodd" clip-rule="evenodd" d="M163.9,204c0,2.7-4.2,2.7-4.1,0C159.7,201.3,163.9,201.3,163.9,204z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" d="M236.7,204c0,2.7-4.2,2.7-4.1,0C232.5,201.3,236.7,201.3,236.7,204z"/>' ) ) ); } /// @dev Eyes N°21 => Cat (no-fill) function item_21() public pure returns (string memory) { return base( string( abi.encodePacked( eyesNoFill(Colors.WHITE), '<path d="M238.4,204.2c0.1,13.1-4.5,13.1-4.5,0C233.8,191.2,238.4,191.2,238.4,204.2z"/>', '<path d="M164.8,204.2c0.1,13-4.5,13-4.5,0C160.2,191.2,164.8,191.2,164.8,204.2z"/>' ) ) ); } /// @dev Eyes N°22 => Ether (no-fill) function item_22() public pure returns (string memory) { return base( string( abi.encodePacked( eyesNoFill(Colors.WHITE), '<path d="M161.7,206.4l-4.6-2.2l4.6,8l4.6-8L161.7,206.4z"/>', '<path d="M165.8,202.6l-4.1-7.1l-4.1,7.1l4.1-1.9L165.8,202.6z"/>', '<path d="M157.9,203.5l3.7,1.8l3.8-1.8l-3.8-1.8L157.9,203.5z"/>', '<path d="M236.1,206.6l-4.6-2.2l4.6,8l4.6-8L236.1,206.6z"/>', '<path d="M240.2,202.8l-4.1-7.1l-4.1,7.1l4.1-1.9L240.2,202.8z"/>', '<path d="M232.4,203.7l3.7,1.8l3.8-1.8l-3.8-1.8L232.4,203.7z"/>' ) ) ); } /// @dev Eyes N°23 => Feels function item_23() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M251.1,201.4c0.7,0.6,1,2.2,1,2.7c-0.1-0.4-1.4-1.1-2.2-1.7c-0.2,0.1-0.4,0.4-0.6,0.5c0.5,0.7,0.7,2,0.7,2.5c-0.1-0.4-1.3-1.1-2.1-1.6c-2.7,1.7-6.4,3.2-11.5,3.7c-8.1,0.7-16.3-1.7-20.9-6.4c5.9,3.1,13.4,4.5,20.9,3.8c6.6-0.6,12.7-2.9,17-6.3C253.4,198.9,252.6,200.1,251.1,201.4z"/>', '<path d="M250,205.6L250,205.6C250.1,205.9,250.1,205.8,250,205.6z"/>', '<path d="M252.1,204.2L252.1,204.2C252.2,204.5,252.2,204.4,252.1,204.2z"/>', '<path d="M162.9,207.9c-4.1-0.4-8-1.4-11.2-2.9c-0.7,0.3-3.1,1.4-3.3,1.9c0.1-0.6,0.3-2.2,1.3-2.8c0.1-0.1,0.2-0.1,0.3-0.1c-0.2-0.1-0.5-0.3-0.7-0.4c-0.8,0.4-3,1.3-3.2,1.9c0.1-0.6,0.3-2.2,1.3-2.8c0.1-0.1,0.3-0.1,0.5-0.1c-0.9-0.7-1.7-1.6-2.4-2.4c1.5,1.1,6.9,4.2,17.4,5.3c11.9,1.2,18.3-4,19.8-4.7C177.7,205.3,171.4,208.8,162.9,207.9z"/>', '<path d="M148.5,207L148.5,207C148.5,207.1,148.5,207.2,148.5,207z"/>', '<path d="M146.2,205.6L146.2,205.6C146.2,205.7,146.2,205.7,146.2,205.6z"/>' ) ) ); } /// @dev Eyes N°24 => Happy function item_24() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M251.5,203.5c0.7-0.7,0.9-2.5,0.9-3.2c-0.1,0.5-1.3,1.4-2.2,1.9c-0.2-0.2-0.4-0.4-0.6-0.6c0.5-0.8,0.7-2.4,0.7-3 c-0.1,0.5-1.2,1.4-2.1,1.9c-2.6-1.9-6.2-3.8-11-4.3c-7.8-0.8-15.7,2-20.1,7.5c5.7-3.6,12.9-5.3,20.1-4.5 c6.4,0.8,12.4,2.9,16.5,6.9C253.3,205.1,252.3,204,251.5,203.5z"/>', '<path d="M250.3,198.6L250.3,198.6C250.4,198.2,250.4,198.3,250.3,198.6z"/>', '<path d="M252.4,200.3L252.4,200.3C252.5,199.9,252.5,200,252.4,200.3z"/>', '<path d="M228.2,192.6c1.1-0.3,2.3-0.5,3.5-0.6c1.1-0.1,2.4-0.1,3.5,0s2.4,0.3,3.5,0.5s2.3,0.6,3.3,1.1l0,0 c-1.1-0.3-2.3-0.6-3.4-0.8c-1.1-0.3-2.3-0.4-3.4-0.5c-1.1-0.1-2.4-0.2-3.5-0.1C230.5,192.3,229.4,192.4,228.2,192.6L228.2,192.6z"/>', '<path d="M224.5,193.8c-0.9,0.6-2,1.1-3,1.7c-0.9,0.6-2,1.2-3,1.7c0.4-0.4,0.8-0.8,1.2-1.1s0.9-0.7,1.4-0.9c0.5-0.3,1-0.6,1.5-0.8C223.3,194.2,223.9,193.9,224.5,193.8z"/>', '<path d="M161.3,195.8c-3.7,0.4-7.2,1.6-10.1,3.5c-0.6-0.3-2.8-1.6-3-2.3c0.1,0.7,0.3,2.6,1.1,3.3c0.1,0.1,0.2,0.2,0.3,0.2 c-0.2,0.2-0.4,0.3-0.6,0.5c-0.7-0.4-2.7-1.5-2.9-2.2c0.1,0.7,0.3,2.6,1.1,3.3c0.1,0.1,0.3,0.2,0.4,0.2c-0.8,0.8-1.6,1.9-2.2,2.9 c1.3-1.4,6.3-5,15.8-6.3c10.9-1.4,16.7,4.7,18,5.5C174.8,198.9,169.1,194.8,161.3,195.8z"/>', '<path d="M148.2,196.9L148.2,196.9C148.2,196.8,148.2,196.7,148.2,196.9z"/>', '<path d="M146.1,198.6L146.1,198.6C146.1,198.5,146.1,198.4,146.1,198.6z"/>', '<path d="M167.5,192.2c-1.1-0.2-2.3-0.3-3.5-0.3c-1.1,0-2.4,0-3.5,0.2c-1.1,0.1-2.3,0.3-3.4,0.5c-1.1,0.3-2.3,0.5-3.4,0.8 c2.1-0.9,4.3-1.5,6.7-1.7c1.1-0.1,2.4-0.1,3.5-0.1C165.3,191.7,166.4,191.9,167.5,192.2z"/>', '<path d="M171.4,193.4c0.6,0.2,1.1,0.3,1.7,0.6c0.5,0.3,1,0.5,1.6,0.8c0.5,0.3,1,0.6,1.4,0.9c0.5,0.3,0.9,0.7,1.3,1 c-1-0.5-2.1-1.1-3-1.6C173.3,194.5,172.3,193.9,171.4,193.4z"/>' ) ) ); } /// @dev Eyes N°25 => Arrow function item_25() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="none" stroke="#000000" stroke-width="1.5" stroke-linejoin="round" stroke-miterlimit="10" d="M251.4,192.5l-30.8,8 c10.9,1.9,20.7,5,29.5,9.1"/>', '<path fill="none" stroke="#000000" stroke-width="1.5" stroke-linejoin="round" stroke-miterlimit="10" d="M149.4,192.5l30.8,8 c-10.9,1.9-20.7,5-29.5,9.1"/>' ) ) ); } /// @dev Eyes N°26 => Closed function item_26() public pure returns (string memory) { return base( string( abi.encodePacked( '<line fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10" x1="216.3" y1="200.2" x2="259" y2="198.3"/>', '<line fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10" x1="179.4" y1="200.2" x2="143.4" y2="198.3"/>' ) ) ); } /// @dev Eyes N°27 => Suspicious function item_27() public pure returns (string memory) { return base( string( abi.encodePacked( '<path opacity="0.81" fill="#FFFFFF" d="M220.3,202.5c-0.6,4.6,0.1,5.8,1.6,8.3 c0.9,1.5,1,2.5,8.2-1.2c6.1,0.4,8.2-1.6,16,2.5c3,0,4-3.8,5.1-7.7c0.6-2.2-0.2-4.6-2-5.9c-3.4-2.5-9-6-13.4-5.3 c-3.9,0.7-7.7,1.9-11.3,3.6C222.3,197.9,221,197.3,220.3,202.5z"/>', '<path d="M251.6,200c0.7-0.8,0.9-2.9,0.9-3.7c-0.1,0.6-1.3,1.5-2,2.2c-0.2-0.2-0.4-0.5-0.6-0.7c0.5-1,0.7-2.7,0.7-3.4 c-0.1,0.6-1.2,1.5-1.9,2.1c-2.4-2.2-5.8-4.4-10.4-4.9c-7.4-1-14.7,2.3-18.9,8.6c5.3-4.2,12.1-6,18.9-5.1c6,0.9,11.5,4,15.4,8.5 C253.6,203.4,252.9,201.9,251.6,200z"/>', '<path d="M250.5,194.4L250.5,194.4C250.6,194,250.6,194.1,250.5,194.4z"/>', '<path d="M252.4,196.3L252.4,196.3C252.5,195.9,252.5,196,252.4,196.3z"/>', '<path d="M229.6,187.6c1.1-0.3,2.1-0.6,3.3-0.7c1.1-0.1,2.2-0.1,3.3,0s2.2,0.3,3.3,0.6s2.1,0.7,3.1,1.3l0,0 c-1.1-0.3-2.1-0.7-3.2-0.9c-1.1-0.3-2.1-0.5-3.2-0.6c-1.1-0.1-2.2-0.2-3.3-0.1C231.9,187.2,230.8,187.3,229.6,187.6L229.6,187.6 z"/>', '<path d="M226.1,189c-0.9,0.7-1.8,1.3-2.8,1.9c-0.9,0.7-1.8,1.4-2.8,1.9c0.4-0.5,0.8-0.9,1.2-1.3c0.4-0.4,0.9-0.8,1.4-1.1 s1-0.7,1.5-0.9C225.1,189.4,225.7,189.1,226.1,189z"/>', '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M222,212.8c0,0,9.8-7.3,26.9,0"/>', '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M229,195.2c0,0-4.6,8.5,0.7,14.4 c0,0,8.8-1.5,11.6,0.4c0,0,4.7-5.7,1.5-12.5S229,195.2,229,195.2z"/>', '<path opacity="0.81" fill="#FFFFFF" d="M177.1,202.5c0.6,4.6-0.1,5.8-1.6,8.3 c-0.9,1.5-1,2.5-8.2-1.2c-6.1,0.4-8.2-1.6-16,2.5c-3,0-4-3.8-5.1-7.7c-0.6-2.2,0.2-4.6,2-5.9c3.4-2.5,9-6,13.4-5.3 c3.9,0.7,7.7,1.9,11.3,3.6C175.2,197.9,176.4,197.3,177.1,202.5z"/>', '<path d="M145.9,200c-0.7-0.8-0.9-2.9-0.9-3.7c0.1,0.6,1.3,1.5,2,2.2c0.2-0.2,0.4-0.5,0.6-0.7c-0.5-1-0.7-2.7-0.7-3.4 c0.1,0.6,1.2,1.5,1.9,2.1c2.4-2.2,5.8-4.4,10.4-4.9c7.4-1,14.7,2.3,18.9,8.6c-5.3-4.2-12.1-6-18.9-5.1c-6,0.9-11.5,4-15.4,8.5 C143.8,203.4,144.5,201.9,145.9,200z"/>', '<path d="M146.9,194.4L146.9,194.4C146.9,194,146.9,194.1,146.9,194.4z"/>', abi.encodePacked( '<path d="M145,196.3L145,196.3C144.9,195.9,144.9,196,145,196.3z"/>', '<path d="M167.8,187.6c-1.1-0.3-2.1-0.6-3.3-0.7c-1.1-0.1-2.2-0.1-3.3,0s-2.2,0.3-3.3,0.6s-2.1,0.7-3.1,1.3l0,0 c1.1-0.3,2.1-0.7,3.2-0.9c1.1-0.3,2.1-0.5,3.2-0.6c1.1-0.1,2.2-0.2,3.3-0.1C165.6,187.2,166.6,187.3,167.8,187.6L167.8,187.6z"/>', '<path d="M171.3,189c0.9,0.7,1.8,1.3,2.8,1.9c0.9,0.7,1.8,1.4,2.8,1.9c-0.4-0.5-0.8-0.9-1.2-1.3c-0.4-0.4-0.9-0.8-1.4-1.1 s-1-0.7-1.5-0.9C172.4,189.4,171.8,189.1,171.3,189z"/>', '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M175.4,212.8c0,0-9.8-7.3-26.9,0"/>', '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M168.5,195.2c0,0,4.6,8.5-0.7,14.4 c0,0-8.8-1.5-11.6,0.4c0,0-4.7-5.7-1.5-12.5S168.5,195.2,168.5,195.2z"/>' ) ) ) ); } /// @dev Eyes N°28 => Annoyed 1 function item_28() public pure returns (string memory) { return base( string( abi.encodePacked( '<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="218" y1="195.2" x2="256" y2="195.2"/>', '<path stroke="#000000" stroke-miterlimit="10" d="M234,195.5c0,5.1,4.1,9.2,9.2,9.2s9.2-4.1,9.2-9.2"/>', '<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="143.2" y1="195.7" x2="181.1" y2="195.7"/>', '<path stroke="#000000" stroke-miterlimit="10" d="M158.7,196c0,5.1,4.1,9.2,9.2,9.2c5.1,0,9.2-4.1,9.2-9.2"/>' ) ) ); } /// @dev Eyes N°29 => Annoyed 2 function item_29() public pure returns (string memory) { return base( string( abi.encodePacked( '<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="218" y1="195.2" x2="256" y2="195.2"/>', '<path stroke="#000000" stroke-miterlimit="10" d="M228,195.5c0,5.1,4.1,9.2,9.2,9.2s9.2-4.1,9.2-9.2"/>', '<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="143.2" y1="195.7" x2="181.1" y2="195.7"/>', '<path stroke="#000000" stroke-miterlimit="10" d="M152.7,196c0,5.1,4.1,9.2,9.2,9.2c5.1,0,9.2-4.1,9.2-9.2"/>' ) ) ); } /// @dev Eyes N°30 => RIP function item_30() public pure returns (string memory) { return base( string( abi.encodePacked( '<line fill="none" stroke="#000000" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" x1="225.7" y1="190.8" x2="242.7" y2="207.8"/>', '<line fill="none" stroke="#000000" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" x1="225.7" y1="207.8" x2="243.1" y2="190.8"/>', '<line fill="none" stroke="#000000" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" x1="152.8" y1="190.8" x2="169.8" y2="207.8"/>', '<line fill="none" stroke="#000000" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" x1="152.8" y1="207.8" x2="170.3" y2="190.8"/>' ) ) ); } /// @dev Eyes N°31 => Heart function item_31() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#F44336" stroke="#C90005" stroke-miterlimit="10" d="M161.1,218.1c0.2,0.2,0.4,0.3,0.7,0.3s0.5-0.1,0.7-0.3l12.8-14.1 c5.3-5.9,1.5-16-6-16c-4.6,0-6.7,3.6-7.5,4.3c-0.8-0.7-2.9-4.3-7.5-4.3c-7.6,0-11.4,10.1-6,16L161.1,218.1z"/>', '<path fill="#F44336" stroke="#C90005" stroke-miterlimit="10" d="M235.3,218.1c0.2,0.2,0.5,0.3,0.8,0.3s0.6-0.1,0.8-0.3l13.9-14.1 c5.8-5.9,1.7-16-6.6-16c-4.9,0-7.2,3.6-8.1,4.3c-0.9-0.7-3.1-4.3-8.1-4.3c-8.2,0-12.4,10.1-6.6,16L235.3,218.1z"/>' ) ) ); } /// @dev Eyes N°32 => Scribble function item_32() public pure returns (string memory) { return base( string( abi.encodePacked( '<polyline fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" points="222.5,195.2 252.2,195.2 222.5,199.4 250.5,199.4 223.9,202.8 247.4,202.8"/>', '<polyline fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" points="148.2,195.2 177.9,195.2 148.2,199.4 176.2,199.4 149.6,202.8 173.1,202.8"/>' ) ) ); } /// @dev Eyes N°33 => Wide function item_33() public pure returns (string memory) { return base( string( abi.encodePacked( '<ellipse fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" cx="236.7" cy="200.1" rx="12.6" ry="14.9"/>', '<path d="M249.4,200.1c0,3.6-1,7.3-3.2,10.3c-1.1,1.5-2.5,2.8-4.1,3.7s-3.5,1.4-5.4,1.4s-3.7-0.6-5.3-1.5s-3-2.2-4.1-3.6c-2.2-2.9-3.4-6.5-3.5-10.2c-0.1-3.6,1-7.4,3.3-10.4c1.1-1.5,2.6-2.7,4.2-3.6c1.6-0.9,3.5-1.4,5.4-1.4s3.8,0.5,5.4,1.4c1.6,0.9,3,2.2,4.1,3.7C248.4,192.9,249.4,196.5,249.4,200.1z M249.3,200.1c0-1.8-0.3-3.6-0.9-5.3c-0.6-1.7-1.5-3.2-2.6-4.6c-2.2-2.7-5.5-4.5-9-4.5s-6.7,1.8-8.9,4.6c-2.2,2.7-3.3,6.2-3.4,9.8c-0.1,3.5,1,7.2,3.2,10s5.6,4.6,9.1,4.5c3.5,0,6.8-1.9,9-4.6C248,207.3,249.3,203.7,249.3,200.1z"/>', '<ellipse fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" cx="163" cy="200.1" rx="12.6" ry="14.9"/>', '<path d="M175.6,200.1c0,3.6-1,7.3-3.2,10.3c-1.1,1.5-2.5,2.8-4.1,3.7s-3.5,1.4-5.4,1.4s-3.7-0.6-5.3-1.5s-3-2.2-4.1-3.6c-2.2-2.9-3.4-6.5-3.5-10.2c-0.1-3.6,1-7.4,3.3-10.4c1.1-1.5,2.6-2.7,4.2-3.6c1.6-0.9,3.5-1.4,5.4-1.4s3.8,0.5,5.4,1.4c1.6,0.9,3,2.2,4.1,3.7C174.6,192.9,175.6,196.5,175.6,200.1z M175.5,200.1c0-1.8-0.3-3.6-0.9-5.3c-0.6-1.7-1.5-3.2-2.6-4.6c-2.2-2.7-5.5-4.5-9-4.5s-6.7,1.8-8.9,4.6c-2.2,2.7-3.3,6.2-3.4,9.8c-0.1,3.5,1,7.2,3.2,10s5.6,4.6,9.1,4.5c3.5,0,6.8-1.9,9-4.6C174.3,207.3,175.5,203.7,175.5,200.1z"/>' ) ) ); } /// @dev Eyes N°34 => Dubu function item_34() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M241.6,195.9c-8.7-7.2-25.1-4-4.7,6.6c-21.9-4.3-3.4,11.8,4.7,6.1"/>', '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M167.6,195.9c-8.7-7.2-25.1-4-4.7,6.6c-21.9-4.3-3.4,11.8,4.7,6.1"/>' ) ) ); } /// @dev Right and left eyes (color pupils + eyes) function eyesNoFillAndColorPupils(string memory scleraColor, string memory pupilsColor) private pure returns (string memory) { return base(string(abi.encodePacked(eyesNoFill(scleraColor), colorPupils(pupilsColor)))); } /// @dev Right and left eyes (blank pupils + eyes) function eyesNoFillAndBlankPupils(string memory scleraColor, string memory pupilsColor) private pure returns (string memory) { return base(string(abi.encodePacked(eyesNoFill(scleraColor), blankPupils(pupilsColor)))); } /// @dev Right and left eyes function eyesNoFill(string memory scleraColor) private pure returns (string memory) { return string(abi.encodePacked(eyeLeftNoFill(scleraColor), eyeRightNoFill(scleraColor))); } /// @dev Eye right and no fill function eyeRightNoFill(string memory scleraColor) private pure returns (string memory) { return string( abi.encodePacked( "<path fill='#", scleraColor, "' d='M220.9,203.6c0.5,3.1,1.7,9.6,7.1,10.1 c7,1.1,21,4.3,23.2-9.3c1.3-7.1-9.8-11.4-15.4-11.2C230.7,194.7,220.5,194.7,220.9,203.6z'/>", '<path d="M250.4,198.6c-0.2-0.2-0.4-0.5-0.6-0.7"/>', '<path d="M248.6,196.6c-7.6-7.9-23.4-6.2-29.3,3.7c10-8.2,26.2-6.7,34.4,3.4c0-0.3-0.7-1.8-2-3.7"/>', '<path d="M229.6,187.6c4.2-1.3,9.1-1,13,1.2C238.4,187.4,234,186.6,229.6,187.6L229.6,187.6z"/>', '<path d="M226.1,189c-1.8,1.3-3.7,2.7-5.6,3.9C221.9,191.1,224,189.6,226.1,189z"/>', '<path d="M224.5,212.4c5.2,2.5,19.7,3.5,24-0.9C244.2,216.8,229.6,215.8,224.5,212.4z"/>' ) ); } /// @dev Eye right and no fill function eyeLeftNoFill(string memory scleraColor) private pure returns (string memory) { return string( abi.encodePacked( "<path fill='#", scleraColor, "' d='M175.7,199.4c2.4,7.1-0.6,13.3-4.1,13.9 c-5,0.8-15.8,1-18.8,0c-5-1.7-6.1-12.4-6.1-12.4C156.6,191.4,165,189.5,175.7,199.4z'/>", '<path d="M147.5,198.7c-0.8,1-1.5,2.1-2,3.3c7.5-8.5,24.7-10.3,31.7-0.9c-5.8-10.3-17.5-13-26.4-5.8"/>', '<path d="M149.4,196.6c-0.2,0.2-0.4,0.4-0.6,0.6"/>', '<path d="M166.2,187.1c-4.3-0.8-8.8,0.1-13,1.4C157,186.4,162,185.8,166.2,187.1z"/>', '<path d="M169.8,188.5c2.2,0.8,4.1,2.2,5.6,3.8C173.5,191.1,171.6,189.7,169.8,188.5z"/>', '<path d="M174.4,211.8c-0.2,0.5-0.8,0.8-1.2,1c-0.5,0.2-1,0.4-1.5,0.6c-1,0.3-2.1,0.5-3.1,0.7c-2.1,0.4-4.2,0.5-6.3,0.7 c-2.1,0.1-4.3,0.1-6.4-0.3c-1.1-0.2-2.1-0.5-3.1-0.9c-0.9-0.5-2-1.1-2.4-2.1c0.6,0.9,1.6,1.4,2.5,1.7c1,0.3,2,0.6,3,0.7 c2.1,0.3,4.2,0.3,6.2,0.2c2.1-0.1,4.2-0.2,6.3-0.5c1-0.1,2.1-0.3,3.1-0.5c0.5-0.1,1-0.2,1.5-0.4c0.2-0.1,0.5-0.2,0.7-0.3 C174.1,212.2,174.3,212.1,174.4,211.8z"/>' ) ); } /// @dev Generate color pupils function colorPupils(string memory pupilsColor) private pure returns (string memory) { return string( abi.encodePacked( "<path fill='#", pupilsColor, "' d='M235,194.9c10.6-0.2,10.6,19,0,18.8C224.4,213.9,224.4,194.7,235,194.9z'/>", '<path d="M235,199.5c3.9-0.1,3.9,9.6,0,9.5C231.1,209.1,231.1,199.4,235,199.5z"/>', '<path fill="#FFFFFF" d="M239.1,200.9c3.4,0,3.4,2.5,0,2.5C235.7,203.4,235.7,200.8,239.1,200.9z"/>', "<path fill='#", pupilsColor, "' d='M161.9,194.6c10.5-0.4,11,18.9,0.4,18.9C151.7,213.9,151.3,194.6,161.9,194.6z'/>", '<path d="M162,199.2c3.9-0.2,4.1,9.5,0.2,9.5C158.2,208.9,158.1,199.2,162,199.2z"/>', '<path fill="#FFFFFF" d="M157.9,200.7c3.4-0.1,3.4,2.5,0,2.5C154.6,203.3,154.5,200.7,157.9,200.7z"/>' ) ); } /// @dev Generate blank pupils function blankPupils(string memory pupilsColor) private pure returns (string memory) { return string( abi.encodePacked( abi.encodePacked( "<path fill='#", pupilsColor, "' stroke='#000000' stroke-width='0.25' stroke-miterlimit='10' d='M169.2,204.2c0.1,11.3-14.1,11.3-13.9,0C155.1,192.9,169.3,192.9,169.2,204.2z'/>", "<path fill='#", pupilsColor, "' stroke='#000000' stroke-width='0.25' stroke-miterlimit='10' d='M243.1,204.3c0.1,11.3-14.1,11.3-13.9,0C229,193,243.2,193,243.1,204.3z'/>" ) ) ); } /// @notice Return the eyes name of the given id /// @param id The eyes Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Color White/Brown"; } else if (id == 2) { name = "Color White/Gray"; } else if (id == 3) { name = "Color White/Blue"; } else if (id == 4) { name = "Color White/Green"; } else if (id == 5) { name = "Color White/Black"; } else if (id == 6) { name = "Color White/Yellow"; } else if (id == 7) { name = "Color White/Red"; } else if (id == 8) { name = "Color White/Purple"; } else if (id == 9) { name = "Color White/Pink"; } else if (id == 10) { name = "Color White/White"; } else if (id == 11) { name = "Color Black/Blue"; } else if (id == 12) { name = "Color Black/Yellow"; } else if (id == 13) { name = "Color Black/White"; } else if (id == 14) { name = "Color Black/Red"; } else if (id == 15) { name = "Blank White/White"; } else if (id == 16) { name = "Blank Black/White"; } else if (id == 17) { name = "Shine"; } else if (id == 18) { name = "Stunt"; } else if (id == 19) { name = "Squint"; } else if (id == 20) { name = "Shock"; } else if (id == 21) { name = "Cat"; } else if (id == 22) { name = "Ether"; } else if (id == 23) { name = "Feels"; } else if (id == 24) { name = "Happy"; } else if (id == 25) { name = "Arrow"; } else if (id == 26) { name = "Closed"; } else if (id == 27) { name = "Suspicious"; } else if (id == 28) { name = "Annoyed 1"; } else if (id == 29) { name = "Annoyed 2"; } else if (id == 30) { name = "RIP"; } else if (id == 31) { name = "Heart"; } else if (id == 32) { name = "Scribble"; } else if (id == 33) { name = "Wide"; } else if (id == 34) { name = "Dubu"; } } /// @dev The base SVG for the eyes function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Eyes">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Eyebrow SVG generator library EyebrowDetail { /// @dev Eyebrow N°1 => Classic function item_1() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#150000" d="M213.9,183.1c13.9-5.6,28.6-3,42.7-0.2C244,175,225.8,172.6,213.9,183.1z"/>', '<path fill="#150000" d="M179.8,183.1c-10.7-10.5-27-8.5-38.3-0.5C154.1,179.7,167.6,177.5,179.8,183.1z"/>' ) ) ); } /// @dev Eyebrow N°2 => Thick function item_2() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M211.3,177.6c0,0,28.6-6.6,36.2-6.2c7.7,0.4,13,3,16.7,6.4c0,0-26.9,5.3-38.9,5.9C213.3,184.3,212.9,183.8,211.3,177.6z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M188.2,177.6c0,0-27.9-6.7-35.4-6.3c-7.5,0.4-12.7,2.9-16.2,6.3c0,0,26.3,5.3,38,6C186.2,184.3,186.7,183.7,188.2,177.6z"/>' ) ) ); } /// @dev Eyebrow N°3 => Punk function item_3() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M258.6,179.1l-2-2.3 c3.1,0.4,5.6,1,7.6,1.7C264.2,178.6,262,178.8,258.6,179.1z M249.7,176.3c-0.7,0-1.5,0-2.3,0c-7.6,0-36.1,3.2-36.1,3.2 c-0.4,2.9-3.8,3.5,8.1,3c6.6-0.3,23.6-2,32.3-2.8L249.7,176.3z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M140.2,179.1l1.9-2.3 c-3,0.4-5.4,1-7.3,1.7C134.8,178.6,136.9,178.8,140.2,179.1z M148.8,176.3c0.7,0,1.4,0,2.2,0c7.3,0,34.7,3.2,34.7,3.2 c0.4,2.9,3.6,3.5-7.8,3c-6.3-0.3-22.7-2-31-2.8L148.8,176.3z"/>' ) ) ); } /// @dev Eyebrow N°4 => Small function item_4() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill-rule="evenodd" clip-rule="evenodd" d="M236.3,177c-11.3-5.1-18-3.1-20.3-2.1c-0.1,0-0.2,0.1-0.3,0.2c-0.3,0.1-0.5,0.3-0.6,0.3l0,0l0,0l0,0c-1,0.7-1.7,1.7-1.9,3c-0.5,2.6,1.2,5,3.8,5.5s5-1.2,5.5-3.8c0.1-0.3,0.1-0.6,0.1-1C227.4,175.6,236.3,177,236.3,177z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" d="M160.2,176.3c10.8-4.6,17.1-2.5,19.2-1.3c0.1,0,0.2,0.1,0.3,0.2c0.3,0.1,0.4,0.3,0.5,0.3l0,0l0,0l0,0c0.9,0.7,1.6,1.8,1.8,3.1c0.4,2.6-1.2,5-3.7,5.4s-4.7-1.4-5.1-4c-0.1-0.3-0.1-0.6-0.1-1C168.6,175.2,160.2,176.3,160.2,176.3z"/>' ) ) ); } /// @dev Eyebrow N°5 => Shaved function item_5() public pure returns (string memory) { return base( string( abi.encodePacked( '<g opacity="0.06">', '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M214.5,178 c0,0,20.6-3.5,26.1-3.3s9.4,1.6,12,3.4c0,0-19.4,2.8-28,3.1C215.9,181.6,215.6,181.3,214.5,178z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M180.8,178 c0,0-20.1-3.6-25.5-3.4c-5.4,0.2-9.1,1.5-11.7,3.4c0,0,18.9,2.8,27.4,3.2C179.4,181.6,179.8,181.3,180.8,178z"/>', "</g>" ) ) ); } /// @dev Eyebrow N°6 => Elektric function item_6() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill-rule="evenodd" clip-rule="evenodd" d="M208.9,177.6c14.6-1.5,47.8-6.5,51.6-6.6l-14.4,4.1l19.7,3.2 c-20.2-0.4-40.9-0.1-59.2,2.6C206.6,179.9,207.6,178.5,208.9,177.6z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" d="M185.1,177.7c-13.3-1.5-43.3-6.7-46.7-6.9l13.1,4.2l-17.8,3.1 c18.2-0.3,37,0.1,53.6,2.9C187.2,180,186.2,178.6,185.1,177.7z"/>' ) ) ); } /// @notice Return the eyebrow name of the given id /// @param id The eyebrow Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Classic"; } else if (id == 2) { name = "Thick"; } else if (id == 3) { name = "Punk"; } else if (id == 4) { name = "Small"; } else if (id == 5) { name = "Shaved"; } else if (id == 6) { name = "Elektric"; } } /// @dev The base SVG for the Eyebrow function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Eyebrow">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Mark SVG generator library MarkDetail { /// @dev Mark N°1 => Classic function item_1() public pure returns (string memory) { return ""; } /// @dev Mark N°2 => Blush Cheeks function item_2() public pure returns (string memory) { return base( string( abi.encodePacked( '<g opacity="0.71">', '<ellipse fill="#FF7478" cx="257.6" cy="221.2" rx="11.6" ry="3.6"/>', '<ellipse fill="#FF7478" cx="146.9" cy="221.5" rx="9.6" ry="3.6"/>', "</g>" ) ) ); } /// @dev Mark N°3 => Dark Circle function item_3() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M160.1,223.2c4.4,0.2,8.7-1.3,12.7-3.2C169.3,222.7,164.4,223.9,160.1,223.2z"/>', '<path d="M156.4,222.4c-2.2-0.4-4.3-1.6-6.1-3C152.3,220.3,154.4,221.4,156.4,222.4z"/>', '<path d="M234.5,222.7c4.9,0.1,9.7-1.4,14.1-3.4C244.7,222.1,239.3,223.4,234.5,222.7z"/>', '<path d="M230.3,221.9c-2.5-0.4-4.8-1.5-6.7-2.9C225.9,219.9,228.2,221,230.3,221.9z"/>' ) ) ); } /// @dev Mark N°4 => Chin scar function item_4() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#E83342" d="M195.5,285.7l17,8.9C212.5,294.6,206.1,288.4,195.5,285.7z"/>', '<path fill="#E83342" d="M211.2,285.7l-17,8.9C194.1,294.6,200.6,288.4,211.2,285.7z"/>' ) ) ); } /// @dev Mark N°5 => Blush function item_5() public pure returns (string memory) { return base( string( abi.encodePacked( '<ellipse opacity="0.52" fill-rule="evenodd" clip-rule="evenodd" fill="#FF7F83" cx="196.8" cy="222" rx="32.8" ry="1.9"/>' ) ) ); } /// @dev Mark N°6 => Chin function item_6() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M201.3,291.9c0.2-0.6,0.4-1.3,1-1.8c0.3-0.2,0.7-0.4,1.1-0.3c0.4,0.1,0.7,0.4,0.9,0.7c0.4,0.6,0.5,1.4,0.5,2.1 c0,0.7-0.3,1.5-0.8,2c-0.5,0.6-1.3,0.9-2.1,0.8c-0.8-0.1-1.5-0.5-2-0.9c-0.6-0.4-1.1-1-1.5-1.6c-0.4-0.6-0.6-1.4-0.6-2.2 c0.2-1.6,1.4-2.8,2.7-3.4c1.3-0.6,2.8-0.8,4.2-0.5c0.7,0.1,1.4,0.4,2,0.9c0.6,0.5,0.9,1.2,1,1.9c0.2,1.4-0.2,2.9-1.2,3.9 c0.7-1.1,1-2.5,0.7-3.8c-0.2-0.6-0.5-1.2-1-1.5c-0.5-0.4-1.1-0.6-1.7-0.6c-1.3-0.1-2.6,0-3.7,0.6c-1.1,0.5-2,1.5-2.1,2.6 c-0.1,1.1,0.7,2.2,1.6,3c0.5,0.4,1,0.8,1.5,0.8c0.5,0.1,1.1-0.1,1.5-0.5c0.4-0.4,0.7-0.9,0.7-1.6c0.1-0.6,0-1.3-0.3-1.8 c-0.1-0.3-0.4-0.5-0.6-0.6c-0.3-0.1-0.6,0-0.8,0.1C201.9,290.7,201.5,291.3,201.3,291.9z"/>' ) ) ); } /// @dev Mark N°7 => Yinyang function item_7() public pure returns (string memory) { return base( string( abi.encodePacked( '<path opacity="0.86" d="M211.5,161.1c0-8.2-6.7-14.9-14.9-14.9c-0.2,0-0.3,0-0.5,0l0,0 H196c-0.1,0-0.2,0-0.2,0c-0.2,0-0.4,0-0.5,0c-7.5,0.7-13.5,7.1-13.5,14.8c0,8.2,6.7,14.9,14.9,14.9 C204.8,176,211.5,169.3,211.5,161.1z M198.4,154.2c0,1-0.8,1.9-1.9,1.9c-1,0-1.9-0.8-1.9-1.9c0-1,0.8-1.9,1.9-1.9 C197.6,152.3,198.4,153.1,198.4,154.2z M202.9,168.2c0,3.6-3.1,6.6-6.9,6.6l0,0c-7.3-0.3-13.2-6.3-13.2-13.7c0-6,3.9-11.2,9.3-13 c-2,1.3-3.4,3.6-3.4,6.2c0,4,3.3,7.3,7.3,7.3l0,0C199.8,161.6,202.9,164.5,202.9,168.2z M196.6,170.3c-1,0-1.9-0.8-1.9-1.9 c0-1,0.8-1.9,1.9-1.9c1,0,1.9,0.8,1.9,1.9C198.4,169.5,197.6,170.3,196.6,170.3z"/>' ) ) ); } /// @dev Mark N°8 => Scar function item_8() public pure returns (string memory) { return base( string( abi.encodePacked( '<path id="Scar" fill="#FF7478" d="M236.2,148.7c0,0-7.9,48.9-1.2,97.3C235,246,243.8,201.5,236.2,148.7z"/>' ) ) ); } /// @dev Mark N°9 => Sun function item_9() public pure returns (string memory) { return base( string( abi.encodePacked( '<circle fill="#7F0068" cx="195.8" cy="161.5" r="11.5"/>', '<polygon fill="#7F0068" points="195.9,142.4 192.4,147.8 199.3,147.8"/>', '<polygon fill="#7F0068" points="209.6,158.1 209.6,164.9 214.9,161.5"/>', '<polygon fill="#7F0068" points="195.9,180.6 199.3,175.2 192.4,175.2"/>', '<polygon fill="#7F0068" points="182.1,158.1 176.8,161.5 182.1,164.9"/>', '<polygon fill="#7F0068" points="209.3,148 203.1,149.4 208,154.2"/>', '<polygon fill="#7F0068" points="209.3,175 208,168.8 203.1,173.6"/>', '<polygon fill="#7F0068" points="183.7,168.8 182.4,175 188.6,173.6"/>', '<polygon fill="#7F0068" points="188.6,149.4 182.4,148 183.7,154.2"/>' ) ) ); } /// @dev Mark N°10 => Moon function item_10() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#7F0068" d="M197.2,142.1c-5.8,0-10.9,2.9-13.9,7.3c2.3-2.3,5.4-3.7,8.9-3.7c7.1,0,12.9,5.9,12.9,13.3 s-5.8,13.3-12.9,13.3c-3.4,0-6.6-1.4-8.9-3.7c3.1,4.4,8.2,7.3,13.9,7.3c9.3,0,16.9-7.6,16.9-16.9S206.6,142.1,197.2,142.1z"/>' ) ) ); } /// @dev Mark N°11 => Third Eye function item_11() public pure returns (string memory) { return base( string( abi.encodePacked( '<path opacity="0.81" fill="#FFFFFF" d="M184.4,159.3c0.7,3.5,0.8,8.5,6.3,8.8 c5.5,1.6,23.2,4.2,23.8-7.6c1.2-6.1-10-9.5-15.5-9.3C193.8,152.6,184.1,153.5,184.4,159.3z"/>', '<path d="M213.6,155.6c-0.2-0.2-0.4-0.4-0.6-0.6"/>', '<path d="M211.8,154c-7.7-6.6-23.5-4.9-29.2,3.6c9.9-7.1,26.1-6.1,34.4,2.4c0-0.3-0.7-1.5-2-3.1"/>', '<path d="M197.3,146.8c4.3-0.6,9.1,0.3,12.7,2.7C206,147.7,201.8,146.5,197.3,146.8L197.3,146.8z M193.6,147.5 c-2,0.9-4.1,1.8-6.1,2.6C189.2,148.8,191.5,147.8,193.6,147.5z"/>', '<path d="M187.6,167.2c5.2,2,18.5,3.2,23.3,0.1C206.3,171.3,192.7,170,187.6,167.2z"/>', '<path fill="#0B1F26" d="M199.6,151c11.1-0.2,11.1,17.4,0,17.3C188.5,168.4,188.5,150.8,199.6,151z"/>' ) ) ); } /// @dev Mark N°12 => Tori function item_12() public pure returns (string memory) { return base( string( abi.encodePacked( '<line fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" x1="231.2" y1="221.5" x2="231.2" y2="228.4"/>', '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M228.6,221.2c0,0,3.2,0.4,5.5,0.2"/>', '<path fill-rule="evenodd" clip-rule="evenodd" fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M237.3,221.5c0,0-3.5,3.1,0,6.3C240.8,231,242.2,221.5,237.3,221.5z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M243.2,227.8l-1.2-6.4c0,0,8.7-2,1,2.8l3.2,3"/>', '<line fill-rule="evenodd" clip-rule="evenodd" fill="#FFEBB4" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" x1="248.5" y1="221" x2="248.5" y2="227.5"/>', '<path d="M254.2,226c0,0,0.1,0,0.1,0c0,0,0.1,0,0.1-0.1l1.3-2.2c0.5-0.9-0.2-2.2-1.2-2c-0.6,0.1-0.8,0.7-0.9,0.8 c-0.1-0.1-0.5-0.5-1.1-0.4c-1,0.2-1.3,1.7-0.4,2.3L254.2,226z"/>' ) ) ); } /// @dev Mark N°13 => Ether function item_13() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#2B2B2B" stroke="#000000" stroke-miterlimit="10" d="M196.5,159.9l-12.4-5.9l12.4,21.6l12.4-21.6L196.5,159.9z"/>', '<path fill="#2B2B2B" stroke="#000000" stroke-miterlimit="10" d="M207.5,149.6l-11-19.1l-11,19.2l11-5.2L207.5,149.6z"/>', '<path fill="#2B2B2B" stroke="#000000" stroke-miterlimit="10" d="M186.5,152.2l10.1,4.8l10.1-4.8l-10.1-4.8L186.5,152.2z"/>' ) ) ); } /// @notice Return the mark name of the given id /// @param id The mark Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Classic"; } else if (id == 2) { name = "Blush Cheeks"; } else if (id == 3) { name = "Dark Circle"; } else if (id == 4) { name = "Chin Scar"; } else if (id == 5) { name = "Blush"; } else if (id == 6) { name = "Chin"; } else if (id == 7) { name = "Yinyang"; } else if (id == 8) { name = "Scar"; } else if (id == 9) { name = "Sun"; } else if (id == 10) { name = "Moon"; } else if (id == 11) { name = "Third Eye"; } else if (id == 12) { name = "Tori"; } else if (id == 13) { name = "Ether"; } } /// @dev The base SVG for the hair function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Mark">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; import "./constants/Colors.sol"; /// @title Accessory SVG generator library AccessoryDetail { /// @dev Accessory N°1 => Classic function item_1() public pure returns (string memory) { return ""; } /// @dev Accessory N°2 => Glasses function item_2() public pure returns (string memory) { return base(glasses("D1F5FF", "000000", "0.31")); } /// @dev Accessory N°3 => Bow Tie function item_3() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="none" stroke="#000000" stroke-width="7" stroke-miterlimit="10" d="M176.2,312.5 c3.8,0.3,26.6,7.2,81.4-0.4"/>', '<path fill-rule="evenodd" clip-rule="evenodd" fill="#DF0849" stroke="#000000" stroke-miterlimit="10" d="M211.3,322.1 c-2.5-0.3-5-0.5-7.4,0c-1.1,0-1.9-1.4-1.9-3.1v-4.5c0-1.7,0.9-3.1,1.9-3.1c2.3,0.6,4.8,0.5,7.4,0c1.1,0,1.9,1.4,1.9,3.1v4.5 C213.2,320.6,212.3,322.1,211.3,322.1z"/>', '<path fill="#DF0849" stroke="#000000" stroke-miterlimit="10" d="M202.4,321.5c0,0-14,5.6-17.7,5.3c-1.1-0.1-2.5-4.6-1.2-10.5 c0,0-1-2.2-0.3-9.5c0.4-3.4,19.2,5.1,19.2,5.1S201,316.9,202.4,321.5z"/>', '<path fill="#DF0849" stroke="#000000" stroke-miterlimit="10" d="M212.6,321.5c0,0,14,5.6,17.7,5.3c1.1-0.1,2.5-4.6,1.2-10.5 c0,0,1-2.2,0.3-9.5c-0.4-3.4-19.2,5.1-19.2,5.1S213.9,316.9,212.6,321.5z"/>', '<path opacity="0.41" d="M213.6,315.9l6.4-1.1l-3.6,1.9l4.1,1.1l-7-0.6L213.6,315.9z M201.4,316.2l-6.4-1.1l3.6,1.9l-4.1,1.1l7-0.6L201.4,316.2z"/>' ) ) ); } /// @dev Accessory N°4 => Monk Beads Classic function item_4() public pure returns (string memory) { return base(monkBeads("63205A")); } /// @dev Accessory N°5 => Monk Beads Silver function item_5() public pure returns (string memory) { return base(monkBeads("C7D2D4")); } /// @dev Accessory N°6 => Power Pole function item_6() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FF6F4F" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M272.3,331.9l55.2-74.4c0,0,3,4.3,8.7,7.5l-54,72.3"/>', '<polygon fill="#BA513A" points="335.9,265.3 334.2,264.1 279.9,336.1 281.8,337.1"/>', '<ellipse transform="matrix(0.6516 -0.7586 0.7586 0.6516 -82.3719 342.7996)" fill="#B54E36" stroke="#000000" stroke-width="0.25" stroke-miterlimit="10" cx="332" cy="261.1" rx="1.2" ry="6.1"/>', '<path fill="none" stroke="#B09E00" stroke-miterlimit="10" d="M276.9,335.3c-52.7,31.1-119.3,49.4-120.7,49"/>' ) ) ); } /// @dev Accessory N°7 => Vintage Glasses function item_7() public pure returns (string memory) { return base(glasses("FC55FF", "DFA500", "0.31")); } /// @dev Accessory N°8 => Monk Beads Gold function item_8() public pure returns (string memory) { return base(monkBeads("FFDD00")); } /// @dev Accessory N°9 => Eye Patch function item_9() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FCFEFF" stroke="#4A6362" stroke-miterlimit="10" d="M253.6,222.7H219c-4.7,0-8.5-3.8-8.5-8.5v-20.8 c0-4.7,3.8-8.5,8.5-8.5h34.6c4.7,0,8.5,3.8,8.5,8.5v20.8C262.1,218.9,258.3,222.7,253.6,222.7z"/>', '<path fill="none" stroke="#4A6362" stroke-width="0.75" stroke-miterlimit="10" d="M250.1,218.9h-27.6c-3.8,0-6.8-3.1-6.8-6.8 v-16.3c0-3.8,3.1-6.8,6.8-6.8h27.6c3.8,0,6.8,3.1,6.8,6.8V212C257,215.8,253.9,218.9,250.1,218.9z"/>', '<line fill="none" stroke="#3C4F4E" stroke-linecap="round" stroke-miterlimit="10" x1="211.9" y1="188.4" x2="131.8" y2="183.1"/>', '<line fill="none" stroke="#3C4F4E" stroke-linecap="round" stroke-miterlimit="10" x1="259.9" y1="188.1" x2="293.4" y2="196.7"/>', '<line fill="none" stroke="#3C4F4E" stroke-linecap="round" stroke-miterlimit="10" x1="259.2" y1="220.6" x2="277.5" y2="251.6"/>', '<line fill="none" stroke="#3C4F4E" stroke-linecap="round" stroke-miterlimit="10" x1="211.4" y1="219.1" x2="140.5" y2="242"/>', '<g fill-rule="evenodd" clip-rule="evenodd" fill="#636363" stroke="#4A6362" stroke-width="0.25" stroke-miterlimit="10"><ellipse cx="250.9" cy="215" rx="0.8" ry="1.1"/><ellipse cx="236.9" cy="215" rx="0.8" ry="1.1"/><ellipse cx="250.9" cy="203.9" rx="0.8" ry="1.1"/><ellipse cx="250.9" cy="193.8" rx="0.8" ry="1.1"/><ellipse cx="236.9" cy="193.8" rx="0.8" ry="1.1"/><ellipse cx="221.3" cy="215" rx="0.8" ry="1.1"/><ellipse cx="221.3" cy="203.9" rx="0.8" ry="1.1"/><ellipse cx="221.3" cy="193.8" rx="0.8" ry="1.1"/></g>' ) ) ); } /// @dev Accessory N°10 => Sun Glasses function item_10() public pure returns (string memory) { return base(glasses(Colors.BLACK, Colors.BLACK_DEEP, "1")); } /// @dev Accessory N°11 => Monk Beads Diamond function item_11() public pure returns (string memory) { return base(monkBeads("AAFFFD")); } /// @dev Accessory N°12 => Horns function item_12() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill-rule="evenodd" clip-rule="evenodd" fill="#212121" stroke="#000000" stroke-linejoin="round" stroke-miterlimit="10" d="M257.7,96.3c0,0,35-18.3,46.3-42.9c0,0-0.9,37.6-23.2,67.6C269.8,115.6,261.8,107.3,257.7,96.3z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" fill="#212121" stroke="#000000" stroke-linejoin="round" stroke-miterlimit="10" d="M162,96.7c0,0-33-17.3-43.7-40.5c0,0,0.9,35.5,21.8,63.8C150.6,114.9,158.1,107.1,162,96.7z"/>' ) ) ); } /// @dev Accessory N°13 => Halo function item_13() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#F6FF99" stroke="#000000" stroke-miterlimit="10" d="M136,67.3c0,14.6,34.5,26.4,77,26.4s77-11.8,77-26.4s-34.5-26.4-77-26.4S136,52.7,136,67.3L136,67.3z M213,79.7c-31.4,0-56.9-6.4-56.9-14.2s25.5-14.2,56.9-14.2s56.9,6.4,56.9,14.2S244.4,79.7,213,79.7z"/>' ) ) ); } /// @dev Accessory N°14 => Saiki Power function item_14() public pure returns (string memory) { return base( string( abi.encodePacked( '<line fill="none" stroke="#000000" stroke-width="5" stroke-miterlimit="10" x1="270.5" y1="105.7" x2="281.7" y2="91.7"/>', '<circle fill="#EB7FFF" stroke="#000000" stroke-miterlimit="10" cx="285.7" cy="85.2" r="9.2"/>', '<line fill="none" stroke="#000000" stroke-width="5" stroke-miterlimit="10" x1="155.8" y1="105.7" x2="144.5" y2="91.7"/>', '<circle fill="#EB7FFF" stroke="#000000" stroke-miterlimit="10" cx="138.7" cy="85.2" r="9.2"/>', '<path opacity="0.17" d="M287.3,76.6c0,0,10.2,8.2,0,17.1c0,0,7.8-0.7,7.4-9.5 C293,75.9,287.3,76.6,287.3,76.6z"/>', '<path opacity="0.17" d="M137,76.4c0,0-10.2,8.2,0,17.1c0,0-7.8-0.7-7.4-9.5 C131.4,75.8,137,76.4,137,76.4z"/>', '<ellipse transform="matrix(0.4588 -0.8885 0.8885 0.4588 80.0823 294.4391)" fill="#FFFFFF" cx="281.8" cy="81.5" rx="2.1" ry="1.5"/>', '<ellipse transform="matrix(0.8885 -0.4588 0.4588 0.8885 -21.756 74.6221)" fill="#FFFFFF" cx="142.7" cy="82.1" rx="1.5" ry="2.1"/>', '<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M159.6,101.4c0,0-1.1,4.4-7.4,7.2"/>', '<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M267.2,101.4c0,0,1.1,4.4,7.4,7.2"/>', abi.encodePacked( '<polygon opacity="0.68" fill="#7FFF35" points="126,189.5 185.7,191.8 188.6,199.6 184.6,207.4 157.3,217.9 128.6,203.7"/>', '<polygon opacity="0.68" fill="#7FFF35" points="265.7,189.5 206.7,191.8 203.8,199.6 207.7,207.4 234.8,217.9 263.2,203.7"/>', '<polyline fill="#FFFFFF" stroke="#424242" stroke-width="0.5" stroke-miterlimit="10" points="196.5,195.7 191.8,195.4 187,190.9 184.8,192.3 188.5,198.9 183,206.8 187.6,208.3 193.1,201.2 196.5,201.2"/>', '<polyline fill="#FFFFFF" stroke="#424242" stroke-width="0.5" stroke-miterlimit="10" points="196.4,195.7 201.1,195.4 205.9,190.9 208.1,192.3 204.4,198.9 209.9,206.8 205.3,208.3 199.8,201.2 196.4,201.2"/>', '<polygon fill="#FFFFFF" stroke="#424242" stroke-width="0.5" stroke-miterlimit="10" points="123.8,189.5 126.3,203 129.2,204.4 127.5,189.5"/>', '<polygon fill="#FFFFFF" stroke="#424242" stroke-width="0.5" stroke-miterlimit="10" points="265.8,189.4 263.3,203.7 284.3,200.6 285.3,189.4"/>' ) ) ) ); } /// @dev Accessory N°15 => No Face function item_15() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#F5F4F3" stroke="#000000" stroke-miterlimit="10" d="M285.5,177.9c0,68.3-19.6,127.3-77.9,128.2 c-58.4,0.9-74.4-57.1-74.4-125.4s14.4-103.5,72.7-103.5C266.7,77.2,285.5,109.6,285.5,177.9z"/>', '<path opacity="0.08" d="M285.4,176.9c0,68.3-19.4,127.6-78,129.3 c27.2-17.6,28.3-49.1,28.3-117.3s23.8-86-30-111.6C266.4,77.3,285.4,108.7,285.4,176.9z"/>', '<ellipse cx="243.2" cy="180.7" rx="16.9" ry="6.1"/>', '<path d="M231.4,273.6c0.3-7.2-12.1-6.1-27.2-6.1s-27.4-1.4-27.2,6.1c0.1,3.4,12.1,6.1,27.2,6.1S231.3,277,231.4,273.6z"/>', '<ellipse cx="162" cy="180.5" rx="16.3" ry="6"/>', '<path fill="#F2EDED" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M149.7,191.4c0,0,6.7,5.8,20.5,0.6"/>', '<path fill="#F2EDED" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M232.9,191.3c0,0,6.6,5.7,20.4,0.6"/>', '<path fill="#F2EDED" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M192.7,285.1c0,0,9.2,3.5,21.6,0"/>', '<path fill="#996DAD" d="M150.8,200.5c1.5-3.6,17.2-3.4,18.8-0.4c1.8,3.2-4.8,45.7-6.6,46C159.8,246.8,148.1,211.1,150.8,200.5z"/>', '<path fill="#996DAD" d="M233.9,199.8c1.5-3.6,18-2.7,19.7,0.3c3.7,6.4-6.5,45.5-9.3,45.4C241,245.2,231.1,210.4,233.9,199.8z"/>', '<path fill="#996DAD" d="M231.3,160.6c1.3,2.3,14.7,2.1,16.1,0.2c1.6-2-4.1-27.7-7.2-28.2C236.9,132.2,229,154.1,231.3,160.6z"/>', '<path fill="#996DAD" d="M152.9,163.2c1.3,2.3,14.7,2.1,16.1,0.2c1.6-2-4.1-27.7-7.2-28.2C158.6,134.8,150.6,156.6,152.9,163.2z"/>' ) ) ); } /// @dev Generate glasses with the given color and opacity function glasses( string memory color, string memory stroke, string memory opacity ) private pure returns (string memory) { return string( abi.encodePacked( '<circle fill="none" stroke="#', stroke, '" stroke-miterlimit="10" cx="161.5" cy="201.7" r="23.9"/>', '<circle fill="none" stroke="#', stroke, '" stroke-miterlimit="10" cx="232.9" cy="201.7" r="23.9"/>', '<circle opacity="', opacity, '" fill="#', color, '" cx="161.5" cy="201.7" r="23.9"/>', abi.encodePacked( '<circle opacity="', opacity, '" fill="#', color, '" cx="232.9" cy="201.7" r="23.9"/>', '<path fill="none" stroke="#', stroke, '" stroke-miterlimit="10" d="M256.8,201.7l35.8-3.2 M185.5,201.7 c0,0,14.7-3.1,23.5,0 M137.6,201.7l-8.4-3.2"/>' ) ) ); } /// @dev Generate Monk Beads SVG with the given color function monkBeads(string memory color) private pure returns (string memory) { return string( abi.encodePacked( '<g fill="#', color, '" stroke="#2B232B" stroke-miterlimit="10" stroke-width="0.75">', '<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.3439 3.0256)" cx="176.4" cy="317.8" rx="7.9" ry="8"/>', '<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.458 3.2596)" cx="190.2" cy="324.6" rx="7.9" ry="8"/>', '<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.5085 3.5351)" cx="206.4" cy="327.8" rx="7.9" ry="8"/>', '<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.4607 4.0856)" cx="239.1" cy="325.2" rx="7.9" ry="8"/>', '<ellipse transform="matrix(0.9999 -1.693338e-02 1.693338e-02 0.9999 -5.386 4.3606)" cx="254.8" cy="320.2" rx="7.9" ry="8"/>', '<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.5015 3.8124)" cx="222.9" cy="327.5" rx="7.9" ry="8"/>', "</g>", '<path opacity="0.14" d="M182,318.4 c0.7,1.3-0.4,3.4-2.5,4.6c-2.1,1.2-4.5,1-5.2-0.3c-0.7-1.3,0.4-3.4,2.5-4.6C178.9,316.9,181.3,317,182,318.4z M190.5,325.7 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3s3.2-3.2,2.5-4.6C195,324.6,192.7,324.5,190.5,325.7z M206.7,328.6 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3c2.1-1.2,3.2-3.2,2.5-4.6C211.1,327.6,208.8,327.5,206.7,328.6z M223.2,328.4 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3c2.1-1.2,3.2-3.2,2.5-4.6S225.3,327.3,223.2,328.4z M239.8,325.7 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3c2.1-1.2,3.2-3.2,2.5-4.6C244.3,324.7,242,324.5,239.8,325.7z M255.7,320.9 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3c2.1-1.2,3.2-3.2,2.5-4.6C260.1,319.9,257.8,319.7,255.7,320.9z"/>', abi.encodePacked( '<g fill="#FFFFFF" stroke="#FFFFFF" stroke-miterlimit="10">', '<path d="M250.4,318.9c0.6,0.6,0.5-0.9,1.3-2c0.8-1,2.4-1.2,1.8-1.8 c-0.6-0.6-1.9-0.2-2.8,0.9C250,317,249.8,318.3,250.4,318.9z"/>', '<path d="M234.4,323.6c0.7,0.6,0.5-0.9,1.4-1.9c1-1,2.5-1.1,1.9-1.7 c-0.7-0.6-1.9-0.3-2.8,0.7C234.1,321.7,233.8,323,234.4,323.6z"/>', '<path d="M218.2,325.8c0.6,0.6,0.6-0.9,1.4-1.8c1-1,2.5-1,1.9-1.6 c-0.6-0.6-1.9-0.4-2.8,0.6C217.8,323.9,217.6,325.2,218.2,325.8z"/>', '<path d="M202.1,325.5c0.6,0.6,0.6-0.9,1.7-1.7s2.6-0.8,2-1.5 c-0.6-0.6-1.8-0.5-2.9,0.4C202,323.5,201.5,324.8,202.1,325.5z"/>', '<path d="M186.2,322c0.6,0.6,0.6-0.9,1.7-1.7c1-0.8,2.6-0.8,2-1.5 c-0.6-0.6-1.8-0.5-2.9,0.3C186,320.1,185.7,321.4,186.2,322z"/>', '<path d="M171.7,315.4c0.6,0.6,0.6-0.9,1.5-1.8s2.5-0.9,1.9-1.6 s-1.9-0.4-2.8,0.5C171.5,313.5,171.1,314.9,171.7,315.4z"/>', "</g>" ) ) ); } /// @notice Return the accessory name of the given id /// @param id The accessory Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Classic"; } else if (id == 2) { name = "Glasses"; } else if (id == 3) { name = "Bow Tie"; } else if (id == 4) { name = "Monk Beads Classic"; } else if (id == 5) { name = "Monk Beads Silver"; } else if (id == 6) { name = "Power Pole"; } else if (id == 7) { name = "Vintage Glasses"; } else if (id == 8) { name = "Monk Beads Gold"; } else if (id == 9) { name = "Eye Patch"; } else if (id == 10) { name = "Sun Glasses"; } else if (id == 11) { name = "Monk Beads Diamond"; } else if (id == 12) { name = "Horns"; } else if (id == 13) { name = "Halo"; } else if (id == 14) { name = "Saiki Power"; } else if (id == 15) { name = "No Face"; } } /// @dev The base SVG for the accessory function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Accessory">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Earrings SVG generator library EarringsDetail { /// @dev Earrings N°1 => Classic function item_1() public pure returns (string memory) { return ""; } /// @dev Earrings N°2 => Circle function item_2() public pure returns (string memory) { return base(circle("000000")); } /// @dev Earrings N°3 => Circle Silver function item_3() public pure returns (string memory) { return base(circle("C7D2D4")); } /// @dev Earrings N°4 => Ring function item_4() public pure returns (string memory) { return base(ring("000000")); } /// @dev Earrings N°5 => Circle Gold function item_5() public pure returns (string memory) { return base(circle("FFDD00")); } /// @dev Earrings N°6 => Ring Gold function item_6() public pure returns (string memory) { return base(ring("FFDD00")); } /// @dev Earrings N°7 => Heart function item_7() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M284.3,247.9c0.1,0.1,0.1,0.1,0.2,0.1s0.2,0,0.2-0.1l3.7-3.8c1.5-1.6,0.4-4.3-1.8-4.3c-1.3,0-1.9,1-2.2,1.2c-0.2-0.2-0.8-1.2-2.2-1.2c-2.2,0-3.3,2.7-1.8,4.3L284.3,247.9z"/>', '<path d="M135,246.6c0,0,0.1,0.1,0.2,0.1s0.1,0,0.2-0.1l3.1-3.1c1.3-1.3,0.4-3.6-1.5-3.6c-1.1,0-1.6,0.8-1.8,1c-0.2-0.2-0.7-1-1.8-1c-1.8,0-2.8,2.3-1.5,3.6L135,246.6z"/>' ) ) ); } /// @dev Earrings N°8 => Gold function item_8() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M298.7,228.1l-4.7-1.6c0,0-0.1,0-0.1-0.1v-0.1c2.8-2.7,7.1-17.2,7.2-17.4c0-0.1,0.1-0.1,0.1-0.1l0,0c5.3,1.1,5.6,2.2,5.7,2.4c-3.1,5.4-8,16.7-8.1,16.8C298.9,228,298.8,228.1,298.7,228.1C298.8,228.1,298.8,228.1,298.7,228.1z" style="fill: #fff700;stroke: #000;stroke-miterlimit: 10;stroke-width: 0.75px"/>' ) ) ); } /// @dev Earrings N°9 => Circle Diamond function item_9() public pure returns (string memory) { return base(circle("AAFFFD")); } /// @dev Earrings N°10 => Drop Heart function item_10() public pure returns (string memory) { return base( string( abi.encodePacked( drop(true), '<path fill="#F44336" d="M285.4,282.6c0.1,0.1,0.2,0.2,0.4,0.2s0.3-0.1,0.4-0.2l6.7-6.8c2.8-2.8,0.8-7.7-3.2-7.7c-2.4,0-3.5,1.8-3.9,2.1c-0.4-0.3-1.5-2.1-3.9-2.1c-4,0-6,4.9-3.2,7.7L285.4,282.6z"/>', drop(false), '<path fill="#F44336" d="M134.7,282.5c0.1,0.1,0.2,0.2,0.4,0.2s0.3-0.1,0.4-0.2l6.7-6.8c2.8-2.8,0.8-7.7-3.2-7.7c-2.4,0-3.5,1.8-3.9,2.1c-0.4-0.3-1.5-2.1-3.9-2.1c-4,0-6,4.9-3.2,7.7L134.7,282.5z"/>' ) ) ); } /// @dev Earrings N11 => Ether function item_11() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M285.7,242.7l-4.6-2.2l4.6,8l4.6-8L285.7,242.7z"/>', '<path d="M289.8,238.9l-4.1-7.1l-4.1,7.1l4.1-1.9L289.8,238.9z"/>', '<path d="M282,239.9l3.7,1.8l3.8-1.8l-3.8-1.8L282,239.9z"/>', '<path d="M134.5,241.8l-3.4-1.9l3.7,7.3l2.8-7.7L134.5,241.8z"/>', '<path d="M137.3,238l-3.3-6.5l-2.5,6.9l2.8-2L137.3,238z"/>', '<path d="M131.7,239.2l2.8,1.5l2.6-1.8l-2.8-1.5L131.7,239.2z"/>' ) ) ); } /// @dev Earrings N°12 => Drop Ether function item_12() public pure returns (string memory) { return base( string( abi.encodePacked( drop(true), '<path d="M285.7,279.7l-4.6-2.2l4.6,8l4.6-8L285.7,279.7z"/>', '<path d="M289.8,275.9l-4.1-7.1l-4.1,7.1l4.1-1.9L289.8,275.9z"/>', '<path d="M282,276.9l3.7,1.8l3.8-1.8l-3.8-1.8L282,276.9z"/><path d="M282,276.9l3.7,1.8l3.8-1.8l-3.8-1.8L282,276.9z"/>', drop(false), '<path d="M135.1,279.7l-4-2.2l4,8l4-8L135.1,279.7z"/>', '<path d="M138.7,275.9l-3.6-7.1l-3.6,7.1l3.6-1.9L138.7,275.9z"/>', '<path d="M131.8,276.9l3.3,1.8l3.3-1.8l-3.3-1.8L131.8,276.9z"/>' ) ) ); } /// @dev earring drop function drop(bool right) private pure returns (string memory) { return string( right ? abi.encodePacked( '<circle cx="285.7" cy="243.2" r="3.4"/>', '<line fill="none" stroke="#000000" stroke-miterlimit="10" x1="285.7" y1="243.2" x2="285.7" y2="270.2"/>' ) : abi.encodePacked( '<ellipse cx="135.1" cy="243.2" rx="3" ry="3.4"/>', '<line fill="none" stroke="#000000" stroke-miterlimit="10" x1="135.1" y1="243.2" x2="135.1" y2="270.2"/>' ) ); } /// @dev Generate circle SVG with the given color function circle(string memory color) private pure returns (string memory) { return string( abi.encodePacked( '<ellipse fill="#', color, '" stroke="#000000" cx="135.1" cy="243.2" rx="3" ry="3.4"/>', '<ellipse fill="#', color, '" stroke="#000000" cx="286.1" cy="243.2" rx="3.3" ry="3.4"/>' ) ); } /// @dev Generate ring SVG with the given color function ring(string memory color) private pure returns (string memory) { return string( abi.encodePacked( '<path fill="none" stroke="#', color, '" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M283.5,246c0,0-4.2,2-3.1,6.1c1,4.1,5.1,3.6,5.4,3.5s3.1-0.9,3-5"/>', '<path fill="none" stroke="#', color, '" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M134.3,244.7c0,0-4.2,2-3.1,6.1c1,4.1,5.1,3.6,5.4,3.5c0.3-0.1,3.1-0.9,3-5"/>' ) ); } /// @notice Return the earring name of the given id /// @param id The earring Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Classic"; } else if (id == 2) { name = "Circle"; } else if (id == 3) { name = "Circle Silver"; } else if (id == 4) { name = "Ring"; } else if (id == 5) { name = "Circle Gold"; } else if (id == 6) { name = "Ring Gold"; } else if (id == 7) { name = "Heart"; } else if (id == 8) { name = "Gold"; } else if (id == 9) { name = "Circle Diamond"; } else if (id == 10) { name = "Drop Heart"; } else if (id == 11) { name = "Ether"; } else if (id == 12) { name = "Drop Ether"; } } /// @dev The base SVG for the earrings function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Earrings">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; import "./constants/Colors.sol"; /// @title Masks SVG generator library MaskDetail { /// @dev Mask N°1 => Maskless function item_1() public pure returns (string memory) { return ""; } /// @dev Mask N°2 => Classic function item_2() public pure returns (string memory) { return base(classicMask("575673")); } /// @dev Mask N°3 => Blue function item_3() public pure returns (string memory) { return base(classicMask(Colors.BLUE)); } /// @dev Mask N°4 => Pink function item_4() public pure returns (string memory) { return base(classicMask(Colors.PINK)); } /// @dev Mask N°5 => Black function item_5() public pure returns (string memory) { return base(classicMask(Colors.BLACK)); } /// @dev Mask N°6 => Bandage White function item_6() public pure returns (string memory) { return base(string(abi.encodePacked(classicMask("F5F5F5"), bandage()))); } /// @dev Mask N°7 => Bandage Classic function item_7() public pure returns (string memory) { return base(string(abi.encodePacked(classicMask("575673"), bandage()))); } /// @dev Mask N°8 => Nihon function item_8() public pure returns (string memory) { return base( string( abi.encodePacked( classicMask("F5F5F5"), '<ellipse opacity="0.87" fill="#FF0039" cx="236.1" cy="259.8" rx="13.4" ry="14.5"/>' ) ) ); } /// @dev Generate classic mask SVG with the given color function classicMask(string memory color) public pure returns (string memory) { return string( abi.encodePacked( '<path fill="#', color, '" stroke="#000000" stroke-miterlimit="10" d=" M175.7,317.7c0,0,20,15.1,82.2,0c0,0-1.2-16.2,3.7-46.8l14-18.7c0,0-41.6-27.8-77.6-37.1c-1.1-0.3-3-0.7-4-0.2 c-19.1,8.1-51.5,33-51.5,33s7.5,20.9,9.9,22.9s24.8,19.4,24.8,19.4s0,0,0,0.1C177.3,291.2,178,298.3,175.7,317.7z"/>', '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M177.1,290.1 c0,0,18.3,14.7,26.3,15s15.1-3.8,15.9-4.3c0.9-0.4,11.6-4.5,25.2-14.1"/>', '<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="266.6" y1="264.4" x2="254.5" y2="278.7"/>', '<path opacity="0.21" d="M197.7,243.5l-7.9-3.5c-0.4-0.2-0.5-0.7-0.2-1.1l3.2-3.3 c0.4-0.4,1-0.5,1.5-0.3l12.7,4.6c0.6,0.2,0.6,1.1-0.1,1.3l-8.7,2.4C198,243.6,197.8,243.6,197.7,243.5z"/>', '<path opacity="0.24" fill-rule="evenodd" clip-rule="evenodd" d="M177.2,291.1 c0,0,23,32.3,39.1,28.1s41.9-20.9,41.9-20.9c1.2-8.7,2.1-18.9,3.2-27.6c-4.6,4.7-12.8,13.2-20.9,18.3c-5,3.1-21.2,14.5-34.9,16 C198.3,305.8,177.2,291.1,177.2,291.1z"/>' ) ); } /// @dev Generate bandage SVG function bandage() public pure returns (string memory) { return string( abi.encodePacked( '<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M142.9,247.9c34.3-21.9,59.3-27.4,92.4-18.5 M266.1,264.1c-21-16.2-60.8-36.4-73.9-29.1c-12.8,7.1-36.4,15.6-45.8,22.7 M230.9,242.8c-32.4,2.5-54.9,0.1-81.3,22.7 M259.8,272.3c-19.7-13.9-46.1-24.1-70.3-25.9 M211.6,250.1c-18.5,1.9-41.8,11.2-56.7,22 M256.7,276.1c-46-11.9-50.4-25.6-94,2.7 M229,267.5c-19.9,0.3-42,9.7-60.6,15.9 M238.4,290.6c-11-3.9-39.3-14.6-51.2-14 M214.5,282.5c-10.3-2.8-23,7.6-30.7,12.6 M221.6,299.8c-3.8-5.5-22.1-7.1-27-11.4 M176.2,312.4c8.2,7.3,65.1,6.4,81.2-2.6 M177.3,305.3c11.1,3.6,15.5,4.2,34.6,2.9 c14.5-1,33.2-2.7,46.2-9.2 M224.4,298.4c9,0,25.6-3.3,34.1-6 M249,285.8c3.6-0.2,7.1-1,10.5-2.3 M215.1,225.7 c-6-1.3-11.9-2.3-17.9-3.6c-4.8-1-9.8-2.1-14.7-1.3"/>' ) ); } /// @notice Return the mask name of the given id /// @param id The mask Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Maskless"; } else if (id == 2) { name = "Classic"; } else if (id == 3) { name = "Blue"; } else if (id == 4) { name = "Pink"; } else if (id == 5) { name = "Black"; } else if (id == 6) { name = "Bandage White"; } else if (id == 7) { name = "Bandage Classic"; } else if (id == 8) { name = "Nihon"; } } /// @dev The base SVG for the eyes function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Mask">', children, "</g>")); } } // 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; pragma abicoder v2; /// @title Color constants library Colors { string internal constant BLACK = "33333D"; string internal constant BLACK_DEEP = "000000"; string internal constant BLUE = "7FBCFF"; string internal constant BROWN = "735742"; string internal constant GRAY = "7F8B8C"; string internal constant GREEN = "2FC47A"; string internal constant PINK = "FF78A9"; string internal constant PURPLE = "A839A4"; string internal constant RED = "D9005E"; string internal constant SAIKI = "F02AB6"; string internal constant WHITE = "F7F7F7"; string internal constant YELLOW = "EFED8F"; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } }
@dev Combine face items
function generateSVGFace(SVGParams memory params) private view returns (string memory) { return string( abi.encodePacked( DetailHelper.getDetailSVG(address(BodyDetail), params.skin), DetailHelper.getDetailSVG(address(MarkDetail), params.mark), DetailHelper.getDetailSVG(address(MouthDetail), params.mouth), DetailHelper.getDetailSVG(address(NoseDetail), params.nose), DetailHelper.getDetailSVG(address(EyesDetail), params.eye), DetailHelper.getDetailSVG(address(EyebrowDetail), params.eyebrow) ) ); }
5,890,144
[ 1, 21720, 7945, 1516, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2103, 26531, 11824, 12, 26531, 1370, 3778, 859, 13, 3238, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 203, 5411, 533, 12, 203, 7734, 24126, 18, 3015, 4420, 329, 12, 203, 10792, 27931, 2276, 18, 588, 6109, 26531, 12, 2867, 12, 2250, 6109, 3631, 859, 18, 7771, 267, 3631, 203, 10792, 27931, 2276, 18, 588, 6109, 26531, 12, 2867, 12, 3882, 6109, 3631, 859, 18, 3355, 3631, 203, 10792, 27931, 2276, 18, 588, 6109, 26531, 12, 2867, 12, 49, 15347, 6109, 3631, 859, 18, 81, 15347, 3631, 203, 10792, 27931, 2276, 18, 588, 6109, 26531, 12, 2867, 12, 2279, 307, 6109, 3631, 859, 18, 2135, 307, 3631, 203, 10792, 27931, 2276, 18, 588, 6109, 26531, 12, 2867, 12, 41, 9707, 6109, 3631, 859, 18, 402, 73, 3631, 203, 10792, 27931, 2276, 18, 588, 6109, 26531, 12, 2867, 12, 41, 20513, 70, 492, 6109, 3631, 859, 18, 402, 24008, 492, 13, 203, 7734, 262, 203, 5411, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.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/common/implementation/FixedPoint.sol pragma solidity ^0.6.0; /** * @title Library for fixed point arithmetic on uints */ library FixedPoint { using SafeMath for uint256; // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // Can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77. uint256 private constant FP_SCALING_FACTOR = 10**18; struct Unsigned { uint256 rawValue; } /** * @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5**18`. * @param a uint to convert into a FixedPoint. * @return the converted FixedPoint. */ function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if equal, or False. */ function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if equal, or False. */ function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the minimum of `a` and `b`. */ function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the maximum of `a` and `b`. */ function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return add(a, fromUnscaledUint(b)); } /** * @notice Subtracts two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return sub(a, fromUnscaledUint(b)); } /** * @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow. * @param a a uint256. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return sub(fromUnscaledUint(a), b); } /** * @notice Multiplies two `Unsigned`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as a uint256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because FP_SCALING_FACTOR != 0. return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR); } /** * @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a uint256. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.mul(b)); } /** * @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 mulRaw = a.rawValue.mul(b.rawValue); uint256 mulFloor = mulRaw / FP_SCALING_FACTOR; uint256 mod = mulRaw.mod(FP_SCALING_FACTOR); if (mod != 0) { return Unsigned(mulFloor.add(1)); } else { return Unsigned(mulFloor); } } /** * @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Unsigned(a.rawValue.mul(b)); } /** * @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as a uint256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.div(b)); } /** * @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a uint256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return div(fromUnscaledUint(a), b); } /** * @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR); uint256 divFloor = aScaled.div(b.rawValue); uint256 mod = aScaled.mod(b.rawValue); if (mod != 0) { return Unsigned(divFloor.add(1)); } else { return Unsigned(divFloor); } } /** * @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))" // similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned. // This creates the possibility of overflow if b is very large. return divCeil(a, fromUnscaledUint(b)); } /** * @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return output is `a` to the power of `b`. */ function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) { output = fromUnscaledUint(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } } // File: contracts/common/interfaces/ExpandedIERC20.sol pragma solidity ^0.6.0; /** * @title ERC20 interface that includes burn and mint methods. */ abstract contract ExpandedIERC20 is IERC20 { /** * @notice Burns a specific amount of the caller's tokens. * @dev Only burns the caller's tokens, so it is safe to leave this method permissionless. */ function burn(uint256 value) external virtual; /** * @notice Mints tokens and adds them to the balance of the `to` address. * @dev This method should be permissioned to only allow designated parties to mint tokens. */ function mint(address to, uint256 value) external virtual returns (bool); } // File: contracts/oracle/interfaces/OracleInterface.sol pragma solidity ^0.6.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ interface OracleInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. */ function requestPrice(bytes32 identifier, uint256 time) external; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice(bytes32 identifier, uint256 time) external view returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice(bytes32 identifier, uint256 time) external view returns (int256); } // File: contracts/oracle/interfaces/IdentifierWhitelistInterface.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /** * @title Interface for whitelists of supported identifiers that the oracle can provide prices for. */ interface IdentifierWhitelistInterface { /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external; /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external; /** * @notice Checks whether an identifier is on the whitelist. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view returns (bool); } // File: contracts/oracle/interfaces/AdministrateeInterface.sol pragma solidity ^0.6.0; /** * @title Interface that all financial contracts expose to the admin. */ interface AdministrateeInterface { /** * @notice Initiates the shutdown process, in case of an emergency. */ function emergencyShutdown() external; /** * @notice A core contract method called independently or as a part of other financial contract transactions. * @dev It pays fees and moves money between margin accounts to make sure they reflect the NAV of the contract. */ function remargin() external; } // File: contracts/oracle/implementation/Constants.sol pragma solidity ^0.6.0; /** * @title Stores common interface names used throughout the DVM by registration in the Finder. */ library OracleInterfaces { bytes32 public constant Oracle = "Oracle"; bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist"; bytes32 public constant Store = "Store"; bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin"; bytes32 public constant Registry = "Registry"; bytes32 public constant CollateralWhitelist = "CollateralWhitelist"; } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20MinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/common/implementation/MultiRole.sol pragma solidity ^0.6.0; library Exclusive { struct RoleMembership { address member; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.member == memberToCheck; } function resetMember(RoleMembership storage roleMembership, address newMember) internal { require(newMember != address(0x0), "Cannot set an exclusive role to 0x0"); roleMembership.member = newMember; } function getMember(RoleMembership storage roleMembership) internal view returns (address) { return roleMembership.member; } function init(RoleMembership storage roleMembership, address initialMember) internal { resetMember(roleMembership, initialMember); } } library Shared { struct RoleMembership { mapping(address => bool) members; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.members[memberToCheck]; } function addMember(RoleMembership storage roleMembership, address memberToAdd) internal { require(memberToAdd != address(0x0), "Cannot add 0x0 to a shared role"); roleMembership.members[memberToAdd] = true; } function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal { roleMembership.members[memberToRemove] = false; } function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal { for (uint256 i = 0; i < initialMembers.length; i++) { addMember(roleMembership, initialMembers[i]); } } } /** * @title Base class to manage permissions for the derived class. */ abstract contract MultiRole { using Exclusive for Exclusive.RoleMembership; using Shared for Shared.RoleMembership; enum RoleType { Invalid, Exclusive, Shared } struct Role { uint256 managingRole; RoleType roleType; Exclusive.RoleMembership exclusiveRoleMembership; Shared.RoleMembership sharedRoleMembership; } mapping(uint256 => Role) private roles; event ResetExclusiveMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event AddedSharedMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event RemovedSharedMember(uint256 indexed roleId, address indexed oldMember, address indexed manager); /** * @notice Reverts unless the caller is a member of the specified roleId. */ modifier onlyRoleHolder(uint256 roleId) { require(holdsRole(roleId, msg.sender), "Sender does not hold required role"); _; } /** * @notice Reverts unless the caller is a member of the manager role for the specified roleId. */ modifier onlyRoleManager(uint256 roleId) { require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager"); _; } /** * @notice Reverts unless the roleId represents an initialized, exclusive roleId. */ modifier onlyExclusive(uint256 roleId) { require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role"); _; } /** * @notice Reverts unless the roleId represents an initialized, shared roleId. */ modifier onlyShared(uint256 roleId) { require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role"); _; } /** * @notice Whether `memberToCheck` is a member of roleId. * @dev Reverts if roleId does not correspond to an initialized role. * @param roleId the Role to check. * @param memberToCheck the address to check. * @return True if `memberToCheck` is a member of `roleId`. */ function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) { Role storage role = roles[roleId]; if (role.roleType == RoleType.Exclusive) { return role.exclusiveRoleMembership.isMember(memberToCheck); } else if (role.roleType == RoleType.Shared) { return role.sharedRoleMembership.isMember(memberToCheck); } revert("Invalid roleId"); } /** * @notice Changes the exclusive role holder of `roleId` to `newMember`. * @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an * initialized, ExclusiveRole. * @param roleId the ExclusiveRole membership to modify. * @param newMember the new ExclusiveRole member. */ function resetMember(uint256 roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) { roles[roleId].exclusiveRoleMembership.resetMember(newMember); emit ResetExclusiveMember(roleId, newMember, msg.sender); } /** * @notice Gets the current holder of the exclusive role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, exclusive role. * @param roleId the ExclusiveRole membership to check. * @return the address of the current ExclusiveRole member. */ function getMember(uint256 roleId) public view onlyExclusive(roleId) returns (address) { return roles[roleId].exclusiveRoleMembership.getMember(); } /** * @notice Adds `newMember` to the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param newMember the new SharedRole member. */ function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.addMember(newMember); emit AddedSharedMember(roleId, newMember, msg.sender); } /** * @notice Removes `memberToRemove` from the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param memberToRemove the current SharedRole member to remove. */ function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.removeMember(memberToRemove); emit RemovedSharedMember(roleId, memberToRemove, msg.sender); } /** * @notice Removes caller from the role, `roleId`. * @dev Reverts if the caller is not a member of the role for `roleId` or if `roleId` is not an * initialized, SharedRole. * @param roleId the SharedRole membership to modify. */ function renounceMembership(uint256 roleId) public onlyShared(roleId) onlyRoleHolder(roleId) { roles[roleId].sharedRoleMembership.removeMember(msg.sender); emit RemovedSharedMember(roleId, msg.sender, msg.sender); } /** * @notice Reverts if `roleId` is not initialized. */ modifier onlyValidRole(uint256 roleId) { require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId"); _; } /** * @notice Reverts if `roleId` is initialized. */ modifier onlyInvalidRole(uint256 roleId) { require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role"); _; } /** * @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`. * `initialMembers` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createSharedRole( uint256 roleId, uint256 managingRoleId, address[] memory initialMembers ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Shared; role.managingRole = managingRoleId; role.sharedRoleMembership.init(initialMembers); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage a shared role" ); } /** * @notice Internal method to initialize an exclusive role, `roleId`, which will be managed by `managingRoleId`. * `initialMember` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Exclusive; role.managingRole = managingRoleId; role.exclusiveRoleMembership.init(initialMember); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage an exclusive role" ); } } // File: contracts/common/implementation/ExpandedERC20.sol pragma solidity ^0.6.0; /** * @title An ERC20 with permissioned burning and minting. The contract deployer will initially * be the owner who is capable of adding new roles. */ contract ExpandedERC20 is ExpandedIERC20, ERC20, MultiRole { enum Roles { // Can set the minter and burner. Owner, // Addresses that can mint new tokens. Minter, // Addresses that can burn tokens that address owns. Burner } /** * @notice Constructs the ExpandedERC20. * @param _tokenName The name which describes the new token. * @param _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _tokenDecimals The number of decimals to define token precision. */ constructor( string memory _tokenName, string memory _tokenSymbol, uint8 _tokenDecimals ) public ERC20(_tokenName, _tokenSymbol) { _setupDecimals(_tokenDecimals); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createSharedRole(uint256(Roles.Minter), uint256(Roles.Owner), new address[](0)); _createSharedRole(uint256(Roles.Burner), uint256(Roles.Owner), new address[](0)); } /** * @dev Mints `value` tokens to `recipient`, returning true on success. * @param recipient address to mint to. * @param value amount of tokens to mint. * @return True if the mint succeeded, or False. */ function mint(address recipient, uint256 value) external override onlyRoleHolder(uint256(Roles.Minter)) returns (bool) { _mint(recipient, value); return true; } /** * @dev Burns `value` tokens owned by `msg.sender`. * @param value amount of tokens to burn. */ function burn(uint256 value) external override onlyRoleHolder(uint256(Roles.Burner)) { _burn(msg.sender, value); } } // File: contracts/common/implementation/Lockable.sol pragma solidity ^0.6.0; /** * @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract * is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol * and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol. */ contract Lockable { bool private _notEntered; constructor() internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _preEntranceCheck(); _preEntranceSet(); _; _postEntranceReset(); } /** * @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method. */ modifier nonReentrantView() { _preEntranceCheck(); _; } // Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method. // On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being re-entered. // Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and then call `_postEntranceReset()`. // View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered. function _preEntranceCheck() internal view { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); } function _preEntranceSet() internal { // Any calls to nonReentrant after this point will fail _notEntered = false; } function _postEntranceReset() internal { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // File: contracts/financial-templates/common/SyntheticToken.sol pragma solidity ^0.6.0; /** * @title Burnable and mintable ERC20. * @dev The contract deployer will initially be the only minter, burner and owner capable of adding new roles. */ contract SyntheticToken is ExpandedERC20, Lockable { /** * @notice Constructs the SyntheticToken. * @param tokenName The name which describes the new token. * @param tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals The number of decimals to define token precision. */ constructor( string memory tokenName, string memory tokenSymbol, uint8 tokenDecimals ) public ExpandedERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {} /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external nonReentrant() { addMember(uint256(Roles.Minter), account); } /** * @notice Remove Minter role from account. * @dev The caller must have the Owner role. * @param account The address from which the Minter role is removed. */ function removeMinter(address account) external nonReentrant() { removeMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external nonReentrant() { addMember(uint256(Roles.Burner), account); } /** * @notice Removes Burner role from account. * @dev The caller must have the Owner role. * @param account The address from which the Burner role is removed. */ function removeBurner(address account) external nonReentrant() { removeMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external nonReentrant() { resetMember(uint256(Roles.Owner), account); } /** * @notice Checks if a given account holds the Minter role. * @param account The address which is checked for the Minter role. * @return bool True if the provided account is a Minter. */ function isMinter(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Minter), account); } /** * @notice Checks if a given account holds the Burner role. * @param account The address which is checked for the Burner role. * @return bool True if the provided account is a Burner. */ function isBurner(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Burner), account); } } // File: contracts/financial-templates/common/TokenFactory.sol pragma solidity ^0.6.0; /** * @title Factory for creating new mintable and burnable tokens. */ contract TokenFactory is Lockable { /** * @notice Create a new token and return it to the caller. * @dev The caller will become the only minter and burner and the new owner capable of assigning the roles. * @param tokenName used to describe the new token. * @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals used to define the precision used in the token's numerical representation. * @return newToken an instance of the newly created token interface. */ function createToken( string calldata tokenName, string calldata tokenSymbol, uint8 tokenDecimals ) external nonReentrant() returns (ExpandedIERC20 newToken) { SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals); mintableToken.addMinter(msg.sender); mintableToken.addBurner(msg.sender); mintableToken.resetOwner(msg.sender); newToken = ExpandedIERC20(address(mintableToken)); } } // File: contracts/common/implementation/Timer.sol pragma solidity ^0.6.0; /** * @title Universal store of current contract time for testing environments. */ contract Timer { uint256 private currentTime; constructor() public { currentTime = now; // solhint-disable-line not-rely-on-time } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set `currentTime` to. */ function setCurrentTime(uint256 time) external { currentTime = time; } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint256 for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { return currentTime; } } // File: contracts/common/implementation/Testable.sol pragma solidity ^0.6.0; /** * @title Base class that provides time overrides, but only if being run in test mode. */ abstract contract Testable { // If the contract is being run on the test network, then `timerAddress` will be the 0x0 address. // Note: this variable should be set on construction and never modified. address public timerAddress; /** * @notice Constructs the Testable contract. Called by child contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor(address _timerAddress) internal { timerAddress = _timerAddress; } /** * @notice Reverts if not running in test mode. */ modifier onlyIfTest { require(timerAddress != address(0x0)); _; } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set current Testable time to. */ function setCurrentTime(uint256 time) external onlyIfTest { Timer(timerAddress).setCurrentTime(time); } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { if (timerAddress != address(0x0)) { return Timer(timerAddress).getCurrentTime(); } else { return now; // solhint-disable-line not-rely-on-time } } } // File: contracts/oracle/interfaces/StoreInterface.sol pragma solidity ^0.6.0; /** * @title Interface that allows financial contracts to pay oracle fees for their use of the system. */ interface StoreInterface { /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable; /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external; /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty); /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due. */ function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory); } // File: contracts/oracle/interfaces/FinderInterface.sol pragma solidity ^0.6.0; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples are the Oracle or Store interfaces. */ interface FinderInterface { /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 encoding of the interface name that is either changed or registered. * @param implementationAddress address of the deployed contract that implements the interface. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external; /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the deployed contract that implements the interface. */ function getImplementationAddress(bytes32 interfaceName) external view returns (address); } // File: contracts/financial-templates/common/FeePayer.sol pragma solidity ^0.6.0; /** * @title FeePayer contract. * @notice Provides fee payment functionality for the ExpiringMultiParty contract. * contract is abstract as each derived contract that inherits `FeePayer` must implement `pfc()`. */ abstract contract FeePayer is Testable, Lockable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; /**************************************** * FEE PAYER DATA STRUCTURES * ****************************************/ // The collateral currency used to back the positions in this contract. IERC20 public collateralCurrency; // Finder contract used to look up addresses for UMA system contracts. FinderInterface public finder; // Tracks the last block time when the fees were paid. uint256 private lastPaymentTime; // Tracks the cumulative fees that have been paid by the contract for use by derived contracts. // The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee). // Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ... // For example: // The cumulativeFeeMultiplier should start at 1. // If a 1% fee is charged, the multiplier should update to .99. // If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801). FixedPoint.Unsigned public cumulativeFeeMultiplier; /**************************************** * EVENTS * ****************************************/ event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee); event FinalFeesPaid(uint256 indexed amount); /**************************************** * MODIFIERS * ****************************************/ // modifier that calls payRegularFees(). modifier fees { payRegularFees(); _; } /** * @notice Constructs the FeePayer contract. Called by child contracts. * @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, address _timerAddress ) public Testable(_timerAddress) nonReentrant() { collateralCurrency = IERC20(_collateralAddress); finder = FinderInterface(_finderAddress); lastPaymentTime = getCurrentTime(); cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1); } /**************************************** * FEE PAYMENT FUNCTIONS * ****************************************/ /** * @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract. * @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee * in a week or more then a late penalty is applied which is sent to the caller. If the amount of * fees owed are greater than the pfc, then this will pay as much as possible from the available collateral. * An event is only fired if the fees charged are greater than 0. * @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller). * This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0. */ function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { StoreInterface store = _getStore(); uint256 time = getCurrentTime(); FixedPoint.Unsigned memory collateralPool = _pfc(); // Exit early if there is no collateral from which to pay fees. if (collateralPool.isEqual(0)) { return totalPaid; } // Exit early if fees were already paid during this block. if (lastPaymentTime == time) { return totalPaid; } (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) = store.computeRegularFee( lastPaymentTime, time, collateralPool ); lastPaymentTime = time; totalPaid = regularFee.add(latePenalty); if (totalPaid.isEqual(0)) { return totalPaid; } // If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay // as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the // regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining. if (totalPaid.isGreaterThan(collateralPool)) { FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool); FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit); latePenalty = latePenalty.sub(latePenaltyReduction); deficit = deficit.sub(latePenaltyReduction); regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit)); totalPaid = collateralPool; } emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue); _adjustCumulativeFeeMultiplier(totalPaid, collateralPool); if (regularFee.isGreaterThan(0)) { collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue); store.payOracleFeesErc20(address(collateralCurrency), regularFee); } if (latePenalty.isGreaterThan(0)) { collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue); } return totalPaid; } /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _pfc(); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee // charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not // the contract, pulls in `amount` of collateral currency. function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal { if (amount.isEqual(0)) { return; } if (payer != address(this)) { // If the payer is not the contract pull the collateral from the payer. collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue); } else { // If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate. FixedPoint.Unsigned memory collateralPool = _pfc(); // The final fee must be < available collateral or the fee will be larger than 100%. require(collateralPool.isGreaterThan(amount), "Final fee is more than PfC"); _adjustCumulativeFeeMultiplier(amount, collateralPool); } emit FinalFeesPaid(amount.rawValue); StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue); store.payOracleFeesErc20(address(collateralCurrency), amount); } function _pfc() internal virtual view returns (FixedPoint.Unsigned memory); function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) { StoreInterface store = _getStore(); return store.computeFinalFee(address(collateralCurrency)); } // Returns the user's collateral minus any fees that have been subtracted since it was originally // deposited into the contract. Note: if the contract has paid fees since it was deployed, the raw // value should be larger than the returned value. function _getFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral) internal view returns (FixedPoint.Unsigned memory collateral) { return rawCollateral.mul(cumulativeFeeMultiplier); } // Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees // have been taken from this contract in the past, then the raw value will be larger than the user-readable value. function _convertToRawCollateral(FixedPoint.Unsigned memory collateral) internal view returns (FixedPoint.Unsigned memory rawCollateral) { return collateral.div(cumulativeFeeMultiplier); } // Decrease rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is decreased by less than expected. Because this method is usually called in conjunction with an // actual removal of collateral from this contract, return the fee-adjusted amount that the rawCollateral is // decreased by so that the caller can minimize error between collateral removed and rawCollateral debited. function _removeCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToRemove) internal returns (FixedPoint.Unsigned memory removedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToRemove); rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue; removedCollateral = initialBalance.sub(_getFeeAdjustedCollateral(rawCollateral)); } // Increase rawCollateral by a fee-adjusted collateralToAdd amount. Fee adjustment scales up collateralToAdd // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is increased by less than expected. Because this method is usually called in conjunction with an // actual addition of collateral to this contract, return the fee-adjusted amount that the rawCollateral is // increased by so that the caller can minimize error between collateral added and rawCollateral credited. // NOTE: This return value exists only for the sake of symmetry with _removeCollateral. We don't actually use it // because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral. function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd) internal returns (FixedPoint.Unsigned memory addedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToAdd); rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue; addedCollateral = _getFeeAdjustedCollateral(rawCollateral).sub(initialBalance); } // Scale the cumulativeFeeMultiplier by the ratio of fees paid to the current available collateral. function _adjustCumulativeFeeMultiplier(FixedPoint.Unsigned memory amount, FixedPoint.Unsigned memory currentPfc) internal { FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc); cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee)); } } // File: contracts/financial-templates/expiring-multiparty/PricelessPositionManager.sol pragma solidity ^0.6.0; /** * @title Financial contract with priceless position management. * @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying * on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token. */ contract PricelessPositionManager is FeePayer, AdministrateeInterface { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement. enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived } ContractState public contractState; // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; // Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`. uint256 transferPositionRequestPassTimestamp; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that this contract expires. Should not change post-construction unless an emergency shutdown occurs. uint256 public expirationTimestamp; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // The expiry price pulled from the DVM. FixedPoint.Unsigned public expiryPrice; // The excessTokenBeneficiary of any excess tokens added to the contract. address public excessTokenBeneficiary; /**************************************** * EVENTS * ****************************************/ event RequestTransferPosition(address indexed oldSponsor); event RequestTransferPositionExecuted(address indexed oldSponsor, address indexed newSponsor); event RequestTransferPositionCanceled(address indexed oldSponsor); event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event ContractExpired(address indexed caller); event SettleExpiredPosition( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); event EmergencyShutdown(address indexed caller, uint256 originalExpirationTimestamp, uint256 shutdownTimestamp); /**************************************** * MODIFIERS * ****************************************/ modifier onlyPreExpiration() { _onlyPreExpiration(); _; } modifier onlyPostExpiration() { _onlyPostExpiration(); _; } modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } // Check that the current state of the pricelessPositionManager is Open. // This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration. modifier onlyOpenState() { _onlyOpenState(); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PricelessPositionManager * @param _expirationTimestamp unix timestamp of when the contract will expire. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _syntheticName name for the token contract that will be deployed. * @param _syntheticSymbol symbol for the token contract that will be deployed. * @param _tokenFactoryAddress deployed UMA token factory to create the synthetic token. * @param _minSponsorTokens minimum amount of collateral that must exist at any time in a position. * @param _timerAddress Contract that stores the current time in a testing environment. * @param _excessTokenBeneficiary Beneficiary to which all excess token balances that accrue in the contract can be * sent. * Must be set to 0x0 for production environments that use live time. */ constructor( uint256 _expirationTimestamp, uint256 _withdrawalLiveness, address _collateralAddress, address _finderAddress, bytes32 _priceIdentifier, string memory _syntheticName, string memory _syntheticSymbol, address _tokenFactoryAddress, FixedPoint.Unsigned memory _minSponsorTokens, address _timerAddress, address _excessTokenBeneficiary ) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_expirationTimestamp > getCurrentTime(), "Invalid expiration in future"); require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier"); expirationTimestamp = _expirationTimestamp; withdrawalLiveness = _withdrawalLiveness; TokenFactory tf = TokenFactory(_tokenFactoryAddress); tokenCurrency = tf.createToken(_syntheticName, _syntheticSymbol, 18); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; excessTokenBeneficiary = _excessTokenBeneficiary; } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Requests to transfer ownership of the caller's current position to a new sponsor address. * Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor. * @dev The liveness length is the same as the withdrawal liveness. */ function requestTransferPosition() public onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp == 0, "Pending transfer"); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp, "Request expires post-expiry"); // Update the position object for the user. positionData.transferPositionRequestPassTimestamp = requestPassTime; emit RequestTransferPosition(msg.sender); } /** * @notice After a passed transfer position request (i.e., by a call to `requestTransferPosition` and waiting * `withdrawalLiveness`), transfers ownership of the caller's current position to `newSponsorAddress`. * @dev Transferring positions can only occur if the recipient does not already have a position. * @param newSponsorAddress is the address to which the position will be transferred. */ function transferPositionPassedRequest(address newSponsorAddress) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { require( _getFeeAdjustedCollateral(positions[newSponsorAddress].rawCollateral).isEqual( FixedPoint.fromUnscaledUint(0) ), "Sponsor already has position" ); PositionData storage positionData = _getPositionData(msg.sender); require( positionData.transferPositionRequestPassTimestamp != 0 && positionData.transferPositionRequestPassTimestamp <= getCurrentTime(), "Invalid transfer request" ); // Reset transfer request. positionData.transferPositionRequestPassTimestamp = 0; positions[newSponsorAddress] = positionData; delete positions[msg.sender]; emit RequestTransferPositionExecuted(msg.sender, newSponsorAddress); emit NewSponsor(newSponsorAddress); emit EndedSponsorPosition(msg.sender); } /** * @notice Cancels a pending transfer position request. */ function cancelTransferPosition() external onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp != 0, "No pending transfer"); emit RequestTransferPositionCanceled(msg.sender); // Reset withdrawal request. positionData.transferPositionRequestPassTimestamp = 0; } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0), "Invalid collateral amount"); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(collateralAmount.isGreaterThan(0), "Invalid collateral amount"); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the witdrawl. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)), "Invalid collateral amount" ); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp, "Request expires post-expiry"); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = requestPassTime; positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external onlyPreExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime(), "Invalid withdraw request" ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.withdrawalRequestPassTimestamp != 0, "No pending withdrawal"); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; // Either the new create ratio or the resultant position CR must be above the current GCR. require( (_checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount), positionData.tokensOutstanding.add(numTokens) ) || _checkCollateralization(collateralAmount, numTokens)), "Insufficient collateral" ); require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); require(tokenCurrency.mint(msg.sender, numTokens.rawValue), "Minting synthetic tokens failed"); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(!numTokens.isGreaterThan(positionData.tokensOutstanding), "Invalid token amount"); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul( _getFeeAdjustedCollateral(positionData.rawCollateral) ); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice After a contract has passed expiry all token holders can redeem their tokens for underlying at the * prevailing price defined by the DVM from the `expire` function. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the proportional amount of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleExpired() external onlyPostExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // If the contract state is open and onlyPostExpiration passed then `expire()` has not yet been called. require(contractState != ContractState.Open, "Unexpired position"); // Get the current settlement price and store it. If it is not resolved will revert. if (contractState != ContractState.ExpiredPriceReceived) { expiryPrice = _getOraclePrice(expirationTimestamp); contractState = ContractState.ExpiredPriceReceived; } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = tokensToRedeem.mul(expiryPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying. FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan( positionCollateral ) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min( _getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral ); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleExpiredPosition(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Locks contract state in expired and requests oracle price. * @dev this function can only be called once the contract is expired and can't be re-called. */ function expire() external onlyPostExpiration() onlyOpenState() fees() nonReentrant() { contractState = ContractState.ExpiredPriceRequested; // The final fee for this request is paid out of the contract rather than by the caller. _payFinalFees(address(this), _computeFinalFees()); _requestOraclePrice(expirationTimestamp); emit ContractExpired(msg.sender); } /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the standard `settleExpired` function. Contract state is set to `ExpiredPriceRequested` * which prevents re-entry into this function or the `expire` function. No fees are paid when calling * `emergencyShutdown` as the governor who would call the function would also receive the fees. */ function emergencyShutdown() external override onlyPreExpiration() onlyOpenState() nonReentrant() { require(msg.sender == _getFinancialContractsAdminAddress(), "Caller not Governor"); contractState = ContractState.ExpiredPriceRequested; // Expiratory time now becomes the current time (emergency shutdown time). // Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp. uint256 oldExpirationTimestamp = expirationTimestamp; expirationTimestamp = getCurrentTime(); _requestOraclePrice(expirationTimestamp); emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override onlyPreExpiration() nonReentrant() { return; } /** * @notice Drains any excess balance of the provided ERC20 token to a pre-selected beneficiary. * @dev This will drain down to the amount of tracked collateral and drain the full balance of any other token. * @param token address of the ERC20 token whose excess balance should be drained. */ function trimExcess(IERC20 token) external fees() nonReentrant() returns (FixedPoint.Unsigned memory amount) { FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(token.balanceOf(address(this))); if (address(token) == address(collateralCurrency)) { // If it is the collateral currency, send only the amount that the contract is not tracking. // Note: this could be due to rounding error or balance-changing tokens, like aTokens. amount = balance.sub(_pfc()); } else { // If it's not the collateral currency, send the entire balance. amount = balance; } token.safeTransfer(excessTokenBeneficiary, amount.rawValue); } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory collateralAmount) { // Note: do a direct access to avoid the validity check. return _getFeeAdjustedCollateral(positions[sponsor].rawCollateral); } /** * @notice Accessor method for the total collateral stored within the PricelessPositionManager. * @return totalCollateral amount of all collateral within the Expiring Multi Party Contract. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(tokensToRemove); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral; rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal virtual override view returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(priceIdentifier, requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OracleInterface oracle = _getOracle(); require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyOpenState() internal view { require(contractState == ContractState.Open, "Contract state is not OPEN"); } function _onlyPreExpiration() internal view { require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry"); } function _onlyPostExpiration() internal view { require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry"); } function _onlyCollateralizedPosition(address sponsor) internal view { require( _getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0), "Position has no collateral" ); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio( _getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding ); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { if (!numTokens.isGreaterThan(0)) { return FixedPoint.fromUnscaledUint(0); } else { return collateral.div(numTokens); } } } // File: contracts/financial-templates/expiring-multiparty/Liquidatable.sol pragma solidity ^0.6.0; /** * @title Liquidatable * @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position. * @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the * liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on * a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false * liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a * prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute. */ contract Liquidatable is PricelessPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, PreDispute, PendingDispute, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PricelessPositionManager only. uint256 expirationTimestamp; uint256 withdrawalLiveness; address collateralAddress; address finderAddress; address tokenFactoryAddress; address timerAddress; address excessTokenBeneficiary; bytes32 priceFeedIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned minSponsorTokens; // Params specifically for Liquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPct; FixedPoint.Unsigned sponsorDisputeRewardPct; FixedPoint.Unsigned disputerDisputeRewardPct; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPct; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPct; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPct; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 withdrawalAmount, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PricelessPositionManager( params.expirationTimestamp, params.withdrawalLiveness, params.collateralAddress, params.finderAddress, params.priceFeedIdentifier, params.syntheticName, params.syntheticSymbol, params.tokenFactoryAddress, params.minSponsorTokens, params.timerAddress, params.excessTokenBeneficiary ) nonReentrant() { require(params.collateralRequirement.isGreaterThan(1), "CR is more than 100%"); require( params.sponsorDisputeRewardPct.add(params.disputerDisputeRewardPct).isLessThan(1), "Rewards are more than 100%" ); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPct = params.disputeBondPct; sponsorDisputeRewardPct = params.sponsorDisputeRewardPct; disputerDisputeRewardPct = params.disputerDisputeRewardPct; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external fees() onlyPreExpiration() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. // maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul( ratio ); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.PreDispute, liquidationTime: getCurrentTime(), tokensOutstanding: tokensLiquidated, lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp <= getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(liquidationLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, tokensLiquidated.rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond * and pay a fixed final fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPct` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPct).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.PendingDispute; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePrice(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * the sponsor, liquidator, and/or disputer can call this method to receive payments. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator can receive payment. * Once all collateral is withdrawn, delete the liquidation data. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return amountWithdrawn the total amount of underlying returned from the liquidation. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (msg.sender == liquidation.disputer) || (msg.sender == liquidation.liquidator) || (msg.sender == liquidation.sponsor), "Caller cannot withdraw rewards" ); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul( feeAttenuation ); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPct.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPct.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPct); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation can withdraw different amounts. // Once a caller has been paid their address deleted from the struct. // This prevents them from being paid multiple from times the same liquidation. FixedPoint.Unsigned memory withdrawalAmount = FixedPoint.fromUnscaledUint(0); if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users can withdraw from the contract. if (msg.sender == liquidation.disputer) { // Pay DISPUTER: disputer reward + dispute bond + returned final fee FixedPoint.Unsigned memory payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); withdrawalAmount = withdrawalAmount.add(payToDisputer); delete liquidation.disputer; } if (msg.sender == liquidation.sponsor) { // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward FixedPoint.Unsigned memory remainingCollateral = collateral.sub(tokenRedemptionValue); FixedPoint.Unsigned memory payToSponsor = sponsorDisputeReward.add(remainingCollateral); withdrawalAmount = withdrawalAmount.add(payToSponsor); delete liquidation.sponsor; } if (msg.sender == liquidation.liquidator) { // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: This should never be below zero since we prevent (sponsorDisputePct+disputerDisputePct) >= 0 in // the constructor when these params are set. FixedPoint.Unsigned memory payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub( disputerDisputeReward ); withdrawalAmount = withdrawalAmount.add(payToLiquidator); delete liquidation.liquidator; } // Free up space once all collateral is withdrawn by removing the liquidation object from the array. if ( liquidation.disputer == address(0) && liquidation.sponsor == address(0) && liquidation.liquidator == address(0) ) { delete liquidations[sponsor][liquidationId]; } // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed && msg.sender == liquidation.liquidator) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee withdrawalAmount = collateral.add(disputeBondAmount).add(finalFee); delete liquidations[sponsor][liquidationId]; // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.PreDispute && msg.sender == liquidation.liquidator) { // Pay LIQUIDATOR: collateral + returned final fee withdrawalAmount = collateral.add(finalFee); delete liquidations[sponsor][liquidationId]; } require(withdrawalAmount.isGreaterThan(0), "Invalid withdrawal amount"); // Decrease the total collateral held in liquidatable by the amount withdrawn. amountWithdrawn = _removeCollateral(rawLiquidationCollateral, withdrawalAmount); emit LiquidationWithdrawn(msg.sender, amountWithdrawn.rawValue, liquidation.state, settlementPrice.rawValue); // Transfer amount withdrawn from this contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); return amountWithdrawn; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the PendingDispute state. If not, it will immediately return. // If the liquidation is in the PendingDispute state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == PendingDispute and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.PendingDispute) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul( liquidation.settlementPrice ); // The required collateral is the value of the tokens in underlying * required collateral ratio. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement); // If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal override view returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized, "Invalid liquidation ID" ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.PreDispute), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.PreDispute) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.PreDispute)), "Liquidation not withdrawable" ); } } // File: contracts/financial-templates/expiring-multiparty/ExpiringMultiParty.sol pragma solidity ^0.6.0; /** * @title Expiring Multi Party. * @notice Convenient wrapper for Liquidatable. */ contract ExpiringMultiParty is Liquidatable { /** * @notice Constructs the ExpiringMultiParty contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public Liquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } }
Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%"
FixedPoint.Unsigned public disputeBondPct;
107,674
[ 1, 8410, 434, 279, 511, 18988, 350, 367, 19, 2555, 1807, 8586, 13535, 2045, 287, 358, 506, 443, 1724, 329, 635, 279, 8555, 1015, 458, 264, 868, 6706, 329, 487, 279, 15027, 16, 364, 3454, 404, 18, 25, 73, 2643, 273, 315, 23014, 16407, 471, 374, 18, 6260, 73, 2643, 273, 315, 25, 16407, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 15038, 2148, 18, 13290, 1071, 1015, 2507, 9807, 52, 299, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xB985eA1be961f7c4A4C45504444C02c88c4fdEF9/sources/lib/hats-module/lib/solady/src/utils/LibClone.sol
@dev Deploys a deterministic clone of `implementation` with `salt`. @solidity memory-safe-assembly If `instance` is zero, revert. Store the function selector of `DeploymentFailed()`. Revert with (offset, size).
function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { assembly { mstore(0x21, 0x5af43d3d93803e602a57fd5bf3) mstore(0x14, implementation) mstore(0x00, 0x602c3d8160093d39f33d3d3d3d363d3d37363d73) instance := create2(0, 0x0c, 0x35, salt) if iszero(instance) { mstore(0x00, 0x30116425) revert(0x1c, 0x04) } } }
2,750,453
[ 1, 16316, 383, 1900, 279, 25112, 3236, 434, 1375, 30810, 68, 598, 1375, 5759, 8338, 632, 30205, 560, 3778, 17, 4626, 17, 28050, 971, 1375, 1336, 68, 353, 3634, 16, 15226, 18, 4994, 326, 445, 3451, 434, 1375, 6733, 2925, 1435, 8338, 868, 1097, 598, 261, 3348, 16, 963, 2934, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3236, 9139, 5846, 12, 2867, 4471, 16, 1731, 1578, 4286, 13, 203, 3639, 2713, 203, 3639, 1135, 261, 2867, 791, 13, 203, 565, 288, 203, 3639, 19931, 288, 203, 5411, 312, 2233, 12, 20, 92, 5340, 16, 374, 92, 25, 1727, 8942, 72, 23, 72, 11180, 3672, 23, 73, 26, 3103, 69, 10321, 8313, 25, 17156, 23, 13, 203, 5411, 312, 2233, 12, 20, 92, 3461, 16, 4471, 13, 203, 5411, 312, 2233, 12, 20, 92, 713, 16, 374, 92, 26, 3103, 71, 23, 72, 28, 2313, 713, 11180, 72, 5520, 74, 3707, 72, 23, 72, 23, 72, 23, 72, 23, 4449, 72, 23, 72, 6418, 23, 4449, 72, 9036, 13, 203, 5411, 791, 519, 752, 22, 12, 20, 16, 374, 92, 20, 71, 16, 374, 92, 4763, 16, 4286, 13, 203, 5411, 309, 353, 7124, 12, 1336, 13, 288, 203, 7734, 312, 2233, 12, 20, 92, 713, 16, 374, 92, 31831, 23147, 2947, 13, 203, 7734, 15226, 12, 20, 92, 21, 71, 16, 374, 92, 3028, 13, 203, 5411, 289, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/432204/0x186D0bafbb140d3D216Fb8353F35EE42868a391A/sources/contracts/ExchangeSub.sol
* @notice Sets auction price @param _tradePairId id of the trading pair @param _price price/
function setAuctionPrice(bytes32 _tradePairId, uint256 _price) external onlyRole(AUCTION_ADMIN_ROLE) { ITradePairs.AuctionMode mode = tradePairs.getTradePair(_tradePairId).auctionMode; require(mode != ITradePairs.AuctionMode.OFF, "E-OACC-04"); tradePairs.setAuctionPrice(_tradePairId, _price); }
16,381,638
[ 1, 2785, 279, 4062, 6205, 565, 389, 20077, 4154, 548, 225, 612, 434, 326, 1284, 7459, 3082, 565, 389, 8694, 225, 6205, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 37, 4062, 5147, 12, 3890, 1578, 389, 20077, 4154, 548, 16, 2254, 5034, 389, 8694, 13, 3903, 1338, 2996, 12, 14237, 3106, 67, 15468, 67, 16256, 13, 288, 203, 3639, 467, 22583, 10409, 18, 37, 4062, 2309, 1965, 273, 18542, 10409, 18, 588, 22583, 4154, 24899, 20077, 4154, 548, 2934, 69, 4062, 2309, 31, 203, 3639, 2583, 12, 3188, 480, 467, 22583, 10409, 18, 37, 4062, 2309, 18, 8797, 16, 315, 41, 17, 51, 31414, 17, 3028, 8863, 203, 3639, 18542, 10409, 18, 542, 37, 4062, 5147, 24899, 20077, 4154, 548, 16, 389, 8694, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import './interfaces/IArchRouterImmutableState.sol'; /// @title Immutable state /// @notice Immutable state used by periphery contracts abstract contract ArchRouterImmutableState is IArchRouterImmutableState { /// @inheritdoc IArchRouterImmutableState address public immutable override uniV3Factory; /// @inheritdoc IArchRouterImmutableState address public immutable override WETH; constructor(address _uniV3Factory, address _WETH) { uniV3Factory = _uniV3Factory; WETH = _WETH; } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* Copyright 2021 Archer DAO: Chris Piatt ([email protected]). */ import './interfaces/IERC20Extended.sol'; import './interfaces/IUniswapV2Pair.sol'; import './interfaces/IUniswapV3Pool.sol'; import './interfaces/IUniV3Router.sol'; import './interfaces/IWETH.sol'; import './lib/RouteLib.sol'; import './lib/TransferHelper.sol'; import './lib/SafeCast.sol'; import './lib/Path.sol'; import './lib/CallbackValidation.sol'; import './ArchRouterImmutableState.sol'; import './PaymentsWithFee.sol'; import './Multicall.sol'; import './SelfPermit.sol'; /** * @title ArcherSwapRouter * @dev Allows Uniswap V2/V3 Router-compliant trades to be paid via tips instead of gas */ contract ArcherSwapRouter is IUniV3Router, ArchRouterImmutableState, PaymentsWithFee, Multicall, SelfPermit { using Path for bytes; using SafeCast for uint256; /// @dev Used as the placeholder value for amountInCached, because the computed amount in for an exact output swap /// can never actually be this value uint256 private constant DEFAULT_AMOUNT_IN_CACHED = type(uint256).max; /// @dev Transient storage variable used for returning the computed amount in for an exact output swap. uint256 private amountInCached = DEFAULT_AMOUNT_IN_CACHED; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Trade details struct Trade { uint amountIn; uint amountOut; address[] path; address payable to; uint256 deadline; } /// @notice Uniswap V3 Swap Callback struct SwapCallbackData { bytes path; address payer; } /** * @notice Construct new ArcherSwap Router * @param _uniV3Factory Uni V3 Factory address * @param _WETH WETH address */ constructor(address _uniV3Factory, address _WETH) ArchRouterImmutableState(_uniV3Factory, _WETH) {} /** * @notice Swap tokens for ETH and pay amount of ETH as tip * @param factory Uniswap V2-compliant Factory contract * @param trade Trade details */ function swapExactTokensForETHAndTipAmount( address factory, Trade calldata trade, uint256 tipAmount ) external payable { require(trade.path[trade.path.length - 1] == WETH, 'ArchRouter: INVALID_PATH'); TransferHelper.safeTransferFrom( trade.path[0], msg.sender, RouteLib.pairFor(factory, trade.path[0], trade.path[1]), trade.amountIn ); _exactInputSwap(factory, trade.path, address(this)); uint256 amountOut = IWETH(WETH).balanceOf(address(this)); require(amountOut >= trade.amountOut, 'ArchRouter: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).withdraw(amountOut); tip(tipAmount); TransferHelper.safeTransferETH(trade.to, amountOut - tipAmount); } /** * @notice Swap tokens for ETH and pay amount of ETH as tip * @param factory Uniswap V2-compliant Factory contract * @param trade Trade details */ function swapTokensForExactETHAndTipAmount( address factory, Trade calldata trade, uint256 tipAmount ) external payable { require(trade.path[trade.path.length - 1] == WETH, 'ArchRouter: INVALID_PATH'); uint[] memory amounts = RouteLib.getAmountsIn(factory, trade.amountOut, trade.path); require(amounts[0] <= trade.amountIn, 'ArchRouter: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( trade.path[0], msg.sender, RouteLib.pairFor(factory, trade.path[0], trade.path[1]), amounts[0] ); _exactOutputSwap(factory, amounts, trade.path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); tip(tipAmount); TransferHelper.safeTransferETH(trade.to, trade.amountOut - tipAmount); } /** * @notice Swap ETH for tokens and pay % of ETH input as tip * @param factory Uniswap V2-compliant Factory contract * @param trade Trade details * @param tipAmount amount of ETH to pay as tip */ function swapExactETHForTokensAndTipAmount( address factory, Trade calldata trade, uint256 tipAmount ) external payable { tip(tipAmount); require(trade.path[0] == WETH, 'ArchRouter: INVALID_PATH'); uint256 inputAmount = msg.value - tipAmount; IWETH(WETH).deposit{value: inputAmount}(); assert(IWETH(WETH).transfer(RouteLib.pairFor(factory, trade.path[0], trade.path[1]), inputAmount)); uint256 balanceBefore = IERC20Extended(trade.path[trade.path.length - 1]).balanceOf(trade.to); _exactInputSwap(factory, trade.path, trade.to); require( IERC20Extended(trade.path[trade.path.length - 1]).balanceOf(trade.to) - balanceBefore >= trade.amountOut, 'ArchRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } /** * @notice Swap ETH for tokens and pay amount of ETH input as tip * @param factory Uniswap V2-compliant Factory contract * @param trade Trade details * @param tipAmount amount of ETH to pay as tip */ function swapETHForExactTokensAndTipAmount( address factory, Trade calldata trade, uint256 tipAmount ) external payable { tip(tipAmount); require(trade.path[0] == WETH, 'ArchRouter: INVALID_PATH'); uint[] memory amounts = RouteLib.getAmountsIn(factory, trade.amountOut, trade.path); uint256 inputAmount = msg.value - tipAmount; require(amounts[0] <= inputAmount, 'ArchRouter: EXCESSIVE_INPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(RouteLib.pairFor(factory, trade.path[0], trade.path[1]), amounts[0])); _exactOutputSwap(factory, amounts, trade.path, trade.to); if (inputAmount > amounts[0]) { TransferHelper.safeTransferETH(msg.sender, inputAmount - amounts[0]); } } /** * @notice Swap tokens for tokens and pay ETH amount as tip * @param factory Uniswap V2-compliant Factory contract * @param trade Trade details */ function swapExactTokensForTokensAndTipAmount( address factory, Trade calldata trade ) external payable { tip(msg.value); _swapExactTokensForTokens(factory, trade); } /** * @notice Swap tokens for tokens and pay % of tokens as tip * @param factory Uniswap V2-compliant Factory contract * @param trade Trade details * @param pathToEth Path to ETH for tip * @param tipPct % of resulting tokens to pay as tip */ function swapExactTokensForTokensAndTipPct( address factory, Trade calldata trade, address[] calldata pathToEth, uint32 tipPct ) external payable { _swapExactTokensForTokens(factory, trade); IERC20Extended toToken = IERC20Extended(pathToEth[0]); uint256 contractTokenBalance = toToken.balanceOf(address(this)); uint256 tipAmount = (contractTokenBalance * tipPct) / 1000000; TransferHelper.safeTransfer(pathToEth[0], trade.to, contractTokenBalance - tipAmount); _tipWithTokens(factory, pathToEth); } /** * @notice Swap tokens for tokens and pay ETH amount as tip * @param factory Uniswap V2-compliant Factory contract * @param trade Trade details */ function swapTokensForExactTokensAndTipAmount( address factory, Trade calldata trade ) external payable { tip(msg.value); _swapTokensForExactTokens(factory, trade); } /** * @notice Swap tokens for tokens and pay % of tokens as tip * @param factory Uniswap V2-compliant Factory contract * @param trade Trade details * @param pathToEth Path to ETH for tip * @param tipPct % of resulting tokens to pay as tip */ function swapTokensForExactTokensAndTipPct( address factory, Trade calldata trade, address[] calldata pathToEth, uint32 tipPct ) external payable { _swapTokensForExactTokens(factory, trade); IERC20Extended toToken = IERC20Extended(pathToEth[0]); uint256 contractTokenBalance = toToken.balanceOf(address(this)); uint256 tipAmount = (contractTokenBalance * tipPct) / 1000000; TransferHelper.safeTransfer(pathToEth[0], trade.to, contractTokenBalance - tipAmount); _tipWithTokens(factory, pathToEth); } /** * @notice Returns the pool for the given token pair and fee. The pool contract may or may not exist. * @param tokenA First token * @param tokenB Second token * @param fee Pool fee * @return Uniswap V3 Pool */ function getPool( address tokenA, address tokenB, uint24 fee ) private view returns (IUniswapV3Pool) { return IUniswapV3Pool(RouteLib.computeAddress(uniV3Factory, RouteLib.getPoolKey(tokenA, tokenB, fee))); } /** * @notice Uniswap V3 Callback function that validates and pays for trade * @dev Called by Uni V3 pool contract * @param amount0Delta Delta for token 0 * @param amount1Delta Delta for token 1 * @param _data Swap callback data */ function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata _data ) external override { require(amount0Delta > 0 || amount1Delta > 0); // swaps entirely within 0-liquidity regions are not supported SwapCallbackData memory data = abi.decode(_data, (SwapCallbackData)); (address tokenIn, address tokenOut, uint24 fee) = data.path.decodeFirstPool(); CallbackValidation.verifyCallback(uniV3Factory, tokenIn, tokenOut, fee); (bool isExactInput, uint256 amountToPay) = amount0Delta > 0 ? (tokenIn < tokenOut, uint256(amount0Delta)) : (tokenOut < tokenIn, uint256(amount1Delta)); if (isExactInput) { pay(tokenIn, data.payer, msg.sender, amountToPay); } else { // either initiate the next swap or pay if (data.path.hasMultiplePools()) { data.path = data.path.skipToken(); _exactOutputInternal(amountToPay, msg.sender, 0, data); } else { amountInCached = amountToPay; tokenIn = tokenOut; // swap in/out because exact output swaps are reversed pay(tokenIn, data.payer, msg.sender, amountToPay); } } } /// @inheritdoc IUniV3Router function exactInputSingle(ExactInputSingleParams calldata params) public payable override returns (uint256 amountOut) { amountOut = _exactInputInternal( params.amountIn, params.recipient, params.sqrtPriceLimitX96, SwapCallbackData({path: abi.encodePacked(params.tokenIn, params.fee, params.tokenOut), payer: msg.sender}) ); require(amountOut >= params.amountOutMinimum, 'Too little received'); } /** * @notice Performs a single exact input Uni V3 swap and tips an amount of ETH * @param params Swap params * @param tipAmount Tip amount */ function exactInputSingleAndTipAmount(ExactInputSingleParams calldata params, uint256 tipAmount) external payable returns (uint256 amountOut) { amountOut = exactInputSingle(params); tip(tipAmount); } /// @inheritdoc IUniV3Router function exactInput(ExactInputParams memory params) public payable override returns (uint256 amountOut) { address payer = msg.sender; // msg.sender pays for the first hop while (true) { bool hasMultiplePools = params.path.hasMultiplePools(); // the outputs of prior swaps become the inputs to subsequent ones params.amountIn = _exactInputInternal( params.amountIn, hasMultiplePools ? address(this) : params.recipient, // for intermediate swaps, this contract custodies 0, SwapCallbackData({ path: params.path.getFirstPool(), // only the first pool in the path is necessary payer: payer }) ); // decide whether to continue or terminate if (hasMultiplePools) { payer = address(this); // at this point, the caller has paid params.path = params.path.skipToken(); } else { amountOut = params.amountIn; break; } } require(amountOut >= params.amountOutMinimum, 'Too little received'); } /** * @notice Performs multiple exact input Uni V3 swaps and tips an amount of ETH * @param params Swap params * @param tipAmount Tip amount */ function exactInputAndTipAmount(ExactInputParams calldata params, uint256 tipAmount) external payable returns (uint256 amountOut) { amountOut = exactInput(params); tip(tipAmount); } /// @inheritdoc IUniV3Router function exactOutputSingle(ExactOutputSingleParams calldata params) public payable override returns (uint256 amountIn) { // avoid an SLOAD by using the swap return data amountIn = _exactOutputInternal( params.amountOut, params.recipient, params.sqrtPriceLimitX96, SwapCallbackData({path: abi.encodePacked(params.tokenOut, params.fee, params.tokenIn), payer: msg.sender}) ); require(amountIn <= params.amountInMaximum, 'Too much requested'); // has to be reset even though we don't use it in the single hop case amountInCached = DEFAULT_AMOUNT_IN_CACHED; } /** * @notice Performs an exact output Uni V3 swap and tips an amount of ETH * @param params Swap params * @param tipAmount Tip amount */ function exactOutputSingleAndTipAmount(ExactOutputSingleParams calldata params, uint256 tipAmount) external payable returns (uint256 amountIn) { amountIn = exactOutputSingle(params); tip(tipAmount); } /// @inheritdoc IUniV3Router function exactOutput(ExactOutputParams calldata params) public payable override returns (uint256 amountIn) { // it's okay that the payer is fixed to msg.sender here, as they're only paying for the "final" exact output // swap, which happens first, and subsequent swaps are paid for within nested callback frames _exactOutputInternal( params.amountOut, params.recipient, 0, SwapCallbackData({path: params.path, payer: msg.sender}) ); amountIn = amountInCached; require(amountIn <= params.amountInMaximum, 'Too much requested'); amountInCached = DEFAULT_AMOUNT_IN_CACHED; } /** * @notice Performs multiple exact output Uni V3 swaps and tips an amount of ETH * @param params Swap params * @param tipAmount Tip amount */ function exactOutputAndTipAmount(ExactOutputParams calldata params, uint256 tipAmount) external payable returns (uint256 amountIn) { amountIn = exactOutput(params); tip(tipAmount); } /** * @notice Performs a single exact input Uni V3 swap * @param amountIn Amount of input token * @param recipient Recipient of swap result * @param sqrtPriceLimitX96 Price limit * @param data Swap callback data */ function _exactInputInternal( uint256 amountIn, address recipient, uint160 sqrtPriceLimitX96, SwapCallbackData memory data ) private returns (uint256 amountOut) { // allow swapping to the router address with address 0 if (recipient == address(0)) recipient = address(this); (address tokenIn, address tokenOut, uint24 fee) = data.path.decodeFirstPool(); bool zeroForOne = tokenIn < tokenOut; (int256 amount0, int256 amount1) = getPool(tokenIn, tokenOut, fee).swap( recipient, zeroForOne, amountIn.toInt256(), sqrtPriceLimitX96 == 0 ? (zeroForOne ? MIN_SQRT_RATIO + 1 : MAX_SQRT_RATIO - 1) : sqrtPriceLimitX96, abi.encode(data) ); return uint256(-(zeroForOne ? amount1 : amount0)); } /** * @notice Performs a single exact output Uni V3 swap * @param amountOut Amount of output token * @param recipient Recipient of swap result * @param sqrtPriceLimitX96 Price limit * @param data Swap callback data */ function _exactOutputInternal( uint256 amountOut, address recipient, uint160 sqrtPriceLimitX96, SwapCallbackData memory data ) private returns (uint256 amountIn) { // allow swapping to the router address with address 0 if (recipient == address(0)) recipient = address(this); (address tokenOut, address tokenIn, uint24 fee) = data.path.decodeFirstPool(); bool zeroForOne = tokenIn < tokenOut; (int256 amount0Delta, int256 amount1Delta) = getPool(tokenIn, tokenOut, fee).swap( recipient, zeroForOne, -amountOut.toInt256(), sqrtPriceLimitX96 == 0 ? (zeroForOne ? MIN_SQRT_RATIO + 1 : MAX_SQRT_RATIO - 1) : sqrtPriceLimitX96, abi.encode(data) ); uint256 amountOutReceived; (amountIn, amountOutReceived) = zeroForOne ? (uint256(amount0Delta), uint256(-amount1Delta)) : (uint256(amount1Delta), uint256(-amount0Delta)); // it's technically possible to not receive the full output amount, // so if no price limit has been specified, require this possibility away if (sqrtPriceLimitX96 == 0) require(amountOutReceived == amountOut); } /** * @notice Internal implementation of swap tokens for tokens * @param factory Uniswap V2-compliant Factory contract * @param trade Trade details */ function _swapExactTokensForTokens( address factory, Trade calldata trade ) internal { TransferHelper.safeTransferFrom( trade.path[0], msg.sender, RouteLib.pairFor(factory, trade.path[0], trade.path[1]), trade.amountIn ); uint balanceBefore = IERC20Extended(trade.path[trade.path.length - 1]).balanceOf(trade.to); _exactInputSwap(factory, trade.path, trade.to); require( IERC20Extended(trade.path[trade.path.length - 1]).balanceOf(trade.to) - balanceBefore >= trade.amountOut, 'ArchRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } /** * @notice Internal implementation of swap tokens for tokens * @param factory Uniswap V2-compliant Factory contract * @param trade Trade details */ function _swapTokensForExactTokens( address factory, Trade calldata trade ) internal { uint[] memory amounts = RouteLib.getAmountsIn(factory, trade.amountOut, trade.path); require(amounts[0] <= trade.amountIn, 'ArchRouter: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( trade.path[0], msg.sender, RouteLib.pairFor(factory, trade.path[0], trade.path[1]), amounts[0] ); _exactOutputSwap(factory, amounts, trade.path, trade.to); } /** * @notice Internal implementation of exact input Uni V2/Sushi swap * @param factory Uniswap V2-compliant Factory contract * @param path Trade path * @param _to Trade recipient */ function _exactInputSwap( address factory, address[] memory path, address _to ) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = RouteLib.sortTokens(input, output); IUniswapV2Pair pair = IUniswapV2Pair(RouteLib.pairFor(factory, input, output)); uint amountInput; uint amountOutput; { (uint reserve0, uint reserve1,) = pair.getReserves(); (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountInput = IERC20Extended(input).balanceOf(address(pair)) - reserveInput; amountOutput = RouteLib.getAmountOut(amountInput, reserveInput, reserveOutput); } (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0)); address to = i < path.length - 2 ? RouteLib.pairFor(factory, output, path[i + 2]) : _to; pair.swap(amount0Out, amount1Out, to, new bytes(0)); } } /** * @notice Internal implementation of exact output Uni V2/Sushi swap * @param factory Uniswap V2-compliant Factory contract * @param amounts Output amounts * @param path Trade path * @param _to Trade recipient */ function _exactOutputSwap( address factory, uint[] memory amounts, address[] memory path, address _to ) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = RouteLib.sortTokens(input, output); uint amountOut = amounts[i + 1]; (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? RouteLib.pairFor(factory, output, path[i + 2]) : _to; IUniswapV2Pair(RouteLib.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } /** * @notice Convert a token balance into ETH and then tip * @param factory Factory address * @param path Path for swap */ function _tipWithTokens( address factory, address[] memory path ) internal { _exactInputSwap(factory, path, address(this)); uint256 amountOut = IWETH(WETH).balanceOf(address(this)); IWETH(WETH).withdraw(amountOut); tip(address(this).balance); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import './interfaces/IMulticall.sol'; /// @title Multicall /// @notice Enables calling multiple methods in a single call to the contract abstract contract Multicall is IMulticall { /// @inheritdoc IMulticall function multicall(bytes[] calldata data) external payable override returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); if (!success) { // Next 5 lines from https://ethereum.stackexchange.com/a/83577 if (result.length < 68) revert(); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } results[i] = result; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import './interfaces/IERC20Extended.sol'; import './interfaces/IPayments.sol'; import './interfaces/IWETH.sol'; import './lib/TransferHelper.sol'; import './ArchRouterImmutableState.sol'; abstract contract Payments is IPayments, ArchRouterImmutableState { receive() external payable { require(msg.sender == WETH, 'Not WETH'); } /// @inheritdoc IPayments function unwrapWETH(uint256 amountMinimum, address recipient) external payable override { uint256 balanceWETH = withdrawWETH(amountMinimum); TransferHelper.safeTransferETH(recipient, balanceWETH); } /// @inheritdoc IPayments function unwrapWETHAndTip(uint256 tipAmount, uint256 amountMinimum, address recipient) external payable override { uint256 balanceWETH = withdrawWETH(amountMinimum); tip(tipAmount); if(balanceWETH > tipAmount) { TransferHelper.safeTransferETH(recipient, balanceWETH - tipAmount); } } /// @inheritdoc IPayments function tip(uint256 tipAmount) public payable override { TransferHelper.safeTransferETH(block.coinbase, tipAmount); } /// @inheritdoc IPayments function sweepToken( address token, uint256 amountMinimum, address recipient ) external payable override { uint256 balanceToken = IERC20Extended(token).balanceOf(address(this)); require(balanceToken >= amountMinimum, 'Insufficient token'); if (balanceToken > 0) { TransferHelper.safeTransfer(token, recipient, balanceToken); } } /// @inheritdoc IPayments function refundETH() external payable override { if (address(this).balance > 0) TransferHelper.safeTransferETH(msg.sender, address(this).balance); } /// @param amountMinimum Min amount of WETH to withdraw function withdrawWETH(uint256 amountMinimum) public returns(uint256 balanceWETH){ balanceWETH = IWETH(WETH).balanceOf(address(this)); require(balanceWETH >= amountMinimum && balanceWETH > 0, 'Insufficient WETH'); IWETH(WETH).withdraw(balanceWETH); } /// @param token The token to pay /// @param payer The entity that must pay /// @param recipient The entity that will receive payment /// @param value The amount to pay function pay( address token, address payer, address recipient, uint256 value ) internal { if (token == WETH && address(this).balance >= value) { // pay with WETH IWETH(WETH).deposit{value: value}(); // wrap only what is needed to pay IWETH(WETH).transfer(recipient, value); } else if (payer == address(this)) { // pay with tokens already in the contract (for the exact input multihop case) TransferHelper.safeTransfer(token, recipient, value); } else { // pull payment TransferHelper.safeTransferFrom(token, payer, recipient, value); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import './interfaces/IERC20Extended.sol'; import './interfaces/IPaymentsWithFee.sol'; import './interfaces/IWETH.sol'; import './lib/TransferHelper.sol'; import './Payments.sol'; abstract contract PaymentsWithFee is Payments, IPaymentsWithFee { /// @inheritdoc IPaymentsWithFee function unwrapWETHWithFee( uint256 amountMinimum, address recipient, uint256 feeBips, address feeRecipient ) public payable override { require(feeBips > 0 && feeBips <= 100); uint256 balanceWETH = IWETH(WETH).balanceOf(address(this)); require(balanceWETH >= amountMinimum, 'Insufficient WETH'); if (balanceWETH > 0) { IWETH(WETH).withdraw(balanceWETH); uint256 feeAmount = (balanceWETH * feeBips) / 10_000; if (feeAmount > 0) TransferHelper.safeTransferETH(feeRecipient, feeAmount); TransferHelper.safeTransferETH(recipient, balanceWETH - feeAmount); } } /// @inheritdoc IPaymentsWithFee function sweepTokenWithFee( address token, uint256 amountMinimum, address recipient, uint256 feeBips, address feeRecipient ) public payable override { require(feeBips > 0 && feeBips <= 100); uint256 balanceToken = IERC20Extended(token).balanceOf(address(this)); require(balanceToken >= amountMinimum, 'Insufficient token'); if (balanceToken > 0) { uint256 feeAmount = (balanceToken * feeBips) / 10_000; if (feeAmount > 0) TransferHelper.safeTransfer(token, feeRecipient, feeAmount); TransferHelper.safeTransfer(token, recipient, balanceToken - feeAmount); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import './interfaces/IERC20Extended.sol'; import './interfaces/ISelfPermit.sol'; import './interfaces/IERC20PermitAllowed.sol'; /// @title Self Permit /// @notice Functionality to call permit on any EIP-2612-compliant token for use in the route /// @dev These functions are expected to be embedded in multicalls to allow EOAs to approve a contract and call a function /// that requires an approval in a single transaction. abstract contract SelfPermit is ISelfPermit { /// @inheritdoc ISelfPermit function selfPermit( address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public payable override { IERC20Extended(token).permit(msg.sender, address(this), value, deadline, v, r, s); } /// @inheritdoc ISelfPermit function selfPermitIfNecessary( address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable override { if (IERC20Extended(token).allowance(msg.sender, address(this)) < value) selfPermit(token, value, deadline, v, r, s); } /// @inheritdoc ISelfPermit function selfPermitAllowed( address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public payable override { IERC20PermitAllowed(token).permit(msg.sender, address(this), nonce, expiry, true, v, r, s); } /// @inheritdoc ISelfPermit function selfPermitAllowedIfNecessary( address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external payable override { if (IERC20Extended(token).allowance(msg.sender, address(this)) < type(uint256).max) selfPermitAllowed(token, nonce, expiry, v, r, s); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; /// @title Immutable state /// @notice Functions that return immutable state of the router interface IArchRouterImmutableState { /// @return Returns the address of the Uniswap V3 factory function uniV3Factory() external view returns (address); /// @return Returns the address of WETH function WETH() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IERC20Extended { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function version() external view returns (uint8); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function transferWithAuthorization(address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s) external; function receiveWithAuthorization(address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s) external; function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; function nonces(address) external view returns (uint); function getDomainSeparator() external view returns (bytes32); function DOMAIN_SEPARATOR() external view returns (bytes32); function DOMAIN_TYPEHASH() external view returns (bytes32); function VERSION_HASH() external view returns (bytes32); function PERMIT_TYPEHASH() external view returns (bytes32); function TRANSFER_WITH_AUTHORIZATION_TYPEHASH() external view returns (bytes32); function RECEIVE_WITH_AUTHORIZATION_TYPEHASH() external view returns (bytes32); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; /// @title Interface for permit /// @notice Interface used by DAI/CHAI for permit interface IERC20PermitAllowed { /// @notice Approve the spender to spend some tokens via the holder signature /// @dev This is the permit interface used by DAI and CHAI /// @param holder The address of the token holder, the token owner /// @param spender The address of the token spender /// @param nonce The holder's nonce, increases at each call to permit /// @param expiry The timestamp at which the permit is no longer valid /// @param allowed Boolean that sets approval amount, true for type(uint256).max and false for 0 /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function permit( address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; /// @title Multicall interface /// @notice Enables calling multiple methods in a single call to the contract interface IMulticall { /// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed /// @dev The `msg.value` should not be trusted for any method callable from multicall. /// @param data The encoded function data for each of the calls to make to this contract /// @return results The results from each of the calls passed in via data function multicall(bytes[] calldata data) external payable returns (bytes[] memory results); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; /// @title Periphery Payments /// @notice Functions to ease deposits and withdrawals of ETH interface IPayments { /// @notice Unwraps the contract's WETH balance and sends it to recipient as ETH. /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH from users. /// @param amountMinimum The minimum amount of WETH to unwrap /// @param recipient The address receiving ETH function unwrapWETH(uint256 amountMinimum, address recipient) external payable; /// @notice Refunds any ETH balance held by this contract to the `msg.sender` /// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps /// that use ether for the input amount function refundETH() external payable; /// @notice Transfers the full amount of a token held by this contract to recipient /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users /// @param token The contract address of the token which will be transferred to `recipient` /// @param amountMinimum The minimum amount of token required for a transfer /// @param recipient The destination address of the token function sweepToken( address token, uint256 amountMinimum, address recipient ) external payable; /// @notice Tips miners using the WETH balance in the contract and then transfers the remainder to recipient /// @dev The recipientMinimum parameter prevents malicious contracts from stealing the ETH from users /// @param tipAmount Tip amount /// @param amountMinimum The minimum amount of WETH to withdraw /// @param recipient The destination address of the ETH left after tipping function unwrapWETHAndTip( uint256 tipAmount, uint256 amountMinimum, address recipient ) external payable; /// @notice Tips miners using the ETH balance in the contract + msg.value /// @param tipAmount Tip amount function tip( uint256 tipAmount ) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import './IPayments.sol'; /// @title Periphery Payments /// @notice Functions to ease deposits and withdrawals of ETH interface IPaymentsWithFee is IPayments { /// @notice Unwraps the contract's WETH balance and sends it to recipient as ETH, with a percentage between /// 0 (exclusive), and 1 (inclusive) going to feeRecipient /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH from users. function unwrapWETHWithFee( uint256 amountMinimum, address recipient, uint256 feeBips, address feeRecipient ) external payable; /// @notice Transfers the full amount of a token held by this contract to recipient, with a percentage between /// 0 (exclusive) and 1 (inclusive) going to feeRecipient /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users function sweepTokenWithFee( address token, uint256 amountMinimum, address recipient, uint256 feeBips, address feeRecipient ) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; /// @title Self Permit /// @notice Functionality to call permit on any EIP-2612-compliant token for use in the route interface ISelfPermit { /// @notice Permits this contract to spend a given token from `msg.sender` /// @dev The `owner` is always msg.sender and the `spender` is always address(this). /// @param token The address of the token spent /// @param value The amount that can be spent of token /// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function selfPermit( address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable; /// @notice Permits this contract to spend a given token from `msg.sender` /// @dev The `owner` is always msg.sender and the `spender` is always address(this). /// Can be used instead of #selfPermit to prevent calls from failing due to a frontrun of a call to #selfPermit /// @param token The address of the token spent /// @param value The amount that can be spent of token /// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function selfPermitIfNecessary( address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable; /// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter /// @dev The `owner` is always msg.sender and the `spender` is always address(this) /// @param token The address of the token spent /// @param nonce The current nonce of the owner /// @param expiry The timestamp at which the permit is no longer valid /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function selfPermitAllowed( address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external payable; /// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter /// @dev The `owner` is always msg.sender and the `spender` is always address(this) /// Can be used instead of #selfPermitAllowed to prevent calls from failing due to a frontrun of a call to #selfPermitAllowed. /// @param token The address of the token spent /// @param nonce The current nonce of the owner /// @param expiry The timestamp at which the permit is no longer valid /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function selfPermitAllowedIfNecessary( address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import './IUniswapV3SwapCallback.sol'; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface IUniV3Router is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IUniswapV2Pair { function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool { /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IWETH { function deposit() external payable; function withdraw(uint256) external; function transfer(address recipient, uint256 amount) external returns (bool); function balanceOf(address account) external view returns (uint256); } // SPDX-License-Identifier: GPL-2.0-or-later /* * @title Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ pragma solidity ^0.8.0; library BytesLib { function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, 'slice_overflow'); require(_start + _length >= _start, 'slice_overflow'); require(_bytes.length >= _start + _length, 'slice_outOfBounds'); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. 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) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) { require(_start + 20 >= _start, 'toAddress_overflow'); require(_bytes.length >= _start + 20, 'toAddress_outOfBounds'); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) { require(_start + 3 >= _start, 'toUint24_overflow'); require(_bytes.length >= _start + 3, 'toUint24_outOfBounds'); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import '../interfaces/IUniswapV3Pool.sol'; import './RouteLib.sol'; /// @notice Provides validation for callbacks from Uniswap V3 Pools library CallbackValidation { /// @notice Returns the address of a valid Uniswap V3 Pool /// @param factory The contract address of the Uniswap V3 factory /// @param tokenA The contract address of either token0 or token1 /// @param tokenB The contract address of the other token /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @return pool The V3 pool contract address function verifyCallback( address factory, address tokenA, address tokenB, uint24 fee ) internal view returns (IUniswapV3Pool pool) { return verifyCallback(factory, RouteLib.getPoolKey(tokenA, tokenB, fee)); } /// @notice Returns the address of a valid Uniswap V3 Pool /// @param factory The contract address of the Uniswap V3 factory /// @param poolKey The identifying key of the V3 pool /// @return pool The V3 pool contract address function verifyCallback(address factory, RouteLib.PoolKey memory poolKey) internal view returns (IUniswapV3Pool pool) { pool = IUniswapV3Pool(RouteLib.computeAddress(factory, poolKey)); require(msg.sender == address(pool)); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import './BytesLib.sol'; /// @title Functions for manipulating path data for multihop swaps library Path { using BytesLib for bytes; /// @dev The length of the bytes encoded address uint256 private constant ADDR_SIZE = 20; /// @dev The length of the bytes encoded fee uint256 private constant FEE_SIZE = 3; /// @dev The offset of a single token address and pool fee uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE; /// @dev The offset of an encoded pool key uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE; /// @dev The minimum length of an encoding that contains 2 or more pools uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET; /// @notice Returns true iff the path contains two or more pools /// @param path The encoded swap path /// @return True if path contains two or more pools, otherwise false function hasMultiplePools(bytes memory path) internal pure returns (bool) { return path.length >= MULTIPLE_POOLS_MIN_LENGTH; } /// @notice Decodes the first pool in path /// @param path The bytes encoded swap path /// @return tokenA The first token of the given pool /// @return tokenB The second token of the given pool /// @return fee The fee level of the pool function decodeFirstPool(bytes memory path) internal pure returns ( address tokenA, address tokenB, uint24 fee ) { tokenA = path.toAddress(0); fee = path.toUint24(ADDR_SIZE); tokenB = path.toAddress(NEXT_OFFSET); } /// @notice Gets the segment corresponding to the first pool in the path /// @param path The bytes encoded swap path /// @return The segment containing all data necessary to target the first pool in the path function getFirstPool(bytes memory path) internal pure returns (bytes memory) { return path.slice(0, POP_OFFSET); } /// @notice Skips a token + fee element from the buffer and returns the remainder /// @param path The swap path /// @return The remaining token + fee elements in the path function skipToken(bytes memory path) internal pure returns (bytes memory) { return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '../interfaces/IUniswapV2Pair.sol'; library RouteLib { address internal constant _SUSHI_FACTORY = 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac; bytes32 internal constant _SUSHI_ROUTER_INIT_HASH = 0xe18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303; bytes32 internal constant _UNI_V2_ROUTER_INIT_HASH = 0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f; bytes32 internal constant _UNI_V3_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); } // 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, 'RouteLib: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'RouteLib: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); bytes32 initHash = factory == _SUSHI_FACTORY ? _SUSHI_ROUTER_INIT_HASH : _UNI_V2_ROUTER_INIT_HASH; pair = address( uint160( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), initHash // init code hash ) ) ) ) ); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint160( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), _UNI_V3_INIT_CODE_HASH ) ) ) ) ); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'RouteLib: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'RouteLib: INSUFFICIENT_LIQUIDITY'); amountB = amountA * (reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'RouteLib: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'RouteLib: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn * 997; uint numerator = amountInWithFee * reserveOut; uint denominator = reserveIn * 1000 + amountInWithFee; amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'RouteLib: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'RouteLib: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn * amountOut * 1000; uint denominator = (reserveOut - amountOut) * 997; amountIn = (numerator / denominator) + 1; } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'RouteLib: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'RouteLib: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Safe casting methods /// @notice Contains methods for safely casting between types library SafeCast { /// @notice Cast a uint256 to a uint160, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint160 function toUint160(uint256 y) internal pure returns (uint160 z) { require((z = uint160(y)) == y); } /// @notice Cast a int256 to a int128, revert on overflow or underflow /// @param y The int256 to be downcasted /// @return z The downcasted integer, now type int128 function toInt128(int256 y) internal pure returns (int128 z) { require((z = int128(y)) == y); } /// @notice Cast a uint256 to a int256, revert on overflow /// @param y The uint256 to be casted /// @return z The casted integer, now type int256 function toInt256(uint256 y) internal pure returns (int256 z) { require(y < 2**255); z = int256(y); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeApprove: approve failed' ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeTransfer: transfer failed' ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } }
@inheritdoc IArchRouterImmutableState @inheritdoc IArchRouterImmutableState
constructor(address _uniV3Factory, address _WETH) { uniV3Factory = _uniV3Factory; WETH = _WETH; }
11,683,047
[ 1, 36, 10093, 467, 12269, 8259, 16014, 1119, 632, 10093, 467, 12269, 8259, 16014, 1119, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 12, 2867, 389, 318, 77, 58, 23, 1733, 16, 1758, 389, 59, 1584, 44, 13, 288, 203, 3639, 7738, 58, 23, 1733, 273, 389, 318, 77, 58, 23, 1733, 31, 203, 3639, 678, 1584, 44, 273, 389, 59, 1584, 44, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; pragma experimental ABIEncoderV2; import "../math/SafeMath.sol"; import "./HasSecondarySaleFees.sol"; import "./HasContractURI.sol"; import "./ERC1155MetadataURI.sol"; import "./ERC1155.sol"; import "../utils/Ownable.sol"; contract ERC1155Base is HasSecondarySaleFees, Ownable, ERC1155MetadataURI, HasContractURI, ERC1155 { using SafeMath for uint256; struct Fee { address payable recipient; uint256 value; } // id => creator mapping (uint256 => address) public creators; // id => fees mapping (uint256 => Fee[]) public fees; constructor(string memory contractURI, string memory tokenURIPrefix) HasContractURI(contractURI) ERC1155MetadataURI(tokenURIPrefix) { } function getFeeRecipients(uint256 id) public view override returns (address payable[] memory) { Fee[] memory _fees = fees[id]; address payable[] memory result = new address payable[](_fees.length); for (uint i = 0; i < _fees.length; i++) { result[i] = _fees[i].recipient; } return result; } function getFeeBps(uint256 id) public view override returns (uint[] memory) { Fee[] memory _fees = fees[id]; uint[] memory result = new uint[](_fees.length); for (uint i = 0; i < _fees.length; i++) { result[i] = _fees[i].value; } return result; } // Creates a new token type and assings _initialSupply to minter function _mint(uint256 _id, Fee[] memory _fees, uint256 _supply, string memory _uri) internal { require(creators[_id] == address(0x0), "Token is already minted"); require(_supply != 0, "Supply be positive"); require(bytes(_uri).length > 0, "uri be set"); creators[_id] = msg.sender; address[] memory recipients = new address[](_fees.length); uint[] memory bps = new uint[](_fees.length); for (uint i = 0; i < _fees.length; i++) { require(_fees[i].recipient != address(0x0), "Recipient be present"); require(_fees[i].value != 0, "Fee value be positive"); fees[_id].push(_fees[i]); recipients[i] = _fees[i].recipient; bps[i] = _fees[i].value; } if (_fees.length > 0) { emit SecondarySaleFees(_id, recipients, bps); } balances[_id][msg.sender] = _supply; _setTokenURI(_id, _uri); // Transfer event with mint semantic emit TransferSingle(msg.sender, address(0x0), msg.sender, _id, _supply); emit URI(_uri, _id); } function burn(address _owner, uint256 _id, uint256 _value) external { require(_owner == msg.sender || operatorApproval[_owner][msg.sender] == true, "Need operator approval for 3rd party burns."); // SafeMath will throw with insuficient funds _owner // or if _id is not valid (balance will be 0) balances[_id][_owner] = balances[_id][_owner].sub(_value); // MUST emit event emit TransferSingle(msg.sender, _owner, address(0x0), _id, _value); } /** * @dev Internal function to set the token URI for a given token. * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string memory uri) internal override{ require(creators[tokenId] != address(0x0), "_setTokenURI: Token exist"); super._setTokenURI(tokenId, uri); } function setTokenURIPrefix(string memory tokenURIPrefix) public onlyOwner { _setTokenURIPrefix(tokenURIPrefix); } function setContractURI(string memory contractURI) public onlyOwner { _setContractURI(contractURI); } }
* @dev Internal function to set the token URI for a given token. Reverts if the token ID does not exist. @param tokenId uint256 ID of the token to set its URI @param uri string URI to assign/
function _setTokenURI(uint256 tokenId, string memory uri) internal override{ require(creators[tokenId] != address(0x0), "_setTokenURI: Token exist"); super._setTokenURI(tokenId, uri); }
13,000,540
[ 1, 3061, 445, 358, 444, 326, 1147, 3699, 364, 279, 864, 1147, 18, 868, 31537, 309, 326, 1147, 1599, 1552, 486, 1005, 18, 225, 1147, 548, 2254, 5034, 1599, 434, 326, 1147, 358, 444, 2097, 3699, 225, 2003, 533, 3699, 358, 2683, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 542, 1345, 3098, 12, 11890, 5034, 1147, 548, 16, 533, 3778, 2003, 13, 2713, 3849, 95, 203, 3639, 2583, 12, 1793, 3062, 63, 2316, 548, 65, 480, 1758, 12, 20, 92, 20, 3631, 4192, 542, 1345, 3098, 30, 3155, 225, 1005, 8863, 203, 3639, 2240, 6315, 542, 1345, 3098, 12, 2316, 548, 16, 2003, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x609eee76d7ddd7880ff8349736f1329bffdcecc7 //Contract name: SingularDTVLaunch //Balance: 0 Ether //Verification Date: 2/26/2018 //Transacion Count: 12 // CODE STARTS HERE pragma solidity ^0.4.15; contract Token { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract AbstractSingularDTVToken is Token { } /// @title Token Creation contract - Implements token creation functionality. /// @author Stefan George - <[email protected]> /// @author Razvan Pop - <[email protected]> /// @author Milad Mostavi - <[email protected]> contract SingularDTVLaunch { string public version = "0.1.0"; event Contributed(address indexed contributor, uint contribution, uint tokens); /* * External contracts */ AbstractSingularDTVToken public singularDTVToken; address public workshop; address public SingularDTVWorkshop = 0xc78310231aA53bD3D0FEA2F8c705C67730929D8f; uint public SingularDTVWorkshopFee; /* * Constants */ uint public CAP; // in wei scale of tokens uint public DURATION; // in seconds uint public TOKEN_TARGET; // Goal threshold in wei scale of tokens /* * Enums */ enum Stages { Deployed, GoingAndGoalNotReached, EndedAndGoalNotReached, GoingAndGoalReached, EndedAndGoalReached } /* * Storage */ address public owner; uint public startDate; uint public fundBalance; uint public valuePerToken; //in wei uint public tokensSent; // participant address => value in Wei mapping (address => uint) public contributions; // participant address => token amount in wei scale mapping (address => uint) public sentTokens; // Initialize stage Stages public stage = Stages.Deployed; modifier onlyOwner() { // Only owner is allowed to do this action. if (msg.sender != owner) { revert(); } _; } modifier atStage(Stages _stage) { if (stage != _stage) { revert(); } _; } modifier atStageOR(Stages _stage1, Stages _stage2) { if (stage != _stage1 && stage != _stage2) { revert(); } _; } modifier timedTransitions() { uint timeElapsed = now - startDate; if (timeElapsed >= DURATION) { if (stage == Stages.GoingAndGoalNotReached) { stage = Stages.EndedAndGoalNotReached; } else if (stage == Stages.GoingAndGoalReached) { stage = Stages.EndedAndGoalReached; } } _; } /* * Contract functions */ /// dev Validates invariants. function checkInvariants() constant internal { if (fundBalance > this.balance) { revert(); } } /// @dev Can be triggered if an invariant fails. function emergencyCall() public returns (bool) { if (fundBalance > this.balance) { if (this.balance > 0 && !SingularDTVWorkshop.send(this.balance)) { revert(); } return true; } return false; } /// @dev Allows user to create tokens if token creation is still going and cap not reached. Returns token count. function fund() public timedTransitions atStageOR(Stages.GoingAndGoalNotReached, Stages.GoingAndGoalReached) payable returns (uint) { uint tokenCount = (msg.value * (10**18)) / valuePerToken; // Token count in wei is rounded down. Sent ETH should be multiples of valuePerToken. require(tokenCount > 0); if (tokensSent + tokenCount > CAP) { // User wants to create more tokens than available. Set tokens to possible maximum. tokenCount = CAP - tokensSent; } tokensSent += tokenCount; uint contribution = (tokenCount * valuePerToken) / (10**18); // Ether spent by user. // Send change back to user. if (msg.value > contribution && !msg.sender.send(msg.value - contribution)) { revert(); } // Update fund and user's balance and total supply of tokens. fundBalance += contribution; contributions[msg.sender] += contribution; sentTokens[msg.sender] += tokenCount; if (!singularDTVToken.transfer(msg.sender, tokenCount)) { // Tokens could not be issued. revert(); } // Update stage if (stage == Stages.GoingAndGoalNotReached) { if (tokensSent >= TOKEN_TARGET) { stage = Stages.GoingAndGoalReached; } } // not an else clause for the edge case that the CAP and TOKEN_TARGET are reached in one call if (stage == Stages.GoingAndGoalReached) { if (tokensSent == CAP) { stage = Stages.EndedAndGoalReached; } } checkInvariants(); Contributed(msg.sender, contribution, tokenCount); return tokenCount; } /// @dev Allows user to withdraw ETH if token creation period ended and target was not reached. Returns contribution. function withdrawContribution() public timedTransitions atStage(Stages.EndedAndGoalNotReached) returns (uint) { // We get back the tokens from the contributor before giving back his contribution uint tokensReceived = sentTokens[msg.sender]; sentTokens[msg.sender] = 0; if (!singularDTVToken.transferFrom(msg.sender, owner, tokensReceived)) { revert(); } // Update fund's and user's balance and total supply of tokens. uint contribution = contributions[msg.sender]; contributions[msg.sender] = 0; fundBalance -= contribution; // Send ETH back to user. if (contribution > 0) { msg.sender.transfer(contribution); } checkInvariants(); return contribution; } /// @dev Withdraws ETH to workshop address. Returns success. function withdrawForWorkshop() public timedTransitions atStage(Stages.EndedAndGoalReached) returns (bool) { uint value = fundBalance; fundBalance = 0; require(value > 0); uint networkFee = value * SingularDTVWorkshopFee / 100; workshop.transfer(value - networkFee); SingularDTVWorkshop.transfer(networkFee); uint remainingTokens = CAP - tokensSent; if (remainingTokens > 0 && !singularDTVToken.transfer(owner, remainingTokens)) { revert(); } checkInvariants(); return true; } /// @dev Allows owner to get back unsent tokens in case of launch failure (EndedAndGoalNotReached). function withdrawUnsentTokensForOwner() public timedTransitions atStage(Stages.EndedAndGoalNotReached) returns (uint) { uint remainingTokens = CAP - tokensSent; if (remainingTokens > 0 && !singularDTVToken.transfer(owner, remainingTokens)) { revert(); } checkInvariants(); return remainingTokens; } /// @dev Sets token value in Wei. /// @param valueInWei New value. function changeValuePerToken(uint valueInWei) public onlyOwner atStage(Stages.Deployed) returns (bool) { valuePerToken = valueInWei; return true; } // updateStage allows calls to receive correct stage. It can be used for transactions but is not part of the regular token creation routine. // It is not marked as constant because timedTransitions modifier is altering state and constant is not yet enforced by solc. /// @dev returns correct stage, even if a function with timedTransitions modifier has not yet been called successfully. function updateStage() public timedTransitions returns (Stages) { return stage; } function start() public onlyOwner atStage(Stages.Deployed) returns (uint) { if (!singularDTVToken.transferFrom(msg.sender, this, CAP)) { revert(); } startDate = now; stage = Stages.GoingAndGoalNotReached; checkInvariants(); return startDate; } /// @dev Contract constructor function sets owner and start date. function SingularDTVLaunch( address singularDTVTokenAddress, address _workshop, address _owner, uint _total, uint _unit_price, uint _duration, uint _threshold, uint _singulardtvwoskhop_fee ) { singularDTVToken = AbstractSingularDTVToken(singularDTVTokenAddress); workshop = _workshop; owner = _owner; CAP = _total; // Total number of tokens (wei scale) valuePerToken = _unit_price; // wei per token DURATION = _duration; // in seconds TOKEN_TARGET = _threshold; // Goal threshold SingularDTVWorkshopFee = _singulardtvwoskhop_fee; } /// @dev Fallback function acts as fund() when stage GoingAndGoalNotReached /// or GoingAndGoalReached. And act as withdrawFunding() when EndedAndGoalNotReached. /// otherwise throw. function () public payable { if (stage == Stages.GoingAndGoalNotReached || stage == Stages.GoingAndGoalReached) fund(); else if (stage == Stages.EndedAndGoalNotReached) withdrawContribution(); else revert(); } }
@dev Allows user to create tokens if token creation is still going and cap not reached. Returns token count. User wants to create more tokens than available. Set tokens to possible maximum. Send change back to user. Tokens could not be issued. Update stage not an else clause for the edge case that the CAP and TOKEN_TARGET are reached in one call
function fund() public timedTransitions atStageOR(Stages.GoingAndGoalNotReached, Stages.GoingAndGoalReached) payable returns (uint) { require(tokenCount > 0); if (tokensSent + tokenCount > CAP) { tokenCount = CAP - tokensSent; } tokensSent += tokenCount; if (msg.value > contribution && !msg.sender.send(msg.value - contribution)) { revert(); } contributions[msg.sender] += contribution; sentTokens[msg.sender] += tokenCount; if (!singularDTVToken.transfer(msg.sender, tokenCount)) { revert(); } if (stage == Stages.GoingAndGoalNotReached) { if (tokensSent >= TOKEN_TARGET) { stage = Stages.GoingAndGoalReached; } } if (stage == Stages.GoingAndGoalReached) { if (tokensSent == CAP) { stage = Stages.EndedAndGoalReached; } } checkInvariants(); Contributed(msg.sender, contribution, tokenCount); return tokenCount; }
1,804,739
[ 1, 19132, 729, 358, 752, 2430, 309, 1147, 6710, 353, 4859, 8554, 471, 3523, 486, 8675, 18, 2860, 1147, 1056, 18, 2177, 14805, 358, 752, 1898, 2430, 2353, 2319, 18, 1000, 2430, 358, 3323, 4207, 18, 2479, 2549, 1473, 358, 729, 18, 13899, 3377, 486, 506, 16865, 18, 2315, 6009, 486, 392, 469, 6591, 364, 326, 3591, 648, 716, 326, 29720, 471, 14275, 67, 16374, 854, 8675, 316, 1245, 745, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 284, 1074, 1435, 203, 3639, 1071, 203, 3639, 7491, 23299, 203, 3639, 622, 8755, 916, 12, 31359, 18, 5741, 310, 1876, 27716, 1248, 23646, 16, 934, 1023, 18, 5741, 310, 1876, 27716, 23646, 13, 203, 3639, 8843, 429, 203, 3639, 1135, 261, 11890, 13, 203, 565, 288, 203, 3639, 2583, 12, 2316, 1380, 405, 374, 1769, 203, 3639, 309, 261, 7860, 7828, 397, 1147, 1380, 405, 29720, 13, 288, 203, 5411, 1147, 1380, 273, 29720, 300, 2430, 7828, 31, 203, 3639, 289, 203, 3639, 2430, 7828, 1011, 1147, 1380, 31, 203, 203, 3639, 309, 261, 3576, 18, 1132, 405, 24880, 597, 401, 3576, 18, 15330, 18, 4661, 12, 3576, 18, 1132, 300, 24880, 3719, 288, 203, 5411, 15226, 5621, 203, 3639, 289, 203, 3639, 13608, 6170, 63, 3576, 18, 15330, 65, 1011, 24880, 31, 203, 3639, 3271, 5157, 63, 3576, 18, 15330, 65, 1011, 1147, 1380, 31, 203, 3639, 309, 16051, 17835, 9081, 58, 1345, 18, 13866, 12, 3576, 18, 15330, 16, 1147, 1380, 3719, 288, 203, 5411, 15226, 5621, 203, 3639, 289, 203, 3639, 309, 261, 12869, 422, 934, 1023, 18, 5741, 310, 1876, 27716, 1248, 23646, 13, 288, 203, 5411, 309, 261, 7860, 7828, 1545, 14275, 67, 16374, 13, 288, 203, 7734, 6009, 273, 934, 1023, 18, 5741, 310, 1876, 27716, 23646, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 309, 261, 12869, 422, 934, 1023, 18, 5741, 310, 1876, 27716, 23646, 13, 288, 203, 5411, 309, 261, 7860, 7828, 422, 29720, 13, 288, 203, 7734, 6009, 273, 934, 2 ]
/** *Submitted for verification at Etherscan.io on 2019-08-02 */ // File: contracts\open-zeppelin-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. * * > 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\open-zeppelin-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) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // File: contracts\open-zeppelin-contracts\token\ERC20\ERC20.sol pragma solidity ^0.5.0; /** * @dev Implementation of the `IERC20` interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using `_mint`. * For a generic mechanism see `ERC20Mintable`. * * *For a detailed writeup see our guide [How to implement supply * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).* * * 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 IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); 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 `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(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 returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(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 { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a `Transfer` event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a `Transfer` event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Destoys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See `_burn` and `_approve`. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } } // File: contracts\open-zeppelin-contracts\access\Roles.sol pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: contracts\open-zeppelin-contracts\access\roles\MinterRole.sol pragma solidity ^0.5.0; contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } // File: contracts\open-zeppelin-contracts\token\ERC20\ERC20Mintable.sol pragma solidity ^0.5.0; /** * @dev Extension of `ERC20` that adds a set of accounts with the `MinterRole`, * which have permission to mint (create) new tokens as they see fit. * * At construction, the deployer of the contract is the only minter. */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev See `ERC20._mint`. * * Requirements: * * - the caller must have the `MinterRole`. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } } // File: contracts\ERC20\TokenMintERC20MintableToken.sol pragma solidity ^0.5.0; /** * @title TokenMintERC20MintableToken * @author TokenMint (visit https://tokenmint.io) * * @dev Mintable ERC20 token with burning and optional functions implemented. * Any address with minter role can mint new tokens. * For full specification of ERC-20 standard see: * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md */ contract TokenMintERC20MintableToken is ERC20Mintable { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Constructor. * @param name name of the token * @param symbol symbol of the token, 3-4 chars is recommended * @param decimals number of decimal places of one token unit, 18 is widely used * @param initialSupply initial supply of tokens in lowest units (depending on decimals) * @param tokenOwnerAddress address that gets 100% of token supply */ constructor(string memory name, string memory symbol, uint8 decimals, uint256 initialSupply, address payable feeReceiver, address tokenOwnerAddress) public payable { _name = name; _symbol = symbol; _decimals = decimals; // set tokenOwnerAddress as owner of initial supply, more tokens can be minted later _mint(tokenOwnerAddress, initialSupply); // pay the service fee for contract deployment feeReceiver.transfer(msg.value); } /** * @dev transfers minter role from msg.sender to newMinter */ function transferMinterRole(address newMinter) public { addMinter(newMinter); renounceMinter(); } /** * @dev Burns a specific amount of tokens. * @param value The amount of lowest token units to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } // optional functions from ERC20 stardard /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } }
* @title TokenMintERC20MintableToken @dev Mintable ERC20 token with burning and optional functions implemented. Any address with minter role can mint new tokens. For full specification of ERC-20 standard see:/
contract TokenMintERC20MintableToken is ERC20Mintable { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals, uint256 initialSupply, address payable feeReceiver, address tokenOwnerAddress) public payable { _name = name; _symbol = symbol; _decimals = decimals; _mint(tokenOwnerAddress, initialSupply); feeReceiver.transfer(msg.value); } function transferMinterRole(address newMinter) public { addMinter(newMinter); renounceMinter(); } function burn(uint256 value) public { _burn(msg.sender, value); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } }
2,408,993
[ 1, 1345, 49, 474, 654, 39, 3462, 49, 474, 429, 1345, 225, 490, 474, 429, 4232, 39, 3462, 1147, 598, 18305, 310, 471, 3129, 4186, 8249, 18, 5502, 1758, 598, 1131, 387, 2478, 848, 312, 474, 394, 2430, 18, 2457, 1983, 7490, 434, 4232, 39, 17, 3462, 4529, 2621, 27824, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3155, 49, 474, 654, 39, 3462, 49, 474, 429, 1345, 353, 4232, 39, 3462, 49, 474, 429, 288, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2254, 28, 3238, 389, 31734, 31, 203, 203, 203, 565, 3885, 12, 1080, 3778, 508, 16, 533, 3778, 3273, 16, 2254, 28, 15105, 16, 2254, 5034, 2172, 3088, 1283, 16, 1758, 8843, 429, 14036, 12952, 16, 1758, 1147, 5541, 1887, 13, 1071, 8843, 429, 288, 203, 1377, 389, 529, 273, 508, 31, 203, 1377, 389, 7175, 273, 3273, 31, 203, 1377, 389, 31734, 273, 15105, 31, 203, 203, 1377, 389, 81, 474, 12, 2316, 5541, 1887, 16, 2172, 3088, 1283, 1769, 203, 203, 1377, 14036, 12952, 18, 13866, 12, 3576, 18, 1132, 1769, 203, 565, 289, 203, 203, 565, 445, 7412, 49, 2761, 2996, 12, 2867, 394, 49, 2761, 13, 1071, 288, 203, 1377, 527, 49, 2761, 12, 2704, 49, 2761, 1769, 203, 1377, 1654, 8386, 49, 2761, 5621, 203, 565, 289, 203, 203, 565, 445, 18305, 12, 11890, 5034, 460, 13, 1071, 288, 203, 1377, 389, 70, 321, 12, 3576, 18, 15330, 16, 460, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 508, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 1377, 327, 389, 529, 31, 203, 565, 289, 203, 203, 565, 445, 3273, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 1377, 327, 389, 7175, 31, 203, 565, 289, 203, 203, 565, 445, 15105, 1435, 1071, 1476, 1135, 261, 11890, 28, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0 < 0.8.0; contract Object { uint val; address delegate; constructor(address _delegate) { delegate = _delegate; } fallback() external { assembly { let target := sload(delegate.slot) calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), target, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 {revert(0, returndatasize())} default {return (0, returndatasize())} } } }
SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 < 0.8.0;
901,787
[ 1, 3118, 28826, 17, 13211, 17, 3004, 30, 490, 1285, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 683, 9454, 18035, 560, 1545, 20, 18, 27, 18, 20, 411, 374, 18, 28, 18, 20, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @title Whitelist * @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. * @dev This simplifies the implementation of "user permissions". */ contract Whitelist is Pausable { mapping(address => bool) public whitelist; event WhitelistedAddressAdded(address addr); event WhitelistedAddressRemoved(address addr); /** * @dev Throws if called by any account that's not whitelisted. */ modifier onlyWhitelisted() { require(whitelist[msg.sender]); _; } /** * @dev add an address to the whitelist * @param addr address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function addAddressToWhitelist(address addr) onlyOwner public returns(bool success) { if (!whitelist[addr]) { whitelist[addr] = true; emit WhitelistedAddressAdded(addr); success = true; } } /** * @dev add addresses to the whitelist * @param addrs addresses * @return true if at least one address was added to the whitelist, * false if all addresses were already in the whitelist */ function addAddressesToWhitelist(address[] addrs) onlyOwner public returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (addAddressToWhitelist(addrs[i])) { success = true; } } } /** * @dev remove an address from the whitelist * @param addr address * @return true if the address was removed from the whitelist, * false if the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address addr) onlyOwner public returns(bool success) { if (whitelist[addr]) { whitelist[addr] = false; emit WhitelistedAddressRemoved(addr); success = true; } } /** * @dev remove addresses from the whitelist * @param addrs addresses * @return true if at least one address was removed from the whitelist, * false if all addresses weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] addrs) onlyOwner public returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (removeAddressFromWhitelist(addrs[i])) { success = true; } } } } /** * @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 SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract Crowdsale is Whitelist{ using SafeMath for uint256; // The token being sold MiniMeToken public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei uint256 public rate = 6120; // Amount of tokens sold uint256 public tokensSold; //Star of the crowdsale uint256 startTime; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event buyx(address buyer, address contractAddr, uint256 amount); constructor(address _wallet, MiniMeToken _token, uint256 starttime) public{ require(_wallet != address(0)); require(_token != address(0)); wallet = _wallet; token = _token; startTime = starttime; } function setCrowdsale(address _wallet, MiniMeToken _token, uint256 starttime) public{ require(_wallet != address(0)); require(_token != address(0)); wallet = _wallet; token = _token; startTime = starttime; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * fallback function ***DO NOT OVERRIDE*** */ function () external whenNotPaused payable { emit buyx(msg.sender, this, _getTokenAmount(msg.value)); buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public whenNotPaused payable { if ((tokensSold > 20884500000000000000000000 ) && (tokensSold <= 30791250000000000000000000)) { rate = 5967; } else if ((tokensSold > 30791250000000000000000000) && (tokensSold <= 39270000000000000000000000)) { rate = 5865; } else if ((tokensSold > 39270000000000000000000000) && (tokensSold <= 46856250000000000000000000)) { rate = 5610; } else if ((tokensSold > 46856250000000000000000000) && (tokensSold <= 35700000000000000000000000)) { rate = 5355; } else if (tokensSold > 35700000000000000000000000) { rate = 5100; } uint256 weiAmount = msg.value; uint256 tokens = _getTokenAmount(weiAmount); tokensSold = tokensSold.add(tokens); _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.transfer(_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 returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } contract EmaCrowdSale is Crowdsale { uint256 public hardcap; uint256 public starttime; Crowdsale public csale; using SafeMath for uint256; constructor(address wallet, MiniMeToken token, uint256 startTime, uint256 cap) Crowdsale(wallet, token, starttime) public onlyOwner { hardcap = cap; starttime = startTime; setCrowdsale(wallet, token, startTime); } function tranferPresaleTokens(address investor, uint256 ammount)public onlyOwner{ tokensSold = tokensSold.add(ammount); token.transferFrom(this, investor, ammount); } function setTokenTransferState(bool state) public onlyOwner { token.changeController(this); token.enableTransfers(state); } function claim(address claimToken) public onlyOwner { token.changeController(this); token.claimTokens(claimToken); } function () external payable onlyWhitelisted whenNotPaused{ emit buyx(msg.sender, this, _getTokenAmount(msg.value)); buyTokens(msg.sender); } } contract Controlled is Pausable { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } modifier onlyControllerorOwner { require((msg.sender == controller) || (msg.sender == owner)); _; } address public controller; constructor() public { controller = msg.sender;} /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) public onlyControllerorOwner { controller = _newController; } } /// @dev The token controller contract must implement these functions contract TokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) public payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) public returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) public returns(bool); } /* Copyright 2016, Jordi Baylina This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public; } /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { using SafeMath for uint256; string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = 'V 1.0'; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred constructor( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = MiniMeTokenFactory(_tokenFactory); name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = MiniMeToken(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); 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 controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); } doTransfer(_from, _to, _amount); return true; } /// @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 { if (_amount == 0) { emit Transfer(_from, _to, _amount); // Follow the spec to louch the event when transfer 0 return; } // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer throws uint256 previousBalanceFrom = balanceOfAt(_from, block.number); require(previousBalanceFrom >= _amount); // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens uint256 previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo.add(_amount) >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo.add(_amount)); // An event to make the transfer easy to find on the blockchain emit Transfer(_from, _to, _amount); } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); } allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender ) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(address _spender, uint256 _amount, bytes _extraData ) public returns (bool success) { require(approve(_spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public constant returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount ) public onlyControllerorOwner whenNotPaused returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply.add(_amount) >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo.add(_amount) >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply.add(_amount)); updateValueAtNow(balances[_owner], previousBalanceTo.add(_amount)); emit Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount ) onlyControllerorOwner public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply.sub(_amount)); updateValueAtNow(balances[_owner], previousBalanceFrom.sub(_amount)); emit Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) public onlyControllerorOwner { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block ) constant internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length.sub(1)].fromBlock) return checkpoints[checkpoints.length.sub(1)].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length.sub(1); while (max > min) { uint mid = (max.add(min).add(1)).div(2); if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid.sub(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.sub(1)].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length.sub(1)]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () public payable { /*require(isContract(controller)); require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender));*/ revert(); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) public onlyControllerorOwner { if (_token == 0x0) { controller.transfer(address(this).balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); emit ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } contract EmaToken is MiniMeToken { constructor(address tokenfactory, address parenttoken, uint parentsnapshot, string tokenname, uint8 dec, string tokensymbol, bool transfersenabled) MiniMeToken(tokenfactory, parenttoken, parentsnapshot, tokenname, dec, tokensymbol, transfersenabled) public{ } } contract Configurator is Ownable { EmaToken public token = EmaToken(0xC3EE57Fa8eD253E3F214048879977265967AE745); EmaCrowdSale public crowdsale = EmaCrowdSale(0xAd97aF045F815d91621040809F863a5fb070B52d); address ownerWallet = 0x3046751e1d843748b4983D7bca58ECF6Ef1e5c77; address tokenfactory = 0xB74AA356913316ce49626527AE8543FFf23bB672; address fundsWallet = 0x3046751e1d843748b4983D7bca58ECF6Ef1e5c77; address incetivesPool = 0x95eac65414a6a650E2c71e3480AeEF0cF76392FA; address FoundersAndTeam = 0x88C952c4A8fc156b883318CdA8b4a5279d989391; address FuturePartners = 0x5B0333399E0D8F3eF1e5202b4eA4ffDdFD7a0382; address Contributors = 0xa02dfB73de485Ebd9d37CbA4583e916F3bA94CeE; address BountiesWal = 0xaB662f89A2c6e71BD8c7f754905cAaEC326BcdE7; uint256 public crowdSaleStart; function deploy() onlyOwner public{ owner = msg.sender; // crowdsale.transferOwnership(ownerWallet); // token.transferOwnership(ownerWallet); // token.changeController(this); token.generateTokens(crowdsale, 255000000000000000000000000); // Generate CrowdSale tokens token.generateTokens(incetivesPool, 115000000000000000000000000); //generate Incentives pool tokens token.generateTokens(FoundersAndTeam, 85000000000000000000000000); //generate Founders and team tokens token.generateTokens(FuturePartners, 40000000000000000000000000); //generate future partners tokens and contributors token.generateTokens(BountiesWal, 5000000000000000000000000); //generate contributors tokens token.changeController(EmaCrowdSale(crowdsale)); token.transferOwnership(ownerWallet); crowdsale.transferOwnership(ownerWallet); } }
crowdsale.transferOwnership(ownerWallet); token.transferOwnership(ownerWallet); token.changeController(this);
function deploy() onlyOwner public{ owner = msg.sender; token.changeController(EmaCrowdSale(crowdsale)); token.transferOwnership(ownerWallet); crowdsale.transferOwnership(ownerWallet); }
170,851
[ 1, 71, 492, 2377, 5349, 18, 13866, 5460, 12565, 12, 8443, 16936, 1769, 202, 2316, 18, 13866, 5460, 12565, 12, 8443, 16936, 1769, 202, 2316, 18, 3427, 2933, 12, 2211, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 445, 7286, 1435, 1338, 5541, 1071, 95, 203, 3196, 565, 3410, 273, 1234, 18, 15330, 31, 7010, 202, 377, 203, 202, 21281, 202, 202, 2316, 18, 3427, 2933, 12, 1514, 69, 39, 492, 72, 30746, 12, 71, 492, 2377, 5349, 10019, 203, 1082, 202, 2316, 18, 13866, 5460, 12565, 12, 8443, 16936, 1769, 203, 1082, 202, 71, 492, 2377, 5349, 18, 13866, 5460, 12565, 12, 8443, 16936, 1769, 203, 3639, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; import "./ITaxicoin.sol"; contract Taxicoin is ITaxicoin { uint8 public constant USERTYPE_NONE = 0; uint8 public constant USERTYPE_DRIVER = 1; uint8 public constant USERTYPE_ACTIVEDRIVER = 2; uint8 public constant USERTYPE_RIDER = 3; struct Driver { address addr; string lat; string lon; string pubKey; uint updated; address rider; uint deposit; uint8 rating; uint ratingCount; uint8 riderRating; uint proposedNewFare; bool hasProposedNewFare; } struct Rider { address addr; string pubKey; address driver; uint fare; uint deposit; uint8 rating; uint ratingCount; uint8 driverRating; } mapping(address => Driver) public drivers; mapping(address => Rider) public riders; // contract settings uint public driverDeposit; uint public riderDeposit; constructor() public { // in future, these will change dynamically driverDeposit = 100; riderDeposit = 100; } function driverAdvertise(string lat, string lon, string pubKey) public payable { // check the driver has paid deposit require(drivers[tx.origin].deposit >= driverDeposit || msg.value >= driverDeposit); // must not be ActiveDriver or Rider require(getUserType(tx.origin) != USERTYPE_ACTIVEDRIVER); require(getUserType(tx.origin) != USERTYPE_RIDER); // if new driver, add to index if (drivers[tx.origin].addr != tx.origin) { dllAddDriver(tx.origin); } // update driver state drivers[tx.origin].addr = tx.origin; drivers[tx.origin].lat = lat; drivers[tx.origin].lon = lon; drivers[tx.origin].updated = block.timestamp; drivers[tx.origin].deposit = drivers[tx.origin].deposit + msg.value; drivers[tx.origin].pubKey = pubKey; } function driverRevokeAdvert() public { // check driver is already advertised require(drivers[tx.origin].addr == tx.origin); // remove driver from index and mapping dllRemoveDriver(tx.origin); drivers[tx.origin].addr = address(0); } function riderCreateJourney(address driver, uint fare, string pubKey) public payable { // check the deposit + fare have been paid require(msg.value >= riderDeposit + fare); // check user is not already a rider or driver require(getUserType(tx.origin) == USERTYPE_NONE); // check driver is not the zero address require(driver != address(0)); // check the driver is advertised require(getUserType(driver) == USERTYPE_DRIVER); // set the rider's deposit, fare and pubKey riders[tx.origin].deposit = riderDeposit; riders[tx.origin].fare = fare; riders[tx.origin].pubKey = pubKey; // set the rider's current driver riders[tx.origin].driver = driver; // set the rider's address riders[tx.origin].addr = tx.origin; // send back any excess value tx.origin.transfer(msg.value - riderDeposit - fare); } function riderCancelJourney() public { // rider must have created a journey require(riders[tx.origin].addr != address(0)); // driver must not have accepted require(drivers[riders[tx.origin].driver].rider != tx.origin); // send back deposit and fare tx.origin.transfer(riders[tx.origin].deposit); tx.origin.transfer(riders[tx.origin].fare); // reset rider state riders[tx.origin].deposit = 0; riders[tx.origin].fare = 0; riders[tx.origin].driver = address(0); riders[tx.origin].addr = address(0); } function driverAcceptJourney(address rider, uint fare) public { // check the driver is advertised require(drivers[tx.origin].addr == tx.origin); // check declared fare is the same as rider's provided require(riders[rider].fare == fare); // check the rider has agreed to ride with this driver require(riders[rider].driver == tx.origin); // set the driver's rider drivers[tx.origin].rider = rider; // remove from DLL dllRemoveDriver(tx.origin); } function completeJourney(uint8 rating) public { require(rating > 0); uint8 userType = getUserType(tx.origin); if (userType == USERTYPE_ACTIVEDRIVER) { // set rating to give to rider drivers[tx.origin].riderRating = rating; // if rider has rated us, apply everything if (riders[drivers[tx.origin].rider].driverRating != 0) { finaliseCompleteJourney(drivers[tx.origin].rider, tx.origin); } } else if(userType == USERTYPE_RIDER) { // set rating to give to driver riders[tx.origin].driverRating = rating; // if driver has rated us, apply everything if (drivers[riders[tx.origin].driver].riderRating != 0) { finaliseCompleteJourney(tx.origin, riders[tx.origin].driver); } } else { revert(); } } function finaliseCompleteJourney(address riderAddr, address driverAddr) internal { // send rider deposit back riderAddr.transfer(riders[riderAddr].deposit); // if fare was non-zero, pay to driver and return driver deposit if (riders[riderAddr].fare > 0) { driverAddr.transfer(drivers[driverAddr].deposit); driverAddr.transfer(riders[riderAddr].fare); } // update driver rating drivers[driverAddr].rating = uint8((drivers[driverAddr].rating * drivers[driverAddr].ratingCount + riders[riderAddr].driverRating) / (drivers[driverAddr].ratingCount + 1)); drivers[driverAddr].ratingCount++; // update rider rating riders[riderAddr].rating = uint8((riders[riderAddr].rating * riders[riderAddr].ratingCount + drivers[driverAddr].riderRating) / (riders[riderAddr].ratingCount + 1)); riders[riderAddr].ratingCount++; // reset rider and driver state riders[riderAddr].addr = address(0); riders[riderAddr].driver = address(0); riders[riderAddr].driverRating = 0; riders[riderAddr].fare = 0; riders[riderAddr].deposit = 0; drivers[driverAddr].addr = address(0); drivers[driverAddr].rider = address(0); drivers[driverAddr].riderRating = 0; drivers[driverAddr].deposit = 0; } function driverProposeFareAlteration(uint newFare) public { // user must be active driver require(getUserType(tx.origin) == USERTYPE_ACTIVEDRIVER); // set the proposed new fare for driver drivers[tx.origin].proposedNewFare = newFare; drivers[tx.origin].hasProposedNewFare = true; } function riderConfirmFareAlteration(uint newFare) public payable { // user must be rider require(getUserType(tx.origin) == USERTYPE_RIDER); // driver must have already agreed to the same new fare require(drivers[riders[tx.origin].driver].hasProposedNewFare); require(drivers[riders[tx.origin].driver].proposedNewFare == newFare); uint fareDifference; if (newFare > riders[tx.origin].fare) { fareDifference = newFare - riders[tx.origin].fare; require(msg.value >= fareDifference); if (msg.value > fareDifference) { tx.origin.transfer(msg.value - fareDifference); } } else { fareDifference = riders[tx.origin].fare - newFare; tx.origin.transfer(fareDifference); } // set the new fare for the rider riders[tx.origin].fare = newFare; // reset the fare proposal for driver drivers[riders[tx.origin].driver].proposedNewFare = 0; drivers[riders[tx.origin].driver].hasProposedNewFare = false; } //------------------// // Helper functions // //------------------// function getUserType(address addr) public view returns (uint8) { if (drivers[addr].addr == addr) { if (drivers[addr].rider == address(0)) { return USERTYPE_DRIVER; } else { return USERTYPE_ACTIVEDRIVER; } } else if (riders[addr].addr == addr) { return USERTYPE_RIDER; } else { return USERTYPE_NONE; } } function getDriver(address driverAddr) public view returns (address addr, string lat, string lon, string pubKey, uint updated, address rider, uint deposit, uint8 rating, uint ratingCount, uint8 riderRating, uint proposedNewFare, bool hasProposedNewFare) { Driver memory dr = drivers[driverAddr]; return(dr.addr, dr.lat, dr.lon, dr.pubKey, dr.updated, dr.rider, dr.deposit, dr.rating, dr.ratingCount, dr.riderRating, dr.proposedNewFare, dr.hasProposedNewFare); } function getNextDriver(address driverAddr) public view returns (address addr, string lat, string lon, string pubKey, uint updated, address rider, uint deposit, uint8 rating, uint ratingCount, uint8 riderRating, uint proposedNewFare, bool hasProposedNewFare) { address nextDriver = dllDriverIndex[driverAddr][NEXT]; return getDriver(nextDriver); } function getPreviousDriver(address driverAddr) public view returns (address, string, string, string, uint, address, uint, uint8, uint, uint8, uint, bool) { address prevDriver = dllDriverIndex[driverAddr][PREV]; return getDriver(prevDriver); } function getRider(address riderAddr) public view returns (address addr, string pubKey, address driver, uint fare, uint deposit, uint8 rating, uint ratingCount, uint8 driverRating) { Rider memory rd = riders[riderAddr]; return(rd.addr, rd.pubKey, rd.driver, rd.fare, rd.deposit, rd.rating, rd.ratingCount, rd.driverRating); } //---------------------------------------------------------// // Double Linked List // // Adapted from https://ethereum.stackexchange.com/a/15341 // //---------------------------------------------------------// mapping(address => mapping(bool => address)) public dllDriverIndex; bool constant PREV = false; bool constant NEXT = true; function dllAddDriver(address addr) internal { // link the new node dllDriverIndex[addr][PREV] = 0x0; dllDriverIndex[addr][NEXT] = dllDriverIndex[0x0][NEXT]; // insert the new node dllDriverIndex[dllDriverIndex[0x0][NEXT]][PREV] = addr; dllDriverIndex[0x0][NEXT] = addr; } function dllRemoveDriver(address addr) internal { // stitch the neighbours together dllDriverIndex[dllDriverIndex[addr][PREV]][NEXT] = dllDriverIndex[addr][NEXT]; dllDriverIndex[dllDriverIndex[addr][NEXT]][PREV] = dllDriverIndex[addr][PREV]; // delete state storage delete dllDriverIndex[addr][PREV]; delete dllDriverIndex[addr][NEXT]; } }
user must be active driver set the proposed new fare for driver
function driverProposeFareAlteration(uint newFare) public { require(getUserType(tx.origin) == USERTYPE_ACTIVEDRIVER); drivers[tx.origin].proposedNewFare = newFare; drivers[tx.origin].hasProposedNewFare = true; }
2,547,793
[ 1, 1355, 1297, 506, 2695, 3419, 444, 326, 20084, 394, 284, 834, 364, 3419, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 3419, 626, 4150, 42, 834, 18144, 367, 12, 11890, 394, 42, 834, 13, 1071, 288, 203, 202, 202, 6528, 12, 588, 1299, 559, 12, 978, 18, 10012, 13, 422, 7443, 2399, 67, 6526, 20764, 20078, 1769, 203, 203, 202, 202, 3069, 6760, 63, 978, 18, 10012, 8009, 685, 7423, 1908, 42, 834, 273, 394, 42, 834, 31, 203, 202, 202, 3069, 6760, 63, 978, 18, 10012, 8009, 5332, 626, 7423, 1908, 42, 834, 273, 638, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.22; // File: contracts/ERC223/ERC223_receiving_contract.sol /** * @title Contract that will work with ERC223 tokens. */ contract ERC223ReceivingContract { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes _data) public; } // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // 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]; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: zeppelin-solidity/contracts/token/ERC20/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); 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; } } // File: zeppelin-solidity/contracts/token/ERC20/CappedToken.sol /** * @title Capped token * @dev Mintable token with a token cap. */ contract CappedToken is MintableToken { uint256 public cap; constructor(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } } // File: contracts/SafeGuardsToken.sol contract SafeGuardsToken is CappedToken { string constant public name = "SafeGuards Coin"; string constant public symbol = "SGCT"; uint constant public decimals = 18; // address who can burn tokens address public canBurnAddress; // list with frozen addresses mapping (address => bool) public frozenList; // timestamp until investors in frozen list can't transfer tokens uint256 public frozenPauseTime = now + 180 days; // timestamp until investors can't burn tokens uint256 public burnPausedTime = now + 180 days; constructor(address _canBurnAddress) CappedToken(61 * 1e6 * 1e18) public { require(_canBurnAddress != 0x0); canBurnAddress = _canBurnAddress; } // ===--- Presale frozen functionality ---=== event ChangeFrozenPause(uint256 newFrozenPauseTime); /** * @dev Function to mint frozen 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 mintFrozen(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { frozenList[_to] = true; return super.mint(_to, _amount); } function changeFrozenTime(uint256 _newFrozenPauseTime) onlyOwner public returns (bool) { require(_newFrozenPauseTime > now); frozenPauseTime = _newFrozenPauseTime; emit ChangeFrozenPause(_newFrozenPauseTime); return true; } // ===--- Override transfers with implementation of the ERC223 standard and frozen logic ---=== event Transfer(address indexed from, address indexed to, uint value, bytes data); /** * @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) public returns (bool) { bytes memory empty; return transfer(_to, _value, empty); } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _data Optional metadata. */ function transfer(address _to, uint _value, bytes _data) public returns (bool) { require(now > frozenPauseTime || !frozenList[msg.sender]); super.transfer(_to, _value); if (isContract(_to)) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); emit Transfer(msg.sender, _to, _value, _data); } return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint _value) public returns (bool) { bytes memory empty; return transferFrom(_from, _to, _value, empty); } /** * @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 * @param _data Optional metadata. */ function transferFrom(address _from, address _to, uint _value, bytes _data) public returns (bool) { require(now > frozenPauseTime || !frozenList[msg.sender]); super.transferFrom(_from, _to, _value); if (isContract(_to)) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(_from, _value, _data); } emit Transfer(_from, _to, _value, _data); return true; } 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); } // ===--- Burnable functionality ---=== event Burn(address indexed burner, uint256 value); event ChangeBurnPause(uint256 newBurnPauseTime); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(burnPausedTime < now || msg.sender == canBurnAddress); require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(burner, _value); emit Transfer(burner, address(0), _value); } function changeBurnPausedTime(uint256 _newBurnPauseTime) onlyOwner public returns (bool) { require(_newBurnPauseTime > burnPausedTime); burnPausedTime = _newBurnPauseTime; emit ChangeBurnPause(_newBurnPauseTime); return true; } } // File: zeppelin-solidity/contracts/crowdsale/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ constructor(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transfer(_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); } } // File: zeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { require(now >= openingTime && now <= 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 { require(_openingTime >= now); 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) { return now > 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); } } // File: zeppelin-solidity/contracts/crowdsale/distribution/FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasClosed()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } // File: zeppelin-solidity/contracts/crowdsale/validation/CappedCrowdsale.sol /** * @title CappedCrowdsale * @dev Crowdsale with a limit for total contributions. */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; /** * @dev Constructor, takes maximum amount of wei accepted in the crowdsale. * @param _cap Max amount of wei to be contributed */ constructor(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised >= cap; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(weiRaised.add(_weiAmount) <= cap); } } // File: contracts/SafeGuardsPreSale.sol contract SafeGuardsPreSale is FinalizableCrowdsale, CappedCrowdsale { using SafeMath for uint256; // amount of tokens that was sold on the crowdsale uint256 public tokensSold; // if minimumGoal will not be reached till _closingTime, buyers will be able to refund ETH uint256 public minimumGoal; // how much wei we have returned back to the contract after a failed crowdfund uint public loadedRefund; // how much wei we have given back to buyers uint public weiRefunded; // how much ETH each address has bought to this crowdsale mapping (address => uint) public boughtAmountOf; // minimum amount of wel, that can be contributed uint256 constant public minimumAmountWei = 1e16; // timestamp until presale investors can't transfer tokens uint256 public presaleTransfersPaused = now + 180 days; // timestamp until investors can't burn tokens uint256 public presaleBurnPaused = now + 180 days; // ---====== BONUSES for presale users ======--- // time presale bonuses uint constant public preSaleBonus1Time = 1535155200; // uint constant public preSaleBonus1Percent = 25; uint constant public preSaleBonus2Time = 1536019200; // uint constant public preSaleBonus2Percent = 15; uint constant public preSaleBonus3Time = 1536883200; // uint constant public preSaleBonus3Percent = 5; // amount presale bonuses uint constant public preSaleBonus1Amount = 155 * 1e15; uint constant public preSaleBonus2Amount = 387 * 1e15; uint constant public preSaleBonus3Amount = 1550 * 1e15; uint constant public preSaleBonus4Amount = 15500 * 1e15; // ---=== Addresses of founders, team and bounty ===--- address constant public w_futureDevelopment = 0x4b297AB09bF4d2d8107fAa03cFF5377638Ec6C83; address constant public w_Reserv = 0xbb67c6E089c7801ab3c7790158868970ea0d8a7C; address constant public w_Founders = 0xa3b331037e29540F8BD30f3DE4fF4045a8115ff4; address constant public w_Team = 0xa8324689c94eC3cbE9413C61b00E86A96978b4A7; address constant public w_Advisers = 0x2516998954440b027171Ecb955A4C01DfF610F2d; address constant public w_Bounty = 0x1792b603F233220e1E623a6ab3FEc68deFa15f2F; event AddBonus(address indexed addr, uint256 amountWei, uint256 date, uint bonusType); struct Bonus { address addr; uint256 amountWei; uint256 date; uint bonusType; } struct Bonuses { address addr; uint256 numBonusesInAddress; uint256[] indexes; } /** * @dev Get all bonuses by account address */ mapping(address => Bonuses) public bonuses; /** * @dev Bonuses list */ Bonus[] public bonusList; /** * @dev Count of bonuses in list */ function numBonuses() public view returns (uint256) { return bonusList.length; } /** * @dev Count of members in archive */ function getBonusByAddressAndIndex(address _addr, uint256 _index) public view returns (uint256) { return bonuses[_addr].indexes[_index]; } /** * @param _rate Number of token units a buyer gets per one ETH * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time * @param _minimumGoal Funding goal (soft cap) * @param _cap Max amount of ETH to be contributed (hard cap) */ constructor( uint256 _rate, address _wallet, ERC20 _token, uint256 _openingTime, uint256 _closingTime, uint256 _minimumGoal, uint256 _cap ) Crowdsale(_rate * 1 ether, _wallet, _token) TimedCrowdsale(_openingTime, _closingTime) CappedCrowdsale(_cap * 1 ether) public { require(_rate > 0); require(_wallet != address(0)); rate = _rate; wallet = _wallet; minimumGoal = _minimumGoal * 1 ether; } /** * @dev Allows the current owner to transfer token's control to a newOwner. * @param _newTokenOwner The address to transfer token's ownership to. */ function changeTokenOwner(address _newTokenOwner) external onlyOwner { require(_newTokenOwner != 0x0); require(hasClosed()); SafeGuardsToken(token).transferOwnership(_newTokenOwner); } /** * @dev finalization task, called when owner calls finalize() */ function finalization() internal { require(isMinimumGoalReached()); SafeGuardsToken(token).mint(w_futureDevelopment, tokensSold.mul(20).div(43)); SafeGuardsToken(token).mint(w_Reserv, tokensSold.mul(20).div(43)); SafeGuardsToken(token).mint(w_Founders, tokensSold.mul(7).div(43)); SafeGuardsToken(token).mint(w_Team, tokensSold.mul(5).div(43)); SafeGuardsToken(token).mint(w_Advisers, tokensSold.mul(3).div(43)); SafeGuardsToken(token).mint(w_Bounty, tokensSold.mul(2).div(43)); super.finalization(); } /** * @dev Validation of an incoming purchase. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_weiAmount >= minimumAmountWei); super._preValidatePurchase(_beneficiary, _weiAmount); } /** * @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(SafeGuardsToken(token).mintFrozen(_beneficiary, _tokenAmount)); tokensSold = tokensSold.add(_tokenAmount); } function changeTransfersPaused(uint256 _newFrozenPauseTime) onlyOwner public returns (bool) { require(_newFrozenPauseTime > now); presaleTransfersPaused = _newFrozenPauseTime; SafeGuardsToken(token).changeFrozenTime(_newFrozenPauseTime); return true; } function changeBurnPaused(uint256 _newBurnPauseTime) onlyOwner public returns (bool) { require(_newBurnPauseTime > presaleBurnPaused); presaleBurnPaused = _newBurnPauseTime; SafeGuardsToken(token).changeBurnPausedTime(_newBurnPauseTime); return true; } // ===--- Bonuses functionality ---=== /** * @dev add bonuses for users * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { require(_weiAmount >= minimumAmountWei); boughtAmountOf[msg.sender] = boughtAmountOf[msg.sender].add(_weiAmount); if (_weiAmount >= preSaleBonus1Amount) { if (_weiAmount >= preSaleBonus2Amount) { if (_weiAmount >= preSaleBonus3Amount) { if (_weiAmount >= preSaleBonus4Amount) { addBonusToUser(msg.sender, _weiAmount, preSaleBonus4Amount, 4); } else { addBonusToUser(msg.sender, _weiAmount, preSaleBonus3Amount, 3); } } else { addBonusToUser(msg.sender, _weiAmount, preSaleBonus2Amount, 2); } } else { addBonusToUser(msg.sender, _weiAmount, preSaleBonus1Amount, 1); } } } function addBonusToUser(address _addr, uint256 _weiAmount, uint256 _bonusAmount, uint _bonusType) internal { uint256 countBonuses = _weiAmount.div(_bonusAmount); Bonus memory b; b.addr = _addr; b.amountWei = _weiAmount; b.date = now; b.bonusType = _bonusType; for (uint256 i = 0; i < countBonuses; i++) { bonuses[_addr].addr = _addr; bonuses[_addr].numBonusesInAddress++; bonuses[_addr].indexes.push(bonusList.push(b) - 1); emit AddBonus(_addr, _weiAmount, now, _bonusType); } } /** * @dev Returns the rate of tokens per wei at the present time. * Note that, as price _increases_ with time, the rate _decreases_. * @return The number of tokens a buyer gets per wei at a given time */ function getCurrentRate() public view returns (uint256) { if (now > preSaleBonus3Time) { return rate; } if (now < preSaleBonus1Time) { return rate.add(rate.mul(preSaleBonus1Percent).div(100)); } if (now < preSaleBonus2Time) { return rate.add(rate.mul(preSaleBonus2Percent).div(100)); } if (now < preSaleBonus3Time) { return rate.add(rate.mul(preSaleBonus3Percent).div(100)); } return rate; } /** * @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 currentRate.mul(_weiAmount); } // ===--- Refund functionality ---=== // a refund was processed for an buyer event Refund(address buyer, uint weiAmount); event RefundLoaded(uint amount); // return true if the crowdsale has raised enough money to be a successful. function isMinimumGoalReached() public constant returns (bool) { return weiRaised >= minimumGoal; } /** * Allow load refunds back on the contract for the refunding. * * The team can transfer the funds back on the smart contract in the case the minimum goal was not reached. */ function loadRefund() external payable { require(msg.sender == wallet); require(msg.value > 0); require(!isMinimumGoalReached()); loadedRefund = loadedRefund.add(msg.value); emit RefundLoaded(msg.value); } /** * Buyers can claim refund. * * Note that any refunds from proxy buyers should be handled separately, * and not through this contract. */ function refund() external { require(!isMinimumGoalReached() && loadedRefund > 0); uint weiValue = boughtAmountOf[msg.sender]; require(weiValue > 0); require(weiValue <= loadedRefund); boughtAmountOf[msg.sender] = 0; weiRefunded = weiRefunded.add(weiValue); msg.sender.transfer(weiValue); emit Refund(msg.sender, weiValue); } }
* @dev Burns a specific amount of tokens. @param _value The amount of token to be burned./
function burn(uint256 _value) public { require(burnPausedTime < now || msg.sender == canBurnAddress); require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(burner, _value); emit Transfer(burner, address(0), _value); }
7,316,903
[ 1, 38, 321, 87, 279, 2923, 3844, 434, 2430, 18, 225, 389, 1132, 1021, 3844, 434, 1147, 358, 506, 18305, 329, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18305, 12, 11890, 5034, 389, 1132, 13, 1071, 288, 203, 3639, 2583, 12, 70, 321, 28590, 950, 411, 2037, 747, 1234, 18, 15330, 422, 848, 38, 321, 1887, 1769, 203, 203, 3639, 2583, 24899, 1132, 1648, 324, 26488, 63, 3576, 18, 15330, 19226, 203, 203, 3639, 1758, 18305, 264, 273, 1234, 18, 15330, 31, 203, 3639, 324, 26488, 63, 70, 321, 264, 65, 273, 324, 26488, 63, 70, 321, 264, 8009, 1717, 24899, 1132, 1769, 203, 3639, 2078, 3088, 1283, 67, 273, 2078, 3088, 1283, 27799, 1717, 24899, 1132, 1769, 203, 3639, 3626, 605, 321, 12, 70, 321, 264, 16, 389, 1132, 1769, 203, 3639, 3626, 12279, 12, 70, 321, 264, 16, 1758, 12, 20, 3631, 389, 1132, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: MIT pragma solidity ^0.8.11; /* CAT BRICKS CLUBHOUSE @INVADERETH - DEV @OOFFSETT - ART @ITSFUJIFUJI - FINANCE @HUMZAH_ETH - COMMUNITY @SHARK_IDK - COMMUNITY @DAKL__ - MARKETING @1KIWEE - MARKETING This contract has been insanely gas optimized with the latest best practices. Features such as off-chain whitelisting and permanent OpenSea approval have been implemented - saving gas both on the minting and secondary market end. LEGAL NOTICE The following addresses the issues of copyright or trademark infringement. LEGO® is a trademark of the LEGO Group, which does not sponsor, authorize or endorse the Cat Bricks Clubhouse project. The LEGO Group is neither endorsing the modification in any way, shape, or form, nor accepting any responsibility for unforeseen and/or adverse consequences. The patent for the Toy figure model expired in 1993. The models are open to usage so long as the aforementioned LEGO brand is not infringed upon. */ import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "./ERC721SeqEnumerable.sol"; import "./common/ContextMixin.sol"; import "./common/NativeMetaTransaction.sol"; contract OwnableDelegateProxy { } contract OpenSeaProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } contract CatBricksClubhouse is ERC721SeqEnumerable, ContextMixin, NativeMetaTransaction, Ownable { using Strings for uint256; using ECDSA for bytes32; uint256 public constant CBC_MAX = 9999; uint256 public constant CBC_PRIVATE = 8888; uint256 public constant CBC_PRICE = 0.08 ether; uint256 public constant PRIV_PER_MINT = 2; uint256 public constant PUB_PER_MINT = 4; uint256 public lostCats; string private _contractURI = "https://cbc.mypinata.cloud/ipfs/Qmdbo4z1WLduLoMe7sU9YXe8SDGkiFc7uXwnnodJ2anfc5"; string private _tokenBaseURI = "https://cbc.mypinata.cloud/ipfs/QmZZ5FiQ8FVroynJ4e9v7q5NPygojWv3xFxpJZjaxSkx1H/"; string private _tokenExtension = ".json"; address private _vault = 0x563e6750e382fe86E458153ba520B89F986471aa; address private _signer = 0xb82209b16Ab5c56716f096dc1a51B95d424f755a; address private _proxy = 0xa5409ec958C83C3f309868babACA7c86DCB077c1; bool public presaleLive; bool public saleLive; mapping(address => bool) public projectProxy; mapping(address => uint256) public presalerListPurchases; constructor() ERC721Sequencial("Cat Bricks Clubhouse", "CATBRICK") { _initializeEIP712("Cat Bricks Clubhouse"); } // Mint during public sale function buy(uint256 tokenQuantity) external payable { require(saleLive, "Sale Inactive"); require(!presaleLive, "Only Presale"); require(tokenQuantity <= PUB_PER_MINT, "Exceed Max"); require(totalSupply() + tokenQuantity < CBC_MAX, "Out of Stock"); require(CBC_PRICE * tokenQuantity <= msg.value, "More ETH Needed"); for (uint256 i = 0; i < tokenQuantity; i++) { _safeMint(msg.sender); } } // Mint during presale - disables contract minting function privateBuy(uint256 tokenQuantity, bytes32 hash, bytes memory signature) external payable { require(!saleLive && presaleLive, "Presale Inactive"); require(matchAddressSigner(hash, signature), "Contract Disabled for Presale"); require(tokenQuantity <= PRIV_PER_MINT, "Exceed Max"); require(presalerListPurchases[msg.sender] + tokenQuantity <= PRIV_PER_MINT, "Holding Max Allowed"); require(CBC_PRICE * tokenQuantity <= msg.value, "More ETH"); require(totalSupply() + tokenQuantity <= CBC_PRIVATE, "Exceed Supply"); for (uint256 i = 0; i < tokenQuantity; i++) { _safeMint(msg.sender); } presalerListPurchases[msg.sender] += tokenQuantity; } // Close or open the private sale function togglePrivateSaleStatus() external onlyOwner { presaleLive = !presaleLive; } // Close or open the public sale function toggleSaleStatus() external onlyOwner { saleLive = !saleLive; } // Withdraw funds for team expenses and payment function withdraw() external onlyOwner { (bool success, ) = _vault.call{value: address(this).balance}(""); require(success, "Failed to send to vault."); } // Approves OpenSea - bypassing approval fee payment function isApprovedForAll(address _owner, address operator) public view override returns (bool) { OpenSeaProxyRegistry proxyRegistry = OpenSeaProxyRegistry(_proxy); if (address(proxyRegistry.proxies(_owner)) == operator || projectProxy[operator]) return true; return super.isApprovedForAll(_owner, operator); } // ** - SETTERS - ** // // Set the vault address for payments function setVaultAddress(address addr) external onlyOwner { _vault = addr; } // Set the proxy address for payments function setProxyAddress(address addr) external onlyOwner { _proxy = addr; } // For future proxy approval management function flipProxyState(address proxyAddress) public onlyOwner { projectProxy[proxyAddress] = !projectProxy[proxyAddress]; } // Set the contract URL for OpenSea Metadata function setContractURI(string calldata URI) external onlyOwner { _contractURI = URI; } // Set image path for metadata function setBaseURI(string calldata URI) external onlyOwner { _tokenBaseURI = URI; } // Set file extension for metadata function setTokenExtension(string calldata extension) external onlyOwner { _tokenExtension = extension; } function gift(address[] calldata _recipients) external onlyOwner { uint256 recipients = _recipients.length; require( recipients + _owners.length <= CBC_MAX, "Exceeds Supply" ); for (uint256 i = 0; i < recipients; i++) { _safeMint(_recipients[i]); } } // Future game usage or user choice function burn(uint256 tokenId) public { require(_isApprovedOrOwner(_msgSender(), tokenId), "Not approved to burn."); _burn(tokenId); lostCats++; } // ** - READ - ** // function contractURI() public view returns (string memory) { return _contractURI; } function tokenExtension() public view returns (string memory) { return _tokenExtension; } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "Nonexistent token"); return string(abi.encodePacked(_tokenBaseURI, tokenId.toString(), _tokenExtension)); } function presalePurchasedCount(address addr) external view returns (uint256) { return presalerListPurchases[addr]; } function matchAddressSigner(bytes32 hash, bytes memory signature) private view returns(bool) { return _signer == hash.recover(signature); } } // 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 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.11; import "./ERC721Sequencial.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; /** * @dev This is a no storage implemntation of the optional extension {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. These functions * are mainly for convienence and should NEVER be called from inside a * contract on the chain. */ abstract contract ERC721SeqEnumerable is ERC721Sequencial, IERC721Enumerable { address constant zero = address(0); /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721Sequencial) 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 tokenId) { uint256 length = _owners.length; unchecked { for (; tokenId < length; ++tokenId) { if (_owners[tokenId] == owner) { if (index-- == 0) { break; } } } } require( tokenId < length, "ERC721Enumerable: owner index out of bounds" ); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256 supply) { unchecked { uint256 length = _owners.length; for (uint256 tokenId = 0; tokenId < length; ++tokenId) { if (_owners[tokenId] != zero) { ++supply; } } } } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256 tokenId) { uint256 length = _owners.length; unchecked { for (; tokenId < length; ++tokenId) { if (_owners[tokenId] != zero) { if (index-- == 0) { break; } } } } require( tokenId < length, "ERC721Enumerable: global index out of bounds" ); } /** * @dev Get all tokens owned by owner. */ function ownerTokens(address owner) public view returns (uint256[] memory) { uint256 tokenCount = ERC721Sequencial.balanceOf(owner); require(tokenCount != 0, "ERC721Enumerable: owner owns no tokens"); uint256 length = _owners.length; uint256[] memory tokenIds = new uint256[](tokenCount); unchecked { uint256 i = 0; for (uint256 tokenId = 0; tokenId < length; ++tokenId) { if (_owners[tokenId] == owner) { tokenIds[i++] = tokenId; } } } return tokenIds; } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.11; abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = payable(msg.sender); } return sender; } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.11; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {EIP712Base} from "./EIP712Base.sol"; contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, payable(msg.sender), functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } // 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/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 pragma solidity ^0.8.11; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721 * [ERC721] Non-Fungible Token Standard * * This implmentation of ERC721 assumes sequencial token creation to provide * efficient minting. Storage for balance are no longer required reducing * gas significantly. This comes at the price of calculating the balance by * iterating through the entire array. The balanceOf function should NOT * be used inside a contract. Gas usage will explode as the size of tokens * increase. A convineiance function is provided which returns the entire * list of owners whose index maps tokenIds to thier owners. Zero addresses * indicate burned tokens. * */ contract ERC721Sequencial 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 address[] _owners; // 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 balance) { require(owner != address(0), "ERC721: balance query for the zero address"); unchecked { uint256 length = _owners.length; for (uint256 i = 0; i < length; ++i) { if (_owners[i] == owner) { ++balance; } } } } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: owner query for nonexistent token"); address owner = _owners[tokenId]; return owner; } /** * @dev Returns entire list of owner enumerated by thier tokenIds. Burned tokens * will have a zero address. */ function owners() public view returns (address[] memory) { address[] memory owners_ = _owners; return owners_; } /** * @dev Return largest tokenId minted. */ function maxTokenId() public view returns (uint256) { return _owners.length > 0 ? _owners.length - 1 : 0; } /** * @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 = ERC721Sequencial.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 tokenId < _owners.length && _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 = ERC721Sequencial.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) internal virtual returns (uint256 tokenId) { tokenId = _safeMint(to, ""); } /** * @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, bytes memory _data ) internal virtual returns (uint256 tokenId) { tokenId = _mint(to); 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) internal virtual returns (uint256 tokenId) { require(to != address(0), "ERC721: mint to the zero address"); tokenId = _owners.length; _beforeTokenTransfer(address(0), to, tokenId); _owners.push(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 = ERC721Sequencial.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); 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(ERC721Sequencial.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Sequencial.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.1 (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.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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.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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.11; import {Initializable} from "./Initializable.sol"; contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string public constant ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contracts that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712(string memory name) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.11; contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } }
* @dev Returns entire list of owner enumerated by thier tokenIds. Burned tokens will have a zero address./
function owners() public view returns (address[] memory) { address[] memory owners_ = _owners; return owners_; }
1,210,891
[ 1, 1356, 7278, 666, 434, 3410, 3557, 690, 635, 286, 2453, 1147, 2673, 18, 225, 605, 321, 329, 2430, 903, 1240, 279, 3634, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 25937, 1435, 1071, 1476, 1135, 261, 2867, 8526, 3778, 13, 288, 203, 3639, 1758, 8526, 3778, 25937, 67, 273, 389, 995, 414, 31, 203, 3639, 327, 25937, 67, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x537eE18Ca78C42E1e7fB87FECFE9FC811c3d3575/sources/contracts/strategy/liquity/LiquityStrategy.sol
* Allows an address to be used as a swap target by adding it on the whitelist. @notice Can only be called by the account with the SETTINGS role. @notice Swap targets are addresses of 0x contracts used for swapping ETH and LQTY tokens held by the strategy./
function allowSwapTarget(address _swapTarget) external onlySettings { _checkSwapTargetForZeroAddress(_swapTarget); allowedSwapTargets[_swapTarget] = true; }
16,543,962
[ 1, 19132, 392, 1758, 358, 506, 1399, 487, 279, 7720, 1018, 635, 6534, 518, 603, 326, 10734, 18, 225, 4480, 1338, 506, 2566, 635, 326, 2236, 598, 326, 3174, 15901, 2478, 18, 225, 12738, 5774, 854, 6138, 434, 374, 92, 20092, 1399, 364, 7720, 1382, 512, 2455, 471, 511, 53, 5538, 2430, 15770, 635, 326, 6252, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1699, 12521, 2326, 12, 2867, 389, 22270, 2326, 13, 3903, 1338, 2628, 288, 203, 3639, 389, 1893, 12521, 2326, 1290, 7170, 1887, 24899, 22270, 2326, 1769, 203, 203, 3639, 2935, 12521, 9432, 63, 67, 22270, 2326, 65, 273, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xa3a592a37803f48da9cA6c0558Ef1Fe96181c175/sources/contracts/orderbook/OrderBook.sol
Thrown when the input and output tokens don't match, in either direction. @param aliceToken The input or output of one order. @param bobToken The input or output of the other order that doesn't match a.
error TokenMismatch(address aliceToken, address bobToken);
17,080,216
[ 1, 29591, 1347, 326, 810, 471, 876, 2430, 2727, 1404, 845, 16, 316, 3344, 4068, 18, 225, 524, 1812, 1345, 1021, 810, 578, 876, 434, 1245, 1353, 18, 225, 800, 70, 1345, 1021, 810, 578, 876, 434, 326, 1308, 1353, 716, 3302, 1404, 845, 279, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1636, 3155, 16901, 12, 2867, 524, 1812, 1345, 16, 1758, 800, 70, 1345, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-11-03 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /** * @dev ERC-721 non-fungible token standard. * See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md. */ interface ERC721 { /** * @dev Emits when ownership of any NFT changes by any mechanism. This event emits when NFTs are * created (`from` == 0) and destroyed (`to` == 0). Exception: during contract creation, any * number of NFTs may be created and assigned without emitting Transfer. At the time of any * transfer, the approved address for that NFT (if any) is reset to none. */ event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); /** * @dev This emits when the approved address for an NFT is changed or reaffirmed. The zero * address indicates there is no approved address. When a Transfer event emits, this also * indicates that the approved address for that NFT (if any) is reset to none. */ event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); /** * @dev This emits when an operator is enabled or disabled for an owner. The operator can manage * all NFTs of the owner. */ event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); /** * @dev Transfers the ownership of an NFT from one address to another address. * @notice Throws unless `msg.sender` is the current owner, an authorized operator, or the * approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is * the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this * function checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. * @param _data Additional data with no specified format, sent in call to `_to`. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes calldata _data ) external; /** * @dev Transfers the ownership of an NFT from one address to another address. * @notice This works identically to the other function with an extra data parameter, except this * function just sets data to "" * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external; /** * @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved * address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero * address. Throws if `_tokenId` is not a valid NFT. * @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else * they mayb be permanently lost. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function transferFrom( address _from, address _to, uint256 _tokenId ) external; /** * @dev Set or reaffirm the approved address for an NFT. * @notice The zero address indicates there is no approved address. Throws unless `msg.sender` is * the current NFT owner, or an authorized operator of the current owner. * @param _approved The new approved NFT controller. * @param _tokenId The NFT to approve. */ function approve( address _approved, uint256 _tokenId ) external; /** * @dev Enables or disables approval for a third party ("operator") to manage all of * `msg.sender`'s assets. It also emits the ApprovalForAll event. * @notice The contract MUST allow multiple operators per owner. * @param _operator Address to add to the set of authorized operators. * @param _approved True if the operators is approved, false to revoke approval. */ function setApprovalForAll( address _operator, bool _approved ) external; /** * @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are * considered invalid, and this function throws for queries about the zero address. * @param _owner Address for whom to query the balance. * @return Balance of _owner. */ function balanceOf( address _owner ) external view returns (uint256); /** * @dev Returns the address of the owner of the NFT. NFTs assigned to zero address are considered * invalid, and queries about them do throw. * @param _tokenId The identifier for an NFT. * @return Address of _tokenId owner. */ function ownerOf( uint256 _tokenId ) external view returns (address); /** * @dev Get the approved address for a single NFT. * @notice Throws if `_tokenId` is not a valid NFT. * @param _tokenId The NFT to find the approved address for. * @return Address that _tokenId is approved for. */ function getApproved( uint256 _tokenId ) external view returns (address); /** * @dev Returns true if `_operator` is an approved operator for `_owner`, false otherwise. * @param _owner The address that owns the NFTs. * @param _operator The address that acts on behalf of the owner. * @return True if approved for all, false otherwise. */ function isApprovedForAll( address _owner, address _operator ) external view returns (bool); } /** * @dev ERC-721 interface for accepting safe transfers. * See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md. */ interface ERC721TokenReceiver { /** * @dev Handle the receipt of a NFT. The ERC721 smart contract calls this function on the * recipient after a `transfer`. This function MAY throw to revert and reject the transfer. Return * of other than the magic value MUST result in the transaction being reverted. * Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` unless throwing. * @notice The contract address is always the message sender. A wallet/broker/auction application * MUST implement the wallet interface if it will accept safe transfers. * @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 Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes calldata _data ) external returns(bytes4); } /** * @dev Math operations with safety checks that throw on error. */ library SafeMath { string constant OVERFLOW = "008001"; string constant SUBTRAHEND_GREATER_THEN_MINUEND = "008002"; string constant DIVISION_BY_ZERO = "008003"; /** * @dev Multiplies two numbers, reverts on overflow. * @param _factor1 Factor number. * @param _factor2 Factor number. * @return product The product of the two factors. */ function mul( uint256 _factor1, uint256 _factor2 ) internal pure returns (uint256 product) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. if (_factor1 == 0) { return 0; } product = _factor1 * _factor2; require(product / _factor1 == _factor2, OVERFLOW); } /** * @dev Integer division of two numbers, truncating the quotient, reverts on division by zero. * @param _dividend Dividend number. * @param _divisor Divisor number. * @return quotient The quotient. */ function div( uint256 _dividend, uint256 _divisor ) internal pure returns (uint256 quotient) { // Solidity automatically asserts when dividing by 0, using all gas. require(_divisor > 0, DIVISION_BY_ZERO); quotient = _dividend / _divisor; // assert(_dividend == _divisor * quotient + _dividend % _divisor); // There is no case in which this doesn't hold. } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). * @param _minuend Minuend number. * @param _subtrahend Subtrahend number. * @return difference Difference. */ function sub( uint256 _minuend, uint256 _subtrahend ) internal pure returns (uint256 difference) { require(_subtrahend <= _minuend, SUBTRAHEND_GREATER_THEN_MINUEND); difference = _minuend - _subtrahend; } /** * @dev Adds two numbers, reverts on overflow. * @param _addend1 Number. * @param _addend2 Number. * @return sum Sum. */ function add( uint256 _addend1, uint256 _addend2 ) internal pure returns (uint256 sum) { sum = _addend1 + _addend2; require(sum >= _addend1, OVERFLOW); } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), reverts when * dividing by zero. * @param _dividend Number. * @param _divisor Number. * @return remainder Remainder. */ function mod( uint256 _dividend, uint256 _divisor ) internal pure returns (uint256 remainder) { require(_divisor != 0, DIVISION_BY_ZERO); remainder = _dividend % _divisor; } } /** * @dev A standard for detecting smart contract interfaces. * See: https://eips.ethereum.org/EIPS/eip-165. */ interface ERC165 { /** * @dev Checks if the smart contract includes a specific interface. * @notice This function uses less than 30,000 gas. * @param _interfaceID The interface identifier, as specified in ERC-165. * @return True if _interfaceID is supported, false otherwise. */ function supportsInterface( bytes4 _interfaceID ) external view returns (bool); } /** * @dev Implementation of standard for detect smart contract interfaces. */ contract SupportsInterface is ERC165 { mapping(bytes4 => bool) internal supportedInterfaces; /** * @dev Contract constructor. */ constructor() public { supportedInterfaces[0x01ffc9a7] = true; // ERC165 } /** * @dev Function to check which interfaces are suported by this contract. * @param _interfaceID Id of the interface. * @return True if _interfaceID is supported, false otherwise. */ function supportsInterface( bytes4 _interfaceID ) external override view returns (bool) { return supportedInterfaces[_interfaceID]; } } /** * @dev Utility library of inline functions on addresses. */ library AddressUtils { /** * @dev Returns whether the target address is a contract. * @param _addr Address to check. * @return addressCheck True if _addr is a contract, false if not. */ function isContract( address _addr ) internal view returns (bool addressCheck) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash := extcodehash(_addr) } // solhint-disable-line addressCheck = (codehash != 0x0 && codehash != accountHash); } } /** * @dev Implementation of ERC-721 non-fungible token standard. */ contract NFToken is ERC721, SupportsInterface { using SafeMath for uint256; using AddressUtils for address; string constant ZERO_ADDRESS = "003001"; string constant NOT_VALID_NFT = "003002"; string constant NOT_OWNER_OR_OPERATOR = "003003"; string constant NOT_OWNER_APPROWED_OR_OPERATOR = "003004"; string constant NOT_ABLE_TO_RECEIVE_NFT = "003005"; string constant NFT_ALREADY_EXISTS = "003006"; string constant NOT_OWNER = "003007"; string constant IS_OWNER = "003008"; /** * @dev Magic value of a smart contract that can recieve NFT. * Equal to: bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")). */ bytes4 internal constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02; /** * @dev A mapping from NFT ID to the address that owns it. */ mapping (uint256 => address) internal idToOwner; /** * @dev Mapping from NFT ID to approved address. */ mapping (uint256 => address) internal idToApproval; /** * @dev Mapping from owner address to count of his tokens. */ mapping (address => uint256) private ownerToNFTokenCount; /** * @dev Mapping from owner address to mapping of operator addresses. */ mapping (address => mapping (address => bool)) internal ownerToOperators; // /** // * @dev Emits when ownership of any NFT changes by any mechanism. This event emits when NFTs are // * created (`from` == 0) and destroyed (`to` == 0). Exception: during contract creation, any // * number of NFTs may be created and assigned without emitting Transfer. At the time of any // * transfer, the approved address for that NFT (if any) is reset to none. // * @param _from Sender of NFT (if address is zero address it indicates token creation). // * @param _to Receiver of NFT (if address is zero address it indicates token destruction). // * @param _tokenId The NFT that got transfered. // */ // event Transfer( // address indexed _from, // address indexed _to, // uint256 indexed _tokenId // ); // /** // * @dev This emits when the approved address for an NFT is changed or reaffirmed. The zero // * address indicates there is no approved address. When a Transfer event emits, this also // * indicates that the approved address for that NFT (if any) is reset to none. // * @param _owner Owner of NFT. // * @param _approved Address that we are approving. // * @param _tokenId NFT which we are approving. // */ // event Approval( // address indexed _owner, // address indexed _approved, // uint256 indexed _tokenId // ); // /** // * @dev This emits when an operator is enabled or disabled for an owner. The operator can manage // * all NFTs of the owner. // * @param _owner Owner of NFT. // * @param _operator Address to which we are setting operator rights. // * @param _approved Status of operator rights(true if operator rights are given and false if // * revoked). // */ // event ApprovalForAll( // address indexed _owner, // address indexed _operator, // bool _approved // ); /** * @dev Guarantees that the msg.sender is an owner or operator of the given NFT. * @param _tokenId ID of the NFT to validate. */ modifier canOperate( uint256 _tokenId ) { address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == msg.sender || ownerToOperators[tokenOwner][msg.sender], NOT_OWNER_OR_OPERATOR); _; } /** * @dev Guarantees that the msg.sender is allowed to transfer NFT. * @param _tokenId ID of the NFT to transfer. */ modifier canTransfer( uint256 _tokenId ) { address tokenOwner = idToOwner[_tokenId]; require( tokenOwner == msg.sender || idToApproval[_tokenId] == msg.sender || ownerToOperators[tokenOwner][msg.sender], NOT_OWNER_APPROWED_OR_OPERATOR ); _; } /** * @dev Guarantees that _tokenId is a valid Token. * @param _tokenId ID of the NFT to validate. */ modifier validNFToken( uint256 _tokenId ) { require(idToOwner[_tokenId] != address(0), NOT_VALID_NFT); _; } /** * @dev Contract constructor. */ constructor() public { supportedInterfaces[0x80ac58cd] = true; // ERC721 } /** * @dev Transfers the ownership of an NFT from one address to another address. This function can * be changed to payable. * @notice Throws unless `msg.sender` is the current owner, an authorized operator, or the * approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is * the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this * function checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. * @param _data Additional data with no specified format, sent in call to `_to`. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes calldata _data ) external override { _safeTransferFrom(_from, _to, _tokenId, _data); } /** * @dev Transfers the ownership of an NFT from one address to another address. This function can * be changed to payable. * @notice This works identically to the other function with an extra data parameter, except this * function just sets data to "" * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external override { _safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved * address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero * address. Throws if `_tokenId` is not a valid NFT. This function can be changed to payable. * @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else * they maybe be permanently lost. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function transferFrom( address _from, address _to, uint256 _tokenId ) external override canTransfer(_tokenId) validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == _from, NOT_OWNER); require(_to != address(0), ZERO_ADDRESS); _transfer(_to, _tokenId); } /** * @dev Set or reaffirm the approved address for an NFT. This function can be changed to payable. * @notice The zero address indicates there is no approved address. Throws unless `msg.sender` is * the current NFT owner, or an authorized operator of the current owner. * @param _approved Address to be approved for the given NFT ID. * @param _tokenId ID of the token to be approved. */ function approve( address _approved, uint256 _tokenId ) external override canOperate(_tokenId) validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; require(_approved != tokenOwner, IS_OWNER); idToApproval[_tokenId] = _approved; emit Approval(tokenOwner, _approved, _tokenId); } /** * @dev Enables or disables approval for a third party ("operator") to manage all of * `msg.sender`'s assets. It also emits the ApprovalForAll event. * @notice This works even if sender doesn't own any tokens at the time. * @param _operator Address to add to the set of authorized operators. * @param _approved True if the operators is approved, false to revoke approval. */ function setApprovalForAll( address _operator, bool _approved ) external override { ownerToOperators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are * considered invalid, and this function throws for queries about the zero address. * @param _owner Address for whom to query the balance. * @return Balance of _owner. */ function balanceOf( address _owner ) external override view returns (uint256) { require(_owner != address(0), ZERO_ADDRESS); return _getOwnerNFTCount(_owner); } /** * @dev Returns the address of the owner of the NFT. NFTs assigned to zero address are considered * invalid, and queries about them do throw. * @param _tokenId The identifier for an NFT. * @return _owner Address of _tokenId owner. */ function ownerOf( uint256 _tokenId ) external override view returns (address _owner) { _owner = idToOwner[_tokenId]; require(_owner != address(0), NOT_VALID_NFT); } /** * @dev Get the approved address for a single NFT. * @notice Throws if `_tokenId` is not a valid NFT. * @param _tokenId ID of the NFT to query the approval of. * @return Address that _tokenId is approved for. */ function getApproved( uint256 _tokenId ) external override view validNFToken(_tokenId) returns (address) { return idToApproval[_tokenId]; } /** * @dev Checks if `_operator` is an approved operator for `_owner`. * @param _owner The address that owns the NFTs. * @param _operator The address that acts on behalf of the owner. * @return True if approved for all, false otherwise. */ function isApprovedForAll( address _owner, address _operator ) external override view returns (bool) { return ownerToOperators[_owner][_operator]; } /** * @dev Actually preforms the transfer. * @notice Does NO checks. * @param _to Address of a new owner. * @param _tokenId The NFT that is being transferred. */ function _transfer( address _to, uint256 _tokenId ) internal { address from = idToOwner[_tokenId]; _clearApproval(_tokenId); _removeNFToken(from, _tokenId); _addNFToken(_to, _tokenId); emit Transfer(from, _to, _tokenId); } /** * @dev Mints a new NFT. * @notice This is an internal function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function _mint( address _to, uint256 _tokenId ) internal virtual { require(_to != address(0), ZERO_ADDRESS); require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); _addNFToken(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Burns a NFT. * @notice This is an internal function which should be called from user-implemented external burn * function. Its purpose is to show and properly initialize data structures when using this * implementation. Also, note that this burn implementation allows the minter to re-mint a burned * NFT. * @param _tokenId ID of the NFT to be burned. */ function _burn( uint256 _tokenId ) internal virtual validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; _clearApproval(_tokenId); _removeNFToken(tokenOwner, _tokenId); emit Transfer(tokenOwner, address(0), _tokenId); } /** * @dev Removes a NFT from owner. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from wich we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function _removeNFToken( address _from, uint256 _tokenId ) internal virtual { require(idToOwner[_tokenId] == _from, NOT_OWNER); ownerToNFTokenCount[_from] = ownerToNFTokenCount[_from] - 1; delete idToOwner[_tokenId]; } /** * @dev Assignes a new NFT to owner. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to wich we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function _addNFToken( address _to, uint256 _tokenId ) internal virtual { require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); idToOwner[_tokenId] = _to; ownerToNFTokenCount[_to] = ownerToNFTokenCount[_to].add(1); } /** * @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable * extension to remove double storage (gas optimization) of owner nft count. * @param _owner Address for whom to query the count. * @return Number of _owner NFTs. */ function _getOwnerNFTCount( address _owner ) internal virtual view returns (uint256) { return ownerToNFTokenCount[_owner]; } /** * @dev Actually perform the safeTransferFrom. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. * @param _data Additional data with no specified format, sent in call to `_to`. */ function _safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes memory _data ) private canTransfer(_tokenId) validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == _from, NOT_OWNER); require(_to != address(0), ZERO_ADDRESS); _transfer(_to, _tokenId); if (_to.isContract()) { bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data); require(retval == MAGIC_ON_ERC721_RECEIVED, NOT_ABLE_TO_RECEIVE_NFT); } } /** * @dev Clears the current approval of a given NFT ID. * @param _tokenId ID of the NFT to be transferred. */ function _clearApproval( uint256 _tokenId ) private { if (idToApproval[_tokenId] != address(0)) { delete idToApproval[_tokenId]; } } } /** * @dev Optional metadata extension for ERC-721 non-fungible token standard. * See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md. */ interface ERC721Metadata { /** * @dev Returns a descriptive name for a collection of NFTs in this contract. * @return _name Representing name. */ function name() external view returns (string memory _name); /** * @dev Returns a abbreviated name for a collection of NFTs in this contract. * @return _symbol Representing symbol. */ function symbol() external view returns (string memory _symbol); /** * @dev Returns a distinct Uniform Resource Identifier (URI) for a given asset. It Throws if * `_tokenId` is not a valid NFT. URIs are defined in RFC3986. The URI may point to a JSON file * that conforms to the "ERC721 Metadata JSON Schema". * @return URI of _tokenId. */ function tokenURI(uint256 _tokenId) external view returns (string memory); } /** * @dev Optional metadata implementation for ERC-721 non-fungible token standard. */ contract NFTokenMetadata is NFToken, ERC721Metadata { /** * @dev A descriptive name for a collection of NFTs. */ string internal nftName; /** * @dev An abbreviated name for NFTokens. */ string internal nftSymbol; /** * @dev Mapping from NFT ID to metadata uri. */ mapping (uint256 => string) internal idToUri; /** * @dev Contract constructor. * @notice When implementing this contract don't forget to set nftName and nftSymbol. */ constructor() public { supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata } /** * @dev Returns a descriptive name for a collection of NFTokens. * @return _name Representing name. */ function name() external override view returns (string memory _name) { _name = nftName; } /** * @dev Returns an abbreviated name for NFTokens. * @return _symbol Representing symbol. */ function symbol() external override view returns (string memory _symbol) { _symbol = nftSymbol; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */ function tokenURI( uint256 _tokenId ) external override view validNFToken(_tokenId) returns (string memory) { return idToUri[_tokenId]; } /** * @dev Burns a NFT. * @notice This is an internal function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. Also, note that this burn implementation allows the minter to re-mint a burned * NFT. * @param _tokenId ID of the NFT to be burned. */ function _burn( uint256 _tokenId ) internal override virtual { super._burn(_tokenId); if (bytes(idToUri[_tokenId]).length != 0) { delete idToUri[_tokenId]; } } /** * @dev Set a distinct URI (RFC 3986) for a given NFT ID. * @notice This is an internal function which should be called from user-implemented external * function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _tokenId Id for which we want URI. * @param _uri String representing RFC 3986 URI. */ function _setTokenUri( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToUri[_tokenId] = _uri; } } /** * @dev Optional enumeration extension for ERC-721 non-fungible token standard. * See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md. */ interface ERC721Enumerable { /** * @dev Returns a count of valid NFTs tracked by this contract, where each one of them has an * assigned and queryable owner not equal to the zero address. * @return Total supply of NFTs. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token identifier for the `_index`th NFT. Sort order is not specified. * @param _index A counter less than `totalSupply()`. * @return Token id. */ function tokenByIndex( uint256 _index ) external view returns (uint256); /** * @dev Returns the token identifier for the `_index`th NFT assigned to `_owner`. Sort order is * not specified. It throws if `_index` >= `balanceOf(_owner)` or if `_owner` is the zero address, * representing invalid NFTs. * @param _owner An address where we are interested in NFTs owned by them. * @param _index A counter less than `balanceOf(_owner)`. * @return Token id. */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) external view returns (uint256); } /** * @dev Optional enumeration implementation for ERC-721 non-fungible token standard. */ contract NFTokenEnumerable is NFToken, ERC721Enumerable { string constant INVALID_INDEX = "005007"; /** * @dev Array of all NFT IDs. */ uint256[] internal tokens; /** * @dev Mapping from token ID to its index in global tokens array. */ mapping(uint256 => uint256) internal idToIndex; /** * @dev Mapping from owner to list of owned NFT IDs. */ mapping(address => uint256[]) internal ownerToIds; /** * @dev Mapping from NFT ID to its index in the owner tokens list. */ mapping(uint256 => uint256) internal idToOwnerIndex; /** * @dev Contract constructor. */ constructor() public { supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable } /** * @dev Returns the count of all existing NFTokens. * @return Total supply of NFTs. */ function totalSupply() external override view returns (uint256) { return tokens.length; } /** * @dev Returns NFT ID by its index. * @param _index A counter less than `totalSupply()`. * @return Token id. */ function tokenByIndex( uint256 _index ) external override view returns (uint256) { require(_index < tokens.length, INVALID_INDEX); return tokens[_index]; } /** * @dev returns the n-th NFT ID from a list of owner's tokens. * @param _owner Token owner's address. * @param _index Index number representing n-th token in owner's list of tokens. * @return Token id. */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) external override view returns (uint256) { require(_index < ownerToIds[_owner].length, INVALID_INDEX); return ownerToIds[_owner][_index]; } /** * @dev Mints a new NFT. * @notice This is an internal function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function _mint( address _to, uint256 _tokenId ) internal override virtual { super._mint(_to, _tokenId); tokens.push(_tokenId); idToIndex[_tokenId] = tokens.length - 1; } /** * @dev Burns a NFT. * @notice This is an internal function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. Also, note that this burn implementation allows the minter to re-mint a burned * NFT. * @param _tokenId ID of the NFT to be burned. */ function _burn( uint256 _tokenId ) internal override virtual { super._burn(_tokenId); uint256 tokenIndex = idToIndex[_tokenId]; uint256 lastTokenIndex = tokens.length - 1; uint256 lastToken = tokens[lastTokenIndex]; tokens[tokenIndex] = lastToken; tokens.pop(); // This wastes gas if you are burning the last token but saves a little gas if you are not. idToIndex[lastToken] = tokenIndex; idToIndex[_tokenId] = 0; } /** * @dev Removes a NFT from an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from wich we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function _removeNFToken( address _from, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == _from, NOT_OWNER); delete idToOwner[_tokenId]; uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId]; uint256 lastTokenIndex = ownerToIds[_from].length - 1; if (lastTokenIndex != tokenToRemoveIndex) { uint256 lastToken = ownerToIds[_from][lastTokenIndex]; ownerToIds[_from][tokenToRemoveIndex] = lastToken; idToOwnerIndex[lastToken] = tokenToRemoveIndex; } ownerToIds[_from].pop(); } /** * @dev Assignes a new NFT to an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to wich we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function _addNFToken( address _to, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); idToOwner[_tokenId] = _to; ownerToIds[_to].push(_tokenId); idToOwnerIndex[_tokenId] = ownerToIds[_to].length - 1; } /** * @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable * extension to remove double storage(gas optimization) of owner nft count. * @param _owner Address for whom to query the count. * @return Number of _owner NFTs. */ function _getOwnerNFTCount( address _owner ) internal override virtual view returns (uint256) { return ownerToIds[_owner].length; } } /** * @dev The contract has an owner address, and provides basic authorization control which * simplifies the implementation of user permissions. */ contract Ownable { /** * @dev Error constants. */ string public constant NOT_CURRENT_OWNER = "018001"; string public constant CANNOT_TRANSFER_TO_ZERO_ADDRESS = "018002"; /** * @dev Current owner address. */ address public owner; /** * @dev An event which is triggered when the owner is changed. * @param previousOwner The address of the previous owner. * @param newOwner The address of the new owner. */ event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The 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, NOT_CURRENT_OWNER); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership( address _newOwner ) public onlyOwner { require(_newOwner != address(0), CANNOT_TRANSFER_TO_ZERO_ADDRESS); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } interface IMintable { function mintFor( address to, uint256 id, bytes calldata blueprint ) external; } library Bytes { /** * @dev Converts a `uint256` to a `string`. * via OraclizeAPI - MIT licence * https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol */ function fromUint(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + (temp % 10))); temp /= 10; } return string(buffer); } bytes constant alphabet = "0123456789abcdef"; /** * Index Of * * Locates and returns the position of a character within a string starting * from a defined offset * * @param _base When being used for a data type this is the extended object * otherwise this is the string acting as the haystack to be * searched * @param _value The needle to search for, at present this is currently * limited to one character * @param _offset The starting point to start searching from which can start * from 0, but must not exceed the length of the string * @return int The position of the needle starting from 0 and returning -1 * in the case of no matches found */ function indexOf( bytes memory _base, string memory _value, uint256 _offset ) internal pure returns (int256) { bytes memory _valueBytes = bytes(_value); assert(_valueBytes.length == 1); for (uint256 i = _offset; i < _base.length; i++) { if (_base[i] == _valueBytes[0]) { return int256(i); } } return -1; } function substring( bytes memory strBytes, uint256 startIndex, uint256 endIndex ) internal pure returns (string memory) { bytes memory result = new bytes(endIndex - startIndex); for (uint256 i = startIndex; i < endIndex; i++) { result[i - startIndex] = strBytes[i]; } return string(result); } function toUint(bytes memory b) internal pure returns (uint256) { uint256 result = 0; for (uint256 i = 0; i < b.length; i++) { uint256 val = uint256(uint8(b[i])); if (val >= 48 && val <= 57) { result = result * 10 + (val - 48); } } return result; } } library Minting { // Split the minting blob into token_id and blueprint portions // {token_id}:{blueprint} function split(bytes calldata blob) internal pure returns (uint256, bytes memory) { int256 index = Bytes.indexOf(blob, ":", 0); require(index >= 0, "Separator must exist"); // Trim the { and } from the parameters uint256 tokenID = Bytes.toUint(blob[1:uint256(index) - 1]); uint256 blueprintLength = blob.length - uint256(index) - 3; if (blueprintLength == 0) { return (tokenID, bytes("")); } bytes calldata blueprint = blob[uint256(index) + 2:blob.length - 1]; return (tokenID, blueprint); } } abstract contract Mintable is Ownable, IMintable { address public imx; mapping(uint256 => bytes) public blueprints; event AssetMinted(address to, uint256 id, bytes blueprint); constructor(address _owner, address _imx) { imx = _imx; require(_owner != address(0), "Owner must not be empty"); transferOwnership(_owner); } modifier onlyIMX() { require(msg.sender == imx, "Function can only be called by IMX"); _; } function mintFor( address user, uint256 quantity, bytes calldata mintingBlob ) external override onlyIMX { require(quantity == 1, "Mintable: invalid quantity"); (uint256 id, bytes memory blueprint) = Minting.split(mintingBlob); _mintFor(user, id, blueprint); blueprints[id] = blueprint; emit AssetMinted(user, id, blueprint); } function _mintFor( address to, uint256 id, bytes memory blueprint ) internal virtual; } contract ArtGalleryTokenImx is NFTokenEnumerable, NFTokenMetadata, Ownable, Mintable { /** * Immutable support */ /** * @dev Contract constructor. Sets metadata extension `name` and `symbol`. * @param _imx immutable contract address */ constructor(address _imx) public Mintable(msg.sender, _imx) { nftName = "ArtGallery"; nftSymbol = "ArtGallery"; publisher = msg.sender; //publisher == owner == contract deployer _own_address = address(this); } /** * @dev mint implementation * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. * @param _uri String representing RFC 3986 URI. */ function __mint( address _to, uint256 _tokenId, string memory _uri ) internal { super._mint(_to, _tokenId); super._setTokenUri(_tokenId, _uri); } /** * @dev internal mint function to be called from mintFor called by immutable contract * @param to address that will own the minted NFT * @param id token id of the NFT to be minted. * @param blueprint bytes representing NFT uri string. */ function _mintFor( address to, uint256 id, bytes memory blueprint ) internal override { string memory uri = string(blueprint); __mint(to, id, uri); } /** * ArtGalleryToken */ address public _own_address; address publisher = 0x0000000000000000000000000000000000000000; address bankContract = 0x0000000000000000000000000000000000000000; modifier bankOrPublisher() { require( (msg.sender == publisher) || (msg.sender == bankContract && isContract(msg.sender)), "only bank or publisher can call this function" ); _; } modifier onlyPublisher() { require( msg.sender == publisher, "only publisher can call this function" ); _; } modifier onlyBankContract() { require( msg.sender == bankContract && isContract(msg.sender), "only bank can call this function" ); _; } /** * @dev not bullet-proof check, but additional measure, actually we require specific (contract) address, * which is key (see onlyBankContract) */ function isContract(address _addr) internal view returns (bool) { uint32 size; assembly { size := extcodesize(_addr) } return (size > 0); } /** * @dev only to be used if you do not have minted tokens, * i.e. what to change name& symbol for cotnract without assets * all minted tokens will disappear */ function setNFTName(string calldata new_name) external onlyOwner { nftName = new_name; } /** * @dev only to be used if you do not have minted tokens, * i.e. what to change name& symbol for cotnract without assets * all minted tokens will disappear */ function setNFTSymbol(string calldata new_symbol) external onlyOwner { nftSymbol = new_symbol; } function transferPublishRight(address newPublisher) external onlyOwner { publisher = newPublisher; } function getPublisher() public view returns (address) { return publisher; } function transferBankRight(address newBankContract) external onlyOwner { bankContract = newBankContract; } function getBankContract() public view returns (address) { return bankContract; } /** * @dev returns contract balance */ function getContractBalance() public view returns (uint256) { return address(this).balance; } /** * @dev Mints a new NFT. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. * @param _uri String representing RFC 3986 URI. */ function mint( address _to, uint256 _tokenId, string calldata _uri ) external bankOrPublisher { __mint(_to, _tokenId, _uri); } /** * @dev Removes a NFT from owner. * @param _tokenId Which NFT we want to remove. */ function burn(uint256 _tokenId) external bankOrPublisher { super._burn(_tokenId); } /** * @dev Mints a new NFT. * @notice This is an internal function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function _mint(address _to, uint256 _tokenId) internal virtual override(NFToken, NFTokenEnumerable) { NFTokenEnumerable._mint(_to, _tokenId); } /** * @dev Burns a NFT. * @notice This is an internal function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. Also, note that this burn implementation allows the minter to re-mint a burned * NFT. * @param _tokenId ID of the NFT to be burned. */ function _burn(uint256 _tokenId) internal virtual override(NFTokenMetadata, NFTokenEnumerable) { NFTokenEnumerable._burn(_tokenId); if (bytes(idToUri[_tokenId]).length != 0) { delete idToUri[_tokenId]; } } /** * @dev Removes a NFT from an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from wich we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function _removeNFToken(address _from, uint256 _tokenId) internal override(NFToken, NFTokenEnumerable) { NFTokenEnumerable._removeNFToken(_from, _tokenId); } /** * @dev Assigns a new NFT to an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to wich we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function _addNFToken(address _to, uint256 _tokenId) internal override(NFToken, NFTokenEnumerable) { NFTokenEnumerable._addNFToken(_to, _tokenId); } /** * @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable * extension to remove double storage(gas optimization) of owner nft count. * @param _owner Address for whom to query the count. * @return Number of _owner NFTs. */ function _getOwnerNFTCount(address _owner) internal view override(NFToken, NFTokenEnumerable) returns (uint256) { return NFTokenEnumerable._getOwnerNFTCount(_owner); } }
* @dev Mints a new NFT. @param _to The address that will own the minted NFT. @param _tokenId of the NFT to be minted by the msg.sender. @param _uri String representing RFC 3986 URI./
function mint( address _to, uint256 _tokenId, string calldata _uri ) external bankOrPublisher { __mint(_to, _tokenId, _uri); }
10,392,923
[ 1, 49, 28142, 279, 394, 423, 4464, 18, 225, 389, 869, 1021, 1758, 716, 903, 4953, 326, 312, 474, 329, 423, 4464, 18, 225, 389, 2316, 548, 434, 326, 423, 4464, 358, 506, 312, 474, 329, 635, 326, 1234, 18, 15330, 18, 225, 389, 1650, 514, 5123, 8372, 16977, 5292, 3699, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 12, 203, 3639, 1758, 389, 869, 16, 203, 3639, 2254, 5034, 389, 2316, 548, 16, 203, 3639, 533, 745, 892, 389, 1650, 203, 565, 262, 3903, 11218, 1162, 15960, 288, 203, 3639, 1001, 81, 474, 24899, 869, 16, 389, 2316, 548, 16, 389, 1650, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x22ab062319E037F11e8aD8996f3aB24241a3a2C3/sources/bookie-web/BEP20.sol
* @dev Implementation of the {IBEP20} 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 {BEP20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of BEP20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IBEP20-approve}./
contract BEP20 is Context, IBEP20, IBEP20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public view virtual override returns (uint8) { return 18; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "BEP20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "BEP20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "BEP20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "BEP20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "BEP20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "BEP20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "BEP20: approve from the zero address"); require(spender != address(0), "BEP20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
14,138,022
[ 1, 13621, 434, 326, 288, 45, 5948, 52, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 5948, 52, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 9875, 14567, 30, 4186, 15226, 3560, 434, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 9722, 52, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 9722, 52, 3462, 353, 1772, 16, 467, 5948, 52, 3462, 16, 467, 5948, 52, 3462, 2277, 288, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 377, 203, 203, 203, 565, 3885, 261, 1080, 3778, 508, 67, 16, 533, 3778, 3273, 67, 13, 288, 203, 3639, 389, 529, 273, 508, 67, 31, 203, 3639, 389, 7175, 273, 3273, 67, 31, 203, 3639, 203, 565, 289, 203, 377, 203, 203, 565, 445, 508, 1435, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 203, 203, 565, 445, 3273, 1435, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 7175, 31, 203, 565, 289, 203, 203, 565, 445, 15105, 1435, 1071, 1476, 5024, 3849, 1135, 261, 11890, 28, 13, 288, 203, 3639, 327, 6549, 31, 203, 565, 289, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 31, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 70, 26488, 63, 4631, 15533, 203, 565, 289, 2 ]
./partial_match/1/0x593ff4a3ceB558a7645462E02C5898A5E32bA5eF/sources/RouletteNodeProtocol.sol
sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(_uniPair);
15,939,545
[ 1, 8389, 6205, 3241, 333, 353, 486, 316, 279, 7720, 2492, 5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 467, 984, 291, 91, 438, 58, 22, 4154, 3082, 273, 467, 984, 291, 91, 438, 58, 22, 4154, 24899, 318, 77, 4154, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: contracts\Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts\IERC165.sol pragma solidity ^0.5.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\IERC721.sol pragma solidity ^0.5.0; /** * @dev Required interface of an ERC721 compliant contract. */ 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); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) public view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) public; 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 safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } // File: contracts\IERC721Receiver.sol pragma solidity ^0.5.0; /** * @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 {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } // File: contracts\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: contracts\Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * IMPORTANT: It is unsafe to assume that an address for which this * function returns false is an externally-owned account (EOA) and not a * contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: contracts\Counters.sol pragma solidity ^0.5.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // File: contracts\ERC165.sol pragma solidity ^0.5.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view 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 { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: contracts\ERC721.sol pragma solidity ^0.5.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // 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 => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; 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), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @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, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param 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 != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][to] = approved; emit ApprovalForAll(_msgSender(), to, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * 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 { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _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 {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransferFrom(from, to, tokenId, _data); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal { _transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { 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) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _safeMint(address to, uint256 tokenId) internal { _safeMint(to, tokenId, ""); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted * @param _data bytes data to send along with a safe transfer check */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {_burn} 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, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _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, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, 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. * * This function is deprecated. * @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) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(_msgSender(), 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); } } } // File: contracts\IERC721Enumerable.sol pragma solidity ^0.5.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Enumerable is IERC721 { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId); function tokenByIndex(uint256 index) public view returns (uint256); } // File: contracts\ERC721Enumerable.sol pragma solidity ^0.5.0; /** * @title ERC-721 Non-Fungible Token with optional enumeration extension logic * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // 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; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Constructor function. */ constructor () public { // register the supported interface to conform to ERC721Enumerable via ERC165 _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens. * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @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 { super._transferFrom(from, to, tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); _addTokenToOwnerEnumeration(to, tokenId); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _addTokenToOwnerEnumeration(to, tokenId); _addTokenToAllTokensEnumeration(tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {ERC721-_burn} 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 { super._burn(owner, tokenId); _removeTokenFromOwnerEnumeration(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _removeTokenFromAllTokensEnumeration(tokenId); } /** * @dev Gets the list of token IDs of the requested owner. * @param owner address owning the tokens * @return uint256[] List of token IDs owned by the requested address */ function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; } /** * @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 { _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } /** * @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 = _ownedTokens[from].length.sub(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 _ownedTokens[from].length--; // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by // lastTokenId, or just over the end of the array if the token was the last one). } /** * @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.sub(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 _allTokens.length--; _allTokensIndex[tokenId] = 0; } } // File: contracts\IERC721Metadata.sol pragma solidity ^0.5.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } // File: contracts\ERC721Metadata.sol pragma solidity ^0.5.0; contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /** * @dev Constructor function */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721_METADATA); } /** * @dev Gets the token name. * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return _tokenURIs[tokenId]; } /** * @dev Internal function to set the token URI for a given token. * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string memory uri) internal { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = uri; } /** * @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 by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // File: contracts\ERC721Full.sol pragma solidity ^0.5.0; /** * @title Full ERC721 Token * @dev This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology. * * See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata { constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) { // solhint-disable-previous-line no-empty-blocks } } // File: contracts\Roles.sol pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: contracts\MinterRole.sol pragma solidity ^0.5.0; contract MinterRole is Context { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(_msgSender()); } modifier onlyMinter() { require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(_msgSender()); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } // File: contracts\ERC721MetadataMintable.sol pragma solidity ^0.5.0; /** * @title ERC721MetadataMintable * @dev ERC721 minting logic with metadata. */ contract ERC721MetadataMintable is ERC721, ERC721Metadata, MinterRole { /** * @dev Function to mint tokens. * @param to The address that will receive the minted tokens. * @param tokenId The token id to mint. * @param tokenURI The token URI of the minted token. * @return A boolean that indicates if the operation was successful. */ function mintWithTokenURI(address to, uint256 tokenId, string memory tokenURI) public onlyMinter returns (bool) { _mint(to, tokenId); _setTokenURI(tokenId, tokenURI); return true; } } // File: contracts\SmirriauNFTContracts.sol //Smirriau NFT Token ERC 721 & Marketplace for sale and minting //2021 WikiCode - José Miguel López Salvador pragma solidity ^0.5.0; //Import the OpenZeppeling contracts //Smirriau Token //This is the ERC721 personalized token for Smirriau NFT //This contract has a limit of 5000 tokens contract SmirriauToken is ERC721Full, ERC721MetadataMintable { //Set a constant with the limit of minting uint256 constant maxCounter = 5000; //The constructor to set the name and symbol constructor () public ERC721Full("SmirriauNft","SMR") { } //This function is used to mint a token cheking first the limit of the total supply. function createSmirriau (address nftOwner, uint256 tokenId, string memory tokenURI) public returns(bool) { require (totalSupply()<maxCounter,"Max minted SMR reached"); assert(mintWithTokenURI(nftOwner, tokenId, tokenURI)); return true; } } //Smirriau Market //This contract will be a minter of Smirriau Token and it is used for sell the original tokens in the website. contract SmirriauMarket { using SafeMath for uint256; //The token contract SmirriauToken public smirriauToken; //The address which will receive the payments address payable private destEthers; //A total collected uint256 public totalCollected; //The token price uint256 public tokenPrice; //The controller of this contract address public controller; //A list of minted index mapping (uint256 => bool) public minted; //Another list of minted index uint256[] public mintedList; //Constructor constructor () public { //Set the total collected in 0 totalCollected = 0; //Set the publisher of the contract as a controller controller = msg.sender; } //The modifier for only controller modifier onlyController() { require (msg.sender == controller, "Must be controller"); _; } //This function check if the token is available or not function isTokenAvailableByIndex(uint256 index) public view returns(bool){ bool available = true; if (minted[index]==true){ available = false; } return available; } //Return all the minted indexes function getMintedList() public view returns(uint256 [] memory){ return mintedList; } //Get the balance of this contract function getBalance() public onlyController view returns(uint256) { return address(this).balance; } //Withdraw if there is some ETH in the contract function withdrawBalance() public onlyController { require(address(this).balance > 0, "Balance 0"); destEthers.transfer(address(this).balance); } //Initialize the market with the information of the token address, price and address for payments. function initialize (address _token, address payable _destEth, uint256 _tokenPrice) public onlyController { address tokenAddress = address(smirriauToken); require(tokenAddress==0x0000000000000000000000000000000000000000, "The smirriauToken already exists"); smirriauToken = SmirriauToken(_token); require(smirriauToken.totalSupply() == 0, "There are some tokens in the contract"); require(smirriauToken.isMinter(address(this))== true, "This address has not the correct roles"); tokenPrice = _tokenPrice; destEthers = _destEth; } //Change the address for payments function setDestEthers (address payable _destEth) public onlyController { destEthers = _destEth; } //Get the address for payments function getDestEthers () public onlyController view returns(address) { return destEthers; } //This is used to mint a new Smirriau by index and its tokenURI function buyNewSmirriau(string memory tokenURI, uint256 _index) public payable returns(uint256) { uint256 buyPrice = tokenPrice; //50% Frst 100 NFTs if(totalCollected<100) { buyPrice = tokenPrice/2; } require(msg.value >= buyPrice, "Not enouth ETH to buy"); require(isTokenAvailableByIndex(_index) == true , "Token not available"); address buyer = msg.sender; // uint256 index = tokenIndex++; assert(smirriauToken.createSmirriau(buyer, _index, tokenURI)); destEthers.transfer(buyPrice); if (msg.value>buyPrice) { msg.sender.transfer(msg.value.sub(buyPrice)); } minted[_index] = true; mintedList.push(_index); totalCollected++; return _index; } }
Return all the minted indexes
function getMintedList() public view returns(uint256 [] memory){ return mintedList; }
276,007
[ 1, 990, 777, 326, 312, 474, 329, 5596, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2108, 474, 18073, 1435, 1071, 1476, 1135, 12, 11890, 5034, 5378, 3778, 15329, 203, 3639, 327, 312, 474, 18073, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xc1991bF5359f0BCe4f936e718353b07DeE97DaBa/sources/contracts/Kingdomly Shitcoins/GenericShitcoinETH(test).sol
Nuke function for testing so that I can get GoEth back ... Remove liquidity; get ETH and Tokens in return We now have ETH and Tokens in the contract. Swap Tokens for more ETHSend ETH to fee wallet
function KABOOM() external onlyOwner { uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uint256 lpBalance = IERC20(uniswapV2Pair).balanceOf(address(this)); if (lpBalance > 0) { IERC20(uniswapV2Pair).approve(address(uniswapV2Router), lpBalance); (uint256 amountToken, uint256 amountETH) = uniswapV2Router.removeLiquidityETH( address(this), lpBalance, 0, 0, address(this), block.timestamp ); address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), amountToken); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( amountToken, 0, path, address(this), block.timestamp ); sendETHToFee(address(this).balance); } }
1,870,448
[ 1, 50, 89, 4491, 445, 364, 7769, 1427, 716, 467, 848, 336, 4220, 41, 451, 1473, 1372, 3581, 4501, 372, 24237, 31, 336, 512, 2455, 471, 13899, 316, 327, 1660, 2037, 1240, 512, 2455, 471, 13899, 316, 326, 6835, 18, 12738, 13899, 364, 1898, 512, 2455, 3826, 512, 2455, 358, 14036, 9230, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1475, 2090, 51, 1872, 1435, 3903, 1338, 5541, 288, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 20, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 1769, 203, 3639, 2254, 5034, 12423, 13937, 273, 467, 654, 39, 3462, 12, 318, 291, 91, 438, 58, 22, 4154, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 9953, 13937, 405, 374, 13, 288, 203, 5411, 467, 654, 39, 3462, 12, 318, 291, 91, 438, 58, 22, 4154, 2934, 12908, 537, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 8259, 3631, 12423, 13937, 1769, 203, 5411, 261, 11890, 5034, 3844, 1345, 16, 2254, 5034, 3844, 1584, 44, 13, 273, 640, 291, 91, 438, 58, 22, 8259, 18, 4479, 48, 18988, 24237, 1584, 44, 12, 203, 7734, 1758, 12, 2211, 3631, 203, 7734, 12423, 13937, 16, 203, 7734, 374, 16, 203, 7734, 374, 16, 203, 7734, 1758, 12, 2211, 3631, 203, 7734, 1203, 18, 5508, 203, 5411, 11272, 203, 5411, 1758, 8526, 3778, 589, 273, 394, 1758, 8526, 12, 22, 1769, 203, 5411, 589, 63, 20, 65, 273, 1758, 12, 2211, 1769, 203, 5411, 589, 63, 21, 65, 273, 640, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 5621, 203, 5411, 389, 12908, 537, 12, 2867, 12, 2211, 3631, 1758, 12, 318, 291, 91, 438, 2 ]
pragma solidity 0.4.19; contract Ownable { address public owner; /** * The address whcih deploys this contrcat is automatically assgined ownership. * */ function Ownable() public { owner = msg.sender; } /** * Functions with this modifier can only be executed by the owner of the contract. * */ modifier onlyOwner { require(msg.sender == owner); _; } event OwnershipTransferred(address indexed from, address indexed to); /** * Transfers ownership to new Ethereum address. This function can only be called by the * owner. * @param _newOwner the address to be granted ownership. **/ function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != 0x0); OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20TransferInterface { function transfer(address to, uint256 value) public returns (bool); function balanceOf(address who) constant public returns (uint256); } contract ICO is Ownable { using SafeMath for uint256; event TokenAddressSet(address indexed tokenAddress); event FirstPreIcoActivated(uint256 startTime, uint256 endTime, uint256 bonus); event SecondPreIcoActivated(uint256 startTime, uint256 endTime, uint256 bonus); event MainIcoActivated(uint256 startTime, uint256 endTime, uint256 bonus); event TokenPriceChanged(uint256 newTokenPrice, uint256 newExchangeRate); event ExchangeRateChanged(uint256 newExchangeRate, uint256 newTokenPrice); event BonuseChanged(uint256 newBonus); event OffchainPurchaseMade(address indexed recipient, uint256 tokensPurchased); event TokensPurchased(address indexed recipient, uint256 tokensPurchased, uint256 weiSent); event UnsoldTokensWithdrawn(uint256 tokensWithdrawn); event ICOPaused(uint256 timeOfPause); event ICOUnpaused(uint256 timeOfUnpause); event IcoDeadlineExtended(State currentState, uint256 newDeadline); event IcoDeadlineShortened(State currentState, uint256 newDeadline); event IcoTerminated(uint256 terminationTime); event AirdropInvoked(); uint256 public endTime; uint256 private pausedTime; bool public IcoPaused; uint256 public tokenPrice; uint256 public rate; uint256 public bonus; uint256 public minInvestment; ERC20TransferInterface public MSTCOIN; address public multiSigWallet; uint256 public tokensSold; mapping (address => uint256) public investmentOf; enum State {FIRST_PRE_ICO, SECOND_PRE_ICO, MAIN_ICO, TERMINATED} State public icoState; uint256[4] public mainIcoBonusStages; function ICO() public { endTime = now.add(7 days); pausedTime = 0; IcoPaused = false; tokenPrice = 89e12; // tokenPrice is rate / 1e18 rate = 11235; // rate is 1e18 / tokenPrice bonus = 100; minInvestment = 1e17; multiSigWallet = 0xE1377e465121776d8810007576034c7E0798CD46; tokensSold = 0; icoState = State.FIRST_PRE_ICO; FirstPreIcoActivated(now, endTime, bonus); } /** * Sets the address of the token. This function can only be executed by the * owner of the contract. **/ function setTokenAddress(address _tokenAddress) public onlyOwner { require(_tokenAddress != 0x0); MSTCOIN = ERC20TransferInterface(_tokenAddress); TokenAddressSet(_tokenAddress); } /** * Returns the address of the token. **/ function getTokenAddress() public view returns(address) { return address(MSTCOIN); } /** * Allows the owner to activate the second pre ICO. This function can only be * executed once the first pre ICO has finished. **/ function activateSecondPreIco() public onlyOwner { require(now >= endTime && icoState == State.FIRST_PRE_ICO); icoState = State.SECOND_PRE_ICO; endTime = now.add(4 days); bonus = 50; SecondPreIcoActivated(now, endTime, bonus); } /** * Allows the owner to activate the main public ICO stage. This function can only be * executed once the second pre ICO has finished. **/ function activateMainIco() public onlyOwner { require(now >= endTime && icoState == State.SECOND_PRE_ICO); icoState = State.MAIN_ICO; mainIcoBonusStages[0] = now.add(7 days); mainIcoBonusStages[1] = now.add(14 days); mainIcoBonusStages[2] = now.add(21 days); mainIcoBonusStages[3] = now.add(31 days); endTime = now.add(31 days); bonus = 35; MainIcoActivated(now, endTime, bonus); } /** * Allows the owner to change the price of the token. * * @param _newTokenPrice The new price per token. **/ function changeTokenPrice(uint256 _newTokenPrice) public onlyOwner { require(tokenPrice != _newTokenPrice && _newTokenPrice > 0); tokenPrice = _newTokenPrice; uint256 eth = 1e18; rate = eth.div(tokenPrice); TokenPriceChanged(tokenPrice, rate); } /** * Allows the owner to change the exchange rate of the token. * * @param _newRate The new exchange rate **/ function changeRate(uint256 _newRate) public onlyOwner { require(rate != _newRate && _newRate > 0); rate = _newRate; uint256 x = 1e12; tokenPrice = x.div(rate); ExchangeRateChanged(rate, tokenPrice); } /** * Allows the owner to change the bonus of the current ICO stage. * * @param _newBonus The new bonus percentage investors will receive. **/ function changeBonus(uint256 _newBonus) public onlyOwner { require(bonus != _newBonus && _newBonus > 0); bonus = _newBonus; BonuseChanged(bonus); } /** * Allows the owner to sell tokens with other forms of payment including fiat and all other * cryptos. * * @param _recipient The address to send tokens to. * @param _value The amount of tokens to be sent. **/ function processOffchainTokenPurchase(address _recipient, uint256 _value) public onlyOwner { require(MSTCOIN.balanceOf(address(this)) >= _value); require(_recipient != 0x0 && _value > 0); MSTCOIN.transfer(_recipient, _value); tokensSold = tokensSold.add(_value); OffchainPurchaseMade(_recipient, _value); } /** * Fallback function calls the buyTokens function automatically when an investment is made. **/ function() public payable { buyTokens(msg.sender); } /** * Allows investors to send their ETH and automatically receive tokens in return. * * @param _recipient The addrewss which will receive tokens **/ function buyTokens(address _recipient) public payable { uint256 msgVal = msg.value.div(1e12); //because token has 6 decimals require(MSTCOIN.balanceOf(address(this)) >= msgVal.mul(rate.mul(getBonus()).div(100)).add(rate) ) ; require(msg.value >= minInvestment && withinPeriod()); require(_recipient != 0x0); uint256 toTransfer = msgVal.mul(rate.mul(getBonus()).div(100).add(rate)); MSTCOIN.transfer(_recipient, toTransfer); tokensSold = tokensSold.add(toTransfer); investmentOf[msg.sender] = investmentOf[msg.sender].add(msg.value); TokensPurchased(_recipient, toTransfer, msg.value); forwardFunds(); } /** * This function is internally called by the buyTokens function to automatically forward * all investments made to the multi signature wallet. **/ function forwardFunds() internal { multiSigWallet.transfer(msg.value); } /** * This function is internally called by the buyTokens function to ensure that investments * are made during times when the ICO is not paused and when the duration of the current * phase has not finished. **/ function withinPeriod() internal view returns(bool) { return IcoPaused == false && now < endTime && icoState != State.TERMINATED; } /** * Calculates and returns the bonus of the current ICO stage. During the main public ICO, the * first ICO the bonus stages are set as such: * * week 1: bonus = 35% * week 2: bonus = 25% * week 3: bonus = 15% * week 4: bonus = 5% **/ function getBonus() public view returns(uint256 _bonus) { _bonus = bonus; if(icoState == State.MAIN_ICO) { if(now > mainIcoBonusStages[3]) { _bonus = 0; } else { uint256 timeStamp = now; for(uint i = 0; i < mainIcoBonusStages.length; i++) { if(timeStamp <= mainIcoBonusStages[i]) { break; } else { if(_bonus >= 15) { _bonus = _bonus.sub(10); } } } } } return _bonus; } /** * Allows the owner of the contract to withdraw all unsold tokens. This function can * only be executed once the ICO contract has been terminated after the main public * ICO has finished. * * @param _recipient The address to withdraw all unsold tokens to. If this field is * left empty, then the tokens will just be sent to the owner of the contract. **/ function withdrawUnsoldTokens(address _recipient) public onlyOwner { require(icoState == State.TERMINATED); require(now >= endTime && MSTCOIN.balanceOf(address(this)) > 0); if(_recipient == 0x0) { _recipient = owner; } UnsoldTokensWithdrawn(MSTCOIN.balanceOf(address(this))); MSTCOIN.transfer(_recipient, MSTCOIN.balanceOf(address(this))); } /** * Allows the owner to pause the ICO contract. While the ICO is paused investments cannot * be made. **/ function pauseICO() public onlyOwner { require(!IcoPaused); IcoPaused = true; pausedTime = now; ICOPaused(now); } /** * Allows the owner to unpause the ICO only when the ICO contract has been paused. Once * invoked, the deadline will automatically be extended by the duration the ICO was * paused for. **/ function unpauseICO() public onlyOwner { require(IcoPaused); IcoPaused = false; endTime = endTime.add(now.sub(pausedTime)); ICOUnpaused(now); } /** * Allows the owner of the ICO to extend the deadline of the current ICO stage. This * function can only be executed if the ICO contract has not been terminated. * * @param _days The number of days to increase the duration of the ICO by. **/ function extendDeadline(uint256 _days) public onlyOwner { require(icoState != State.TERMINATED); endTime = endTime.add(_days.mul(1 days)); if(icoState == State.MAIN_ICO) { uint256 blocks = 0; uint256 stage = 0; for(uint i = 0; i < mainIcoBonusStages.length; i++) { if(now < mainIcoBonusStages[i]) { stage = i; } } blocks = (_days.mul(1 days)).div(mainIcoBonusStages.length.sub(stage)); for(uint x = stage; x < mainIcoBonusStages.length; x++) { mainIcoBonusStages[x] = mainIcoBonusStages[x].add(blocks); } } IcoDeadlineExtended(icoState, endTime); } /** * Allows the owner of the contract to shorten the deadline of the current ICO stage. * * @param _days The number of days to reduce the druation of the ICO by. **/ function shortenDeadline(uint256 _days) public onlyOwner { if(now.add(_days.mul(1 days)) >= endTime) { revert(); } else { endTime = endTime.sub(_days.mul(1 days)); if(icoState == State.MAIN_ICO) { uint256 blocks = 0; uint256 stage = 0; for(uint i = 0; i < mainIcoBonusStages.length; i++) { if(now < mainIcoBonusStages[i]) { stage = i; } } blocks = (_days.mul(1 days)).div(mainIcoBonusStages.length.sub(stage)); for(uint x = stage; x < mainIcoBonusStages.length; x++) { mainIcoBonusStages[x] = mainIcoBonusStages[x].sub(blocks); } } } IcoDeadlineShortened(icoState, endTime); } /** * Terminates the ICO early permanently. This function can only be called by the * owner of the contract during the main public ICO. **/ function terminateIco() public onlyOwner { require(icoState == State.MAIN_ICO); require(now < endTime); endTime = now; icoState = State.TERMINATED; IcoTerminated(now); } /** * Returns the amount of tokens that have been sold. **/ function getTokensSold() public view returns(uint256) { return tokensSold; } /** * Airdrops tokens to up to 100 ETH addresses. * * @param _addrs The list of addresses to send tokens to * @param _values The list of amounts of tokens to send to each corresponding address. **/ function airdrop(address[] _addrs, uint256[] _values) public onlyOwner returns(bool) { require(_addrs.length == _values.length && _addrs.length <= 100); require(MSTCOIN.balanceOf(address(this)) >= getSumOfValues(_values)); for (uint i = 0; i < _addrs.length; i++) { if (_addrs[i] != 0x0 && _values[i] > 0) { MSTCOIN.transfer(_addrs[i], _values[i]); } } AirdropInvoked(); return true; } /** * Called internally by the airdrop function to ensure the contract holds enough tokens * to succesfully execute the airdrop. * * @param _values The list of values representing the amount of tokens which will be airdroped. **/ function getSumOfValues(uint256[] _values) internal pure returns(uint256) { uint256 sum = 0; for(uint i=0; i < _values.length; i++) { sum = sum.add(_values[i]); } return sum; } }
* Allows the owner of the contract to shorten the deadline of the current ICO stage. @param _days The number of days to reduce the druation of the ICO by./
function shortenDeadline(uint256 _days) public onlyOwner { if(now.add(_days.mul(1 days)) >= endTime) { revert(); endTime = endTime.sub(_days.mul(1 days)); if(icoState == State.MAIN_ICO) { uint256 blocks = 0; uint256 stage = 0; for(uint i = 0; i < mainIcoBonusStages.length; i++) { if(now < mainIcoBonusStages[i]) { stage = i; } } blocks = (_days.mul(1 days)).div(mainIcoBonusStages.length.sub(stage)); for(uint x = stage; x < mainIcoBonusStages.length; x++) { mainIcoBonusStages[x] = mainIcoBonusStages[x].sub(blocks); } } } IcoDeadlineShortened(icoState, endTime); }
10,280,913
[ 1, 19132, 326, 3410, 434, 326, 6835, 358, 19651, 326, 14096, 434, 326, 783, 467, 3865, 6009, 18, 225, 389, 9810, 1021, 1300, 434, 4681, 358, 5459, 326, 5081, 11407, 434, 326, 467, 3865, 635, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 19651, 15839, 12, 11890, 5034, 389, 9810, 13, 1071, 1338, 5541, 288, 203, 3639, 309, 12, 3338, 18, 1289, 24899, 9810, 18, 16411, 12, 21, 4681, 3719, 1545, 13859, 13, 288, 203, 5411, 15226, 5621, 203, 5411, 13859, 273, 13859, 18, 1717, 24899, 9810, 18, 16411, 12, 21, 4681, 10019, 203, 5411, 309, 12, 10764, 1119, 422, 3287, 18, 19803, 67, 2871, 51, 13, 288, 203, 7734, 2254, 5034, 4398, 273, 374, 31, 203, 7734, 2254, 5034, 6009, 273, 374, 31, 203, 7734, 364, 12, 11890, 277, 273, 374, 31, 277, 411, 2774, 45, 2894, 38, 22889, 31359, 18, 2469, 31, 277, 27245, 288, 203, 10792, 309, 12, 3338, 411, 2774, 45, 2894, 38, 22889, 31359, 63, 77, 5717, 288, 203, 13491, 6009, 273, 277, 31, 203, 10792, 289, 203, 7734, 289, 203, 7734, 4398, 273, 261, 67, 9810, 18, 16411, 12, 21, 4681, 13, 2934, 2892, 12, 5254, 45, 2894, 38, 22889, 31359, 18, 2469, 18, 1717, 12, 12869, 10019, 203, 7734, 364, 12, 11890, 619, 273, 6009, 31, 619, 411, 2774, 45, 2894, 38, 22889, 31359, 18, 2469, 31, 619, 27245, 288, 203, 10792, 2774, 45, 2894, 38, 22889, 31359, 63, 92, 65, 273, 2774, 45, 2894, 38, 22889, 31359, 63, 92, 8009, 1717, 12, 7996, 1769, 203, 7734, 289, 203, 5411, 289, 203, 3639, 289, 203, 3639, 467, 2894, 15839, 4897, 275, 329, 12, 10764, 1119, 16, 13859, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xf607014406bc3Fa7aAB224a85A0318b4556e9C28/sources/browser/AuctionHouseV1.sol
@author Guillaume Gonnaud 2019 @title Auction House Header @notice Contain all the events emitted by the Auction House Deposit: Event emitted whenever money is made available for withdrawal in the Auction House amount: Amount of money being deposited beneficiary: Account that will be able to withdraw the money contributor: Which user wallet initially contributed the received money origin: Which smart contract sent the money Withdrawal: event emitted whenever a user withdraw his Eth on the auction house smart contract amount: total amount of money withdrawn account: address of user withdrawing his money Bid: event emitted whenever a user submit a new bid to an auction auction: the address of the auction bidValue: the eth value of the new standing bid bidder: the address of the user who just bid CancelBid: event emitted whenever a user manually cancel a bid auction: the address of the auction bidder: the address of the user who just cancelled his bid Win: event emitted whenever a user win an auction auction: the address of the auction bidValue: the eth value of the winning bid bidder: the address of the user who just won the auction his bid UserSell: event emitted whenever a user trigger a sale at an auction auction: the address of the auction UserSellingPriceAdjust: event emitted whenever a user adjust the selling price of an auction auction: the address of the auction value : the new adjusted price. 0 for disabled
contract AuctionHouseHeaderV1 { event Deposit(uint256 indexed amount, address indexed beneficiary, address indexed contributor, address origin); event UserWithdrawal(uint256 indexed amount, address indexed account); event UserBid(address indexed auction, uint256 indexed bidValue, address indexed bidder); event UserCancelledBid(address indexed auction, address indexed bidder); event UserWin(address indexed auction, uint256 indexed bidValue, address indexed bidder); event UserSell(address indexed auction); event UserSellingPriceAdjust(address indexed auction, uint256 indexed value); pragma solidity 0.6.6; }
3,152,142
[ 1, 6099, 10745, 2066, 611, 265, 6582, 1100, 30562, 225, 432, 4062, 670, 3793, 4304, 225, 1816, 530, 777, 326, 2641, 17826, 635, 326, 432, 4062, 670, 3793, 4019, 538, 305, 30, 2587, 17826, 17334, 15601, 353, 7165, 2319, 364, 598, 9446, 287, 316, 326, 432, 4062, 670, 3793, 3844, 30, 16811, 434, 15601, 3832, 443, 1724, 329, 27641, 74, 14463, 814, 30, 6590, 716, 903, 506, 7752, 358, 598, 9446, 326, 15601, 31123, 30, 21918, 729, 9230, 22458, 356, 11050, 326, 5079, 15601, 4026, 30, 21918, 13706, 6835, 3271, 326, 15601, 3423, 9446, 287, 30, 871, 17826, 17334, 279, 729, 598, 9446, 18423, 512, 451, 603, 326, 279, 4062, 23867, 13706, 6835, 3844, 30, 2078, 3844, 434, 15601, 598, 9446, 82, 2236, 30, 1758, 434, 729, 598, 9446, 310, 18423, 15601, 605, 350, 30, 871, 17826, 17334, 279, 729, 4879, 279, 394, 9949, 358, 392, 279, 4062, 279, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 432, 4062, 44, 3793, 1864, 58, 21, 288, 203, 203, 565, 871, 4019, 538, 305, 12, 11890, 5034, 8808, 3844, 16, 1758, 8808, 27641, 74, 14463, 814, 16, 1758, 8808, 31123, 16, 1758, 4026, 1769, 203, 203, 565, 871, 2177, 1190, 9446, 287, 12, 11890, 5034, 8808, 3844, 16, 1758, 8808, 2236, 1769, 203, 203, 565, 871, 2177, 17763, 12, 2867, 8808, 279, 4062, 16, 2254, 5034, 8808, 9949, 620, 16, 1758, 8808, 9949, 765, 1769, 203, 203, 565, 871, 2177, 21890, 17763, 12, 2867, 8808, 279, 4062, 16, 1758, 8808, 9949, 765, 1769, 203, 203, 565, 871, 2177, 18049, 12, 2867, 8808, 279, 4062, 16, 2254, 5034, 8808, 9949, 620, 16, 1758, 8808, 9949, 765, 1769, 203, 203, 565, 871, 2177, 55, 1165, 12, 2867, 8808, 279, 4062, 1769, 203, 203, 565, 871, 2177, 55, 1165, 310, 5147, 10952, 12, 2867, 8808, 279, 4062, 16, 2254, 5034, 8808, 460, 1769, 203, 683, 9454, 18035, 560, 374, 18, 26, 18, 26, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } interface reverseCrowdsaleInterface { function updateReverseCrowdsaleInfo (address ad, uint tok, uint weis) external; function getReverseCrowdSaleStatus() constant external returns(bool); } contract AudreyHepburnToken is ERC20Interface,Ownable { using SafeMath for uint256; string public name; string public symbol; uint256 public decimals; uint256 public _totalSupply; mapping(address => uint256) tokenBalances; address ownerWallet; // Owner of account approves the transfer of an amount to another account mapping (address => mapping (address => uint256)) allowed; uint256 exchangeRate; bool isCrowdsaleEnabled; reverseCrowdsaleInterface reverseCrowdsale; address reverseCrowdsaleAddress; /** * @dev Contructor that gives msg.sender all of existing tokens. */ function AudreyHepburnToken(address wallet) public { owner = msg.sender; ownerWallet = wallet; name = "Audrey_ArtDeal"; symbol = "AAD"; decimals = 18; _totalSupply = 1200 * 10 ** uint(decimals); tokenBalances[wallet] = _totalSupply; //Since we divided the token into 10^18 parts exchangeRate = 1172 * 10 ** 11; } // Get the token balance for account `tokenOwner` function balanceOf(address tokenOwner) public constant returns (uint balance) { return tokenBalances[tokenOwner]; } // Transfer the balance from owner's account to another account function transfer(address to, uint tokens) public returns (bool success) { require(to != address(0)); require(tokens <= tokenBalances[msg.sender]); if (to == reverseCrowdsaleAddress) { require (reverseCrowdsale.getReverseCrowdSaleStatus() == true); uint amountToSend = tokens.div(10**uint(decimals)); amountToSend = amountToSend.mul(exchangeRate); msg.sender.transfer(amountToSend); tokenBalances[msg.sender] = tokenBalances[msg.sender].sub(tokens); tokenBalances[ownerWallet] = tokenBalances[ownerWallet].add(tokens); Transfer(msg.sender, ownerWallet, tokens); reverseCrowdsale.updateReverseCrowdsaleInfo(msg.sender,tokens,amountToSend); } else { tokenBalances[msg.sender] = tokenBalances[msg.sender].sub(tokens); tokenBalances[to] = tokenBalances[to].add(tokens); Transfer(msg.sender, to, tokens); } return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= tokenBalances[_from]); require(_value <= allowed[_from][msg.sender]); tokenBalances[_from] = tokenBalances[_from].sub(_value); tokenBalances[_to] = tokenBalances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - tokenBalances[address(0)]; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } //only to be used by the ICO function mint(address wallet, address buyer, uint256 tokenAmount) public onlyOwner { require(tokenBalances[wallet] >= tokenAmount); // checks if it has enough to sell tokenBalances[buyer] = tokenBalances[buyer].add(tokenAmount); // adds the amount to buyer's balance tokenBalances[wallet] = tokenBalances[wallet].sub(tokenAmount); // subtracts amount from seller's balance Transfer(wallet, buyer, tokenAmount); _totalSupply = _totalSupply.sub(tokenAmount); } function setReverseContractAddress(address addr) public{ require(msg.sender == ownerWallet); reverseCrowdsale = reverseCrowdsaleInterface(addr); reverseCrowdsaleAddress = addr; } function claimFunds() public onlyOwner { ownerWallet.transfer(this.balance); } function showMyEtherBalance() public constant onlyOwner returns (uint) { return this.balance; } function refundToBuyers(address[] buyersList, uint rate) public onlyOwner { for (uint i=0;i<buyersList.length;i++) { uint amountToSend = balanceOf(buyersList[i]).mul(rate); buyersList[i].transfer(amountToSend); } } } contract AudreyHepburnCrowdsale { using SafeMath for uint256; // The token being sold AudreyHepburnToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected // address where tokens are deposited and from where we send tokens to buyers address public wallet; // rate of tokens uint256 public rate = 5858 * 10 ** 10; // amount of raised money in wei uint256 public weiRaised; uint256 TOKENS_SOLD; uint256 maxTokensToSale = 1200 * 10 ** 18; //uint256 softCap = 702960 * 10 ** 11; address[] buyersList; /** * 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); function AudreyHepburnCrowdsale(uint256 _startTime, address _wallet) public { startTime = now; endTime = startTime + 5 days; require(startTime >=now); require(endTime >= startTime); require(_wallet != 0x0); wallet = _wallet; token = createTokenContract(wallet); } // creates the token to be sold. function createTokenContract(address wall) internal returns (AudreyHepburnToken) { return new AudreyHepburnToken(wall); } // fallback function can be used to buy tokens function () public payable { buyTokens(msg.sender); } // low level token purchase function // Minimum purchase can be of 1 ETH function buyTokens(address beneficiary) public payable { require(beneficiary != 0x0); require(validPurchase()); require(TOKENS_SOLD<maxTokensToSale); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiAmount.div(rate); tokens = tokens.mul(10**18); require(TOKENS_SOLD+tokens<=maxTokensToSale); // update state weiRaised = weiRaised.add(weiAmount); token.mint(wallet, beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); TOKENS_SOLD = TOKENS_SOLD.add(tokens); buyersList.push(beneficiary); token.transfer(msg.value); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function claimFunds() public { require(msg.sender == wallet); token.claimFunds(); } function refundToBuyers() public { require (msg.sender == wallet && hasEnded() && TOKENS_SOLD <maxTokensToSale); token.refundToBuyers(buyersList, rate); } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { return now > endTime; } // ------------------------------------------------------------------------ // Remaining tokens for sale // ------------------------------------------------------------------------ function remainingTokensForSale() public constant returns (uint) { return maxTokensToSale - TOKENS_SOLD; } function showAvailableEtherBalance() public constant returns (uint) { return token.showMyEtherBalance(); } }
* 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/
{ startTime = now; endTime = startTime + 5 days; require(startTime >=now); require(endTime >= startTime); require(_wallet != 0x0); wallet = _wallet; token = createTokenContract(wallet); }
7,301,590
[ 1, 2575, 364, 1147, 23701, 2907, 225, 5405, 343, 14558, 10354, 30591, 364, 326, 2430, 225, 27641, 74, 14463, 814, 10354, 2363, 326, 2430, 225, 460, 732, 291, 30591, 364, 23701, 225, 3844, 3844, 434, 2430, 5405, 343, 8905, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 288, 203, 565, 8657, 273, 2037, 31, 203, 565, 13859, 273, 8657, 397, 1381, 4681, 31, 203, 203, 565, 2583, 12, 1937, 950, 1545, 3338, 1769, 203, 565, 2583, 12, 409, 950, 1545, 8657, 1769, 203, 565, 2583, 24899, 19177, 480, 374, 92, 20, 1769, 203, 203, 565, 9230, 273, 389, 19177, 31, 203, 565, 1147, 273, 752, 1345, 8924, 12, 19177, 1769, 203, 225, 289, 203, 21281, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x1b5CA8B0DD289430d1a7Df73C77b48B24707C81E/sources/VariableRateTokenVesting.sol
Every element between 0 and 100, and should increase monotonically. [10, 20, 30, ..., 100] means releasing 10% for each period. Seconds between each period. We don't need `duration`, also always allow revoking.
contract VariableRateTokenVesting is TokenVesting { using SafeMath for uint256; using SafeERC20 for ERC20Basic; uint256[] public cumulativeRates; uint256 public interval; constructor( address _beneficiary, uint256 _start, uint256[] _cumulativeRates, uint256 _interval ) public TokenVesting(_beneficiary, _start, /*cliff*/0, /*duration: uint max*/~uint256(0), true) { for (uint256 i = 0; i < _cumulativeRates.length; ++i) { require(_cumulativeRates[i] <= 100); if (i > 0) { require(_cumulativeRates[i] >= _cumulativeRates[i - 1]); } } cumulativeRates = _cumulativeRates; interval = _interval; } { for (uint256 i = 0; i < _cumulativeRates.length; ++i) { require(_cumulativeRates[i] <= 100); if (i > 0) { require(_cumulativeRates[i] >= _cumulativeRates[i - 1]); } } cumulativeRates = _cumulativeRates; interval = _interval; } { for (uint256 i = 0; i < _cumulativeRates.length; ++i) { require(_cumulativeRates[i] <= 100); if (i > 0) { require(_cumulativeRates[i] >= _cumulativeRates[i - 1]); } } cumulativeRates = _cumulativeRates; interval = _interval; } owner = 0x0298CF0d5B60a0aD885518adCB4c3fc49b36D347; function vestedAmount(ERC20Basic token) public view returns (uint256) { if (now < start) { return 0; } uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); uint256 timeSinceStart = now.sub(start); uint256 currentPeriod = timeSinceStart.div(interval); if (currentPeriod >= cumulativeRates.length) { return totalBalance; } return totalBalance.mul(cumulativeRates[currentPeriod]).div(100); } function vestedAmount(ERC20Basic token) public view returns (uint256) { if (now < start) { return 0; } uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); uint256 timeSinceStart = now.sub(start); uint256 currentPeriod = timeSinceStart.div(interval); if (currentPeriod >= cumulativeRates.length) { return totalBalance; } return totalBalance.mul(cumulativeRates[currentPeriod]).div(100); } function vestedAmount(ERC20Basic token) public view returns (uint256) { if (now < start) { return 0; } uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); uint256 timeSinceStart = now.sub(start); uint256 currentPeriod = timeSinceStart.div(interval); if (currentPeriod >= cumulativeRates.length) { return totalBalance; } return totalBalance.mul(cumulativeRates[currentPeriod]).div(100); } }
9,414,076
[ 1, 21465, 930, 3086, 374, 471, 2130, 16, 471, 1410, 10929, 6921, 352, 265, 6478, 18, 306, 2163, 16, 4200, 16, 5196, 16, 1372, 16, 2130, 65, 4696, 6707, 11730, 1728, 9, 364, 1517, 3879, 18, 18301, 3086, 1517, 3879, 18, 1660, 2727, 1404, 1608, 1375, 8760, 9191, 2546, 3712, 1699, 5588, 601, 310, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 7110, 4727, 1345, 58, 10100, 353, 3155, 58, 10100, 288, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 654, 39, 3462, 364, 4232, 39, 3462, 8252, 31, 203, 203, 565, 2254, 5034, 8526, 1071, 15582, 20836, 31, 203, 203, 565, 2254, 5034, 1071, 3673, 31, 203, 203, 565, 3885, 12, 203, 3639, 1758, 389, 70, 4009, 74, 14463, 814, 16, 203, 3639, 2254, 5034, 389, 1937, 16, 203, 3639, 2254, 5034, 8526, 389, 71, 11276, 20836, 16, 203, 3639, 2254, 5034, 389, 6624, 203, 565, 262, 1071, 203, 3639, 3155, 58, 10100, 24899, 70, 4009, 74, 14463, 814, 16, 389, 1937, 16, 1748, 830, 3048, 5549, 20, 16, 1748, 8760, 30, 2254, 943, 5549, 98, 11890, 5034, 12, 20, 3631, 638, 13, 203, 565, 288, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 71, 11276, 20836, 18, 2469, 31, 965, 77, 13, 288, 203, 5411, 2583, 24899, 71, 11276, 20836, 63, 77, 65, 1648, 2130, 1769, 203, 5411, 309, 261, 77, 405, 374, 13, 288, 203, 7734, 2583, 24899, 71, 11276, 20836, 63, 77, 65, 1545, 389, 71, 11276, 20836, 63, 77, 300, 404, 19226, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 15582, 20836, 273, 389, 71, 11276, 20836, 31, 203, 3639, 3673, 273, 389, 6624, 31, 203, 565, 289, 203, 203, 565, 288, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 71, 11276, 20836, 18, 2469, 31, 965, 77, 13, 288, 203, 5411, 2583, 2 ]
./partial_match/4/0x5Ec5149aac729C3aEbeDE9B496D1388C0D33b083/sources/MasterChef.sol
MasterChef is the master of Sushi. He can make Sushi and he is a fair guy. Note that it's ownable and the owner wields tremendous power. The ownership will be transferred to a governance smart contract once SUSHI is sufficiently distributed and the community can show to govern itself. Have fun reading it. Hopefully it's bug-free. God bless. Info of each user.
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; struct UserInfo { } struct PoolInfo { } event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( SushiToken _sushi, address _devaddr, uint256 _sushiPerBlock, uint256 _startBlock, uint256 _bonusEndBlock SushiToken public sushi; address public devaddr; uint256 public bonusEndBlock; uint256 public sushiPerBlock; uint256 public constant BONUS_MULTIPLIER = 2000; IMigratorChef public migrator; PoolInfo[] public poolInfo; mapping (uint256 => mapping (address => UserInfo)) public userInfo; uint256 public totalAllocPoint = 0; uint256 public startBlock; ) public { sushi = _sushi; devaddr = _devaddr; sushiPerBlock = _sushiPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSushiPerShare: 0 })); } function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSushiPerShare: 0 })); } function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSushiPerShare: 0 })); } function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); return _to.sub(_from); return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); return _to.sub(_from); return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } } else if (_from >= bonusEndBlock) { } else { function pendingSushi(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSushiPerShare = pool.accSushiPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt); } function pendingSushi(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSushiPerShare = pool.accSushiPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt); } function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock || stopVerification() == true) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint); sushi.mint(devaddr, sushiReward.div(10)); sushi.mint(address(this), sushiReward); pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock || stopVerification() == true) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint); sushi.mint(devaddr, sushiReward.div(10)); sushi.mint(address(this), sushiReward); pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock || stopVerification() == true) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint); sushi.mint(devaddr, sushiReward.div(10)); sushi.mint(address(this), sushiReward); pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeSushiTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeSushiTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeSushiTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeSushiTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeSushiTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeSushiTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeSushiTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } function safeSushiTransfer(address _to, uint256 _amount) internal { uint256 sushiBal = sushi.balanceOf(address(this)); if (_amount > sushiBal) { sushi.transfer(_to, sushiBal); sushi.transfer(_to, _amount); } } function safeSushiTransfer(address _to, uint256 _amount) internal { uint256 sushiBal = sushi.balanceOf(address(this)); if (_amount > sushiBal) { sushi.transfer(_to, sushiBal); sushi.transfer(_to, _amount); } } } else { function stopVerification() view internal returns(bool){ if(sushi.totalSupply() == 77777*(10 ** 18)){ return true; } return false; } function stopVerification() view internal returns(bool){ if(sushi.totalSupply() == 77777*(10 ** 18)){ return true; } return false; } function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
8,760,865
[ 1, 7786, 39, 580, 74, 353, 326, 4171, 434, 348, 1218, 77, 18, 8264, 848, 1221, 348, 1218, 77, 471, 3904, 353, 279, 284, 1826, 3058, 93, 18, 3609, 716, 518, 1807, 4953, 429, 471, 326, 3410, 341, 491, 87, 268, 2764, 409, 1481, 7212, 18, 1021, 23178, 903, 506, 906, 4193, 358, 279, 314, 1643, 82, 1359, 13706, 6835, 3647, 11726, 2664, 45, 353, 18662, 715, 16859, 471, 326, 19833, 848, 2405, 358, 314, 1643, 82, 6174, 18, 21940, 9831, 6453, 518, 18, 670, 1306, 4095, 518, 1807, 7934, 17, 9156, 18, 611, 369, 324, 2656, 18, 3807, 434, 1517, 729, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 13453, 39, 580, 74, 353, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 1958, 25003, 288, 203, 565, 289, 203, 203, 565, 1958, 8828, 966, 288, 203, 565, 289, 203, 203, 203, 203, 565, 871, 4019, 538, 305, 12, 2867, 8808, 729, 16, 2254, 5034, 8808, 4231, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 3423, 9446, 12, 2867, 8808, 729, 16, 2254, 5034, 8808, 4231, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 512, 6592, 75, 2075, 1190, 9446, 12, 2867, 8808, 729, 16, 2254, 5034, 8808, 4231, 16, 2254, 5034, 3844, 1769, 203, 203, 565, 3885, 12, 203, 3639, 348, 1218, 77, 1345, 389, 87, 1218, 77, 16, 203, 3639, 1758, 389, 5206, 4793, 16, 203, 3639, 2254, 5034, 389, 87, 1218, 77, 2173, 1768, 16, 203, 3639, 2254, 5034, 389, 1937, 1768, 16, 203, 3639, 2254, 5034, 389, 18688, 407, 1638, 1768, 203, 565, 348, 1218, 77, 1345, 1071, 272, 1218, 77, 31, 203, 565, 1758, 1071, 4461, 4793, 31, 203, 565, 2254, 5034, 1071, 324, 22889, 1638, 1768, 31, 203, 565, 2254, 5034, 1071, 272, 1218, 77, 2173, 1768, 31, 203, 565, 2254, 5034, 1071, 5381, 605, 673, 3378, 67, 24683, 2053, 654, 273, 16291, 31, 203, 565, 6246, 2757, 639, 39, 580, 74, 1071, 30188, 31, 203, 565, 8828, 966, 8526, 1071, 2845, 966, 31, 203, 565, 2874, 261, 11890, 5034, 516, 2874, 261, 2867, 516, 25003, 3719, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } 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; } } abstract contract Ownable is Context { address private _owner; address payable private _Powner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { address payable msgSender = _msgSender(); _owner = msgSender; _Powner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view virtual returns (address) { return _owner; } function owner_payable() public view virtual returns (address payable) { return _Powner; } modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address payable newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; _Powner = newOwner; } } //雞巴大小 contract DickSizeToken is Ownable, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => uint256) private _maximums; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; uint256 public _limitICO; // limit for faucet and mining uint256 private _coinbase; // profit from mining per member uint256 private _bigBonusLim; // max bonus for bigDick uint256 public _bonusWins; // How many BigDicks was uint256 public _kingsize; // the royal size of penis uint256 public _micropenis; uint256 public _ratioInchPerEther; //price for buy uint256 public _minWei; // the minimal wei in address to consider it real. For mining uint256 public _LastRecordSet; // sets by func IhaveTheBiggestDick. For big bonus address public _theBiggestDick; // arddress of the biggest dick string public _MessageFromBigDick; //mess to the all world string public _Intro; // 'hurry up! Less than two million mens will have a king size (7") penis'; string private _name; string private _symbol; uint8 private _decimals; event BuyDickInch(address indexed from, uint256 amountWEI); event BigDickBonus(address indexed to, uint256 amountInch); event BigDickSays(address indexed from, string Says); constructor () public { //string memory name_, string memory symbol_ _name = "DickSize"; //"DickSize"; _symbol = "inch";//"inch"; _decimals = 2; //_setupDecimals(2); _mint(_msgSender(),1500000000); _coinbase=100; //setup_coinbase(100); _bigBonusLim = 10000; //setup_bigBonusLim(10000) ; _kingsize = 700; _micropenis = 300; _limitICO = 1000000000; //setup_limitICO(1000000000); _ratioInchPerEther = 2000; //setup_ratioInchPerEther(20); //averege 100$ _minWei = 10**14; //setup_minWei(10**14); } // setups function setup_Intro(string memory value)public virtual onlyOwner{ _Intro = value; } function setup_bigBonusLim(uint256 value)public virtual onlyOwner{ _bigBonusLim = value; } function setup_ratioInchPerEther(uint256 price)public virtual onlyOwner{ _ratioInchPerEther = price.mul(10**_decimals); } function setup_minWei(uint256 value)public virtual onlyOwner{ _minWei = value; } function setup_limitICO(uint256 value)public virtual onlyOwner{ _limitICO = value; } function setup_coinbase(uint256 value)public virtual onlyOwner{ _coinbase = value; } function send_to (address[] memory newMembers,uint256 value) public virtual onlyOwner{ uint256 len = newMembers.length; for (uint256 i = 0; i < len; i++) extend(newMembers[i],value); } // setups function name() public view virtual returns (string memory) { return _name; } function symbol() public view virtual returns (string memory) { return _symbol; } function decimals() public view virtual returns (uint8) { return _decimals; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); if (_maximums[recipient]<_balances[recipient]) _maximums[recipient]=_balances[recipient]; emit Transfer(sender, recipient, amount); } 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); } 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); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {} //feature //coinbase for mining function coinbase() public view virtual returns (uint256) { uint256 declim = totalSupply().sub(_limitICO); if (_balances[owner()]<declim) return 0; return _coinbase; } //coinbase to the new memders function giftbase() public view virtual returns (uint256) { if (coinbase()==0) return 0; return coinbase().div(2); } // bonus for the biggest dick function bigbonus() public view virtual returns (uint256) { if (_bonusWins.mul(100)>=_bigBonusLim) return _bigBonusLim; return _bonusWins.mul(100); } //real length of champion function BigDickLength() public view virtual returns (uint256){ return balanceOf(_theBiggestDick); } function isNew(address to) public view virtual returns (bool){ return _maximums[to]==0 && address(to).balance>=_minWei; } // function isNewCheck(address to) public virtual returns (bool){ // require(address(to).balance>=_minWei, "isNew: recipient must have _minWei"); // require(_balances[to]==0, "isNew: recipient already have inches"); // return true; // } function extend(address to, uint256 amount) internal virtual returns (bool){ require(amount < _balances[owner()], "Opps! The global men's fund is almost empty"); _balances[owner()] = _balances[owner()].sub(amount); _balances[to] = _balances[to].add(amount); if (_maximums[to]<_balances[to]) _maximums[to]=_balances[to]; emit Transfer(owner(), to, amount); return true; } // free inch function faucet () public returns (bool){ require(coinbase() != 0, "Coinbase is zero"); require(_maximums[_msgSender()]<_micropenis, "faucet: You already have minimum inches, try to mining"); extend(_msgSender(),coinbase()); return true; } // You can buy Inches by Ether with price's ratio "_ratioInchPerEther" function buyInches() payable external { uint256 amountEth = msg.value; uint256 amountToken = amountEth.mul(_ratioInchPerEther).div(10**18); require(amountEth > 0, "You need to send some ether to buy inches"); require(amountToken > 0, "Oh! It is not enough to buy even a small piece"); extend(_msgSender(),amountToken); owner_payable().transfer(amountEth); emit BuyDickInch(_msgSender(), amountEth); } //if you really have the biggest dick, then capture it in history and leave a message to posterity function IhaveTheBiggestDick(string memory MessageToTheWorld) public returns (bool){ require(_msgSender()!=owner(), "Sorry, the owner has no rights"); require(_msgSender()!=_theBiggestDick, "You already have The Biggest dick"); require(_balances[_msgSender()]>_balances[_theBiggestDick], "Sorry, it's not true"); _theBiggestDick = _msgSender(); _MessageFromBigDick = MessageToTheWorld; //BigDickBonus - if you exceed the previous record by more than double bonus, you will receive a bonus if (_balances[_msgSender()]>=_LastRecordSet.add(bigbonus().mul(2))){ extend(_msgSender(),bigbonus()); _bonusWins++; emit BigDickBonus(_msgSender(),bigbonus()); } _LastRecordSet = _balances[_theBiggestDick]; emit BigDickSays(_theBiggestDick,_MessageFromBigDick); return true; } // Mining by newMembers without this token with minimum wei function mining (address[] memory newMembers) public returns (bool){ require(coinbase() != 0, "Coinbase is zero"); uint256 len = newMembers.length; for (uint256 i = 0; i < len; i++) if (isNew(newMembers[i])) { extend(newMembers[i],giftbase()); extend(_msgSender(),coinbase()); } return true; } // Size without decimals function mySizeInInch(address YourAddress) public view virtual returns (uint256) { return balanceOf(YourAddress).div(10**_decimals); } // Size in centimeters without decimals function mySizeInCM(address YourAddress) public view virtual returns (uint256) { // return balanceOf(_msgSender()).mul(254).div(100).div(10**_decimals); return balanceOf(YourAddress).mul(254).div(100).div(10**_decimals); } //feature } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } // function mod(uint256 a, uint256 b) internal pure returns (uint256) { // require(b > 0, "SafeMath: modulo by zero"); // return a % b; // } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } // function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // require(b > 0, errorMessage); // return a % b; // } }
setup_ratioInchPerEther(20); averege 100$
_ratioInchPerEther = 2000;
14,518,501
[ 1, 8401, 67, 9847, 382, 343, 2173, 41, 1136, 12, 3462, 1769, 23713, 73, 908, 2130, 8, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 4202, 389, 9847, 382, 343, 2173, 41, 1136, 273, 16291, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/80001/0x41CEefb585E58995a8ce20c23d75B004edAbceba/sources/TetherToken.sol
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
contract TetherToken is Pausable, StandardToken, BlackList { string public name; string public symbol; uint public decimals; address public upgradedAddress; bool public deprecated; constructor(uint _initialSupply, string _name, string _symbol, uint _decimals) public { _totalSupply = _initialSupply; name = _name; symbol = _symbol; decimals = _decimals; balances[owner] = _initialSupply; deprecated = false; } function transfer(address _to, uint _value) public whenNotPaused { require(!isBlackListed[msg.sender]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value); return super.transfer(_to, _value); } } function transfer(address _to, uint _value) public whenNotPaused { require(!isBlackListed[msg.sender]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value); return super.transfer(_to, _value); } } } else { function transferFrom(address _from, address _to, uint _value) public whenNotPaused { require(!isBlackListed[_from]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value); return super.transferFrom(_from, _to, _value); } } function transferFrom(address _from, address _to, uint _value) public whenNotPaused { require(!isBlackListed[_from]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value); return super.transferFrom(_from, _to, _value); } } } else { function balanceOf(address who) public constant returns (uint) { if (deprecated) { return UpgradedStandardToken(upgradedAddress).balanceOf(who); return super.balanceOf(who); } } function balanceOf(address who) public constant returns (uint) { if (deprecated) { return UpgradedStandardToken(upgradedAddress).balanceOf(who); return super.balanceOf(who); } } } else { function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) { if (deprecated) { return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value); return super.approve(_spender, _value); } } function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) { if (deprecated) { return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value); return super.approve(_spender, _value); } } } else { function allowance(address _owner, address _spender) public constant returns (uint remaining) { if (deprecated) { return StandardToken(upgradedAddress).allowance(_owner, _spender); return super.allowance(_owner, _spender); } } function allowance(address _owner, address _spender) public constant returns (uint remaining) { if (deprecated) { return StandardToken(upgradedAddress).allowance(_owner, _spender); return super.allowance(_owner, _spender); } } } else { function deprecate(address _upgradedAddress) public onlyOwner { deprecated = true; upgradedAddress = _upgradedAddress; emit Deprecate(_upgradedAddress); } function totalSupply() public constant returns (uint) { if (deprecated) { return StandardToken(upgradedAddress).totalSupply(); return _totalSupply; } } function totalSupply() public constant returns (uint) { if (deprecated) { return StandardToken(upgradedAddress).totalSupply(); return _totalSupply; } } } else { function issue(uint amount) public { require(_totalSupply + amount > _totalSupply); require(balances[msg.sender] + amount > balances[msg.sender]); balances[msg.sender] += amount; _totalSupply += amount; emit Issue(amount); } function redeem(uint amount) public onlyOwner { require(_totalSupply >= amount); require(balances[owner] >= amount); _totalSupply -= amount; balances[owner] -= amount; emit Redeem(amount); } function setParams(uint newBasisPoints, uint newMaxFee) public onlyOwner { require(newBasisPoints < 20); require(newMaxFee < 50); basisPointsRate = newBasisPoints; maximumFee = newMaxFee.mul(10**decimals); emit Params(basisPointsRate, maximumFee); } event Issue(uint amount); event Redeem(uint amount); event Deprecate(address newAddress); event Params(uint feeBasisPoints, uint maxFee); }
8,799,196
[ 1, 1986, 6835, 848, 506, 6454, 598, 279, 1300, 434, 2430, 225, 4826, 326, 2430, 854, 443, 1724, 329, 358, 326, 3410, 1758, 225, 389, 12296, 10188, 14467, 434, 326, 6835, 225, 389, 529, 3155, 1770, 225, 389, 7175, 3155, 3273, 225, 389, 31734, 3155, 15105, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 399, 2437, 1345, 353, 21800, 16665, 16, 8263, 1345, 16, 22467, 682, 288, 203, 203, 565, 533, 1071, 508, 31, 203, 565, 533, 1071, 3273, 31, 203, 565, 2254, 1071, 15105, 31, 203, 565, 1758, 1071, 31049, 1887, 31, 203, 565, 1426, 1071, 6849, 31, 203, 203, 565, 3885, 12, 11890, 389, 6769, 3088, 1283, 16, 533, 389, 529, 16, 533, 389, 7175, 16, 2254, 389, 31734, 13, 1071, 288, 203, 3639, 389, 4963, 3088, 1283, 273, 389, 6769, 3088, 1283, 31, 203, 3639, 508, 273, 389, 529, 31, 203, 3639, 3273, 273, 389, 7175, 31, 203, 3639, 15105, 273, 389, 31734, 31, 203, 3639, 324, 26488, 63, 8443, 65, 273, 389, 6769, 3088, 1283, 31, 203, 3639, 6849, 273, 629, 31, 203, 565, 289, 203, 203, 565, 445, 7412, 12, 2867, 389, 869, 16, 2254, 389, 1132, 13, 1071, 1347, 1248, 28590, 288, 203, 3639, 2583, 12, 5, 291, 13155, 682, 329, 63, 3576, 18, 15330, 19226, 203, 3639, 309, 261, 14089, 13, 288, 203, 5411, 327, 1948, 19305, 8336, 1345, 12, 416, 19305, 1887, 2934, 13866, 858, 12235, 12, 3576, 18, 15330, 16, 389, 869, 16, 389, 1132, 1769, 203, 5411, 327, 2240, 18, 13866, 24899, 869, 16, 389, 1132, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 7412, 12, 2867, 389, 869, 16, 2254, 389, 1132, 13, 1071, 1347, 1248, 28590, 288, 203, 3639, 2583, 12, 5, 291, 13155, 682, 329, 63, 3576, 18, 15330, 19226, 203, 3639, 309, 261, 14089, 13, 288, 203, 5411, 327, 1948, 2 ]
./full_match/11155111/0x5539dFfaFe2785Ae0B1301001076c11f3af4eB67/sources/contracts/dStorage.sol
Define a function to get the access control list of the caller
function shareAccess() external view returns (Access[] memory) { return _authorizedList[msg.sender]; }
3,786,743
[ 1, 11644, 279, 445, 358, 336, 326, 2006, 3325, 666, 434, 326, 4894, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7433, 1862, 1435, 3903, 1476, 1135, 261, 1862, 8526, 3778, 13, 288, 203, 3639, 327, 389, 8434, 682, 63, 3576, 18, 15330, 15533, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/56/0xdefac16715671b7b6aeeFE012125f1E19Ee4b7d7/sources/_MultiTransfer.sol
* @dev Transfer tokens from one address to multiple others. @param from Address to send from. @param to Array of addresses to transfer to. @param value Array of amounts to be transferred. Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License)/
function multiTransferFrom( address from, address[] calldata to, uint256[] calldata value ) public whenNotPaused onlyBundler returns (bool) { expect(to.length > 0, ERROR_EMPTY_ARRAY); expect(value.length == to.length, ERROR_LENGTH_MISMATCH); for (uint256 i = 0; i < to.length; i++) { if (!isFrozen(to[i])) { allowed[from][msg.sender] -= value[i]; _transfer(from, to[i], value[i]); emit MultiTransferPrevented(from, to[i], value[i]); } } return true; }
11,212,209
[ 1, 5912, 2430, 628, 1245, 1758, 358, 3229, 10654, 18, 225, 628, 5267, 358, 1366, 628, 18, 225, 358, 1510, 434, 6138, 358, 7412, 358, 18, 225, 460, 1510, 434, 30980, 358, 506, 906, 4193, 18, 3914, 30389, 1312, 9173, 261, 27233, 1582, 1462, 4276, 716, 328, 3606, 603, 17, 5639, 3970, 19656, 16832, 13176, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3309, 5912, 1265, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 8526, 745, 892, 358, 16, 203, 3639, 2254, 5034, 8526, 745, 892, 460, 203, 565, 262, 1071, 1347, 1248, 28590, 1338, 15405, 1135, 261, 6430, 13, 288, 203, 3639, 4489, 12, 869, 18, 2469, 405, 374, 16, 5475, 67, 13625, 67, 8552, 1769, 203, 3639, 4489, 12, 1132, 18, 2469, 422, 358, 18, 2469, 16, 5475, 67, 7096, 67, 30062, 11793, 1769, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 358, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 16051, 291, 42, 9808, 12, 869, 63, 77, 22643, 288, 203, 7734, 2935, 63, 2080, 6362, 3576, 18, 15330, 65, 3947, 460, 63, 77, 15533, 203, 7734, 389, 13866, 12, 2080, 16, 358, 63, 77, 6487, 460, 63, 77, 19226, 203, 7734, 3626, 5991, 5912, 25828, 329, 12, 2080, 16, 358, 63, 77, 6487, 460, 63, 77, 19226, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.25; /** * Ascii工具类 **/ library LibAscii{ /** * 单个10进制ascii字符串转字符串 * 例:"55" 得出 "U" * "109" 得出 "m" **/ function decAscii2str(string data) internal pure returns (string){ uint _data = decStrToUint(data); require(_data < 128, "data must be 0 ~ 127"); bytes memory result = new bytes(1); result[0] = byte(_data); return string(result); } /** * 单个16进制ascii字符串转字符串 * * @ param data 原字符串(大小写均可) * * 例:"55" 得出 "U" * "6D" 得出 "Z" **/ function hexAscii2str(string data) internal pure returns(string){ uint _data = hexStrToUint(data); require(_data < 128, "data must be 0x00 ~ 0x7F"); return decAscii2str(uint2str(_data)); } /** * 字符串转ascii字符串 * 例:"aa" 得出9797 10进制 **/ function str2ascii(string data) internal pure returns(string){ bytes memory temp = bytes(data); bytes memory resultStr = ""; for(uint i = 0; i<temp.length; i++){ uint _t = uint(temp[i]); resultStr=abi.encodePacked(resultStr,uint2str(_t)); } return string(resultStr); } //-----------HELPER METHOD--------------// //10字符串转int function decStrToUint(string data) internal pure returns (uint){ bytes memory temp = bytes(data); uint result=0; for(uint i = temp.length; i>0; i--){ uint _t = uint(temp[i-1]);//ascii码的十进制 result+=(_t-48)*(10**(temp.length-i)); } return result; } //字符串转int function hexStrToUint(string data) internal pure returns (uint){ bytes memory temp = bytes(data); uint result=0; for(uint i = temp.length; i>0; i--){ uint _t = uint(temp[i-1]);//ascii码的十进制 uint _t1=0; if (_t > 96) {//a-f 97-102 _t1 = _t - 97 + 10; } else if (_t > 64) {//A-F 65-70 _t1 = _t - 65 + 10; } else {//0-9 48-57 _t1 = _t - 48; } result+=_t1*(16**(temp.length-i)); } return result; } //数字转字符串 function uint2str(uint num) internal pure returns (string) { if (num == 0) return "0"; uint temp = num; uint length = 0; while (temp != 0){ length++; temp /= 10; } bytes memory result = new bytes(length); uint k = length - 1; while (num != 0){ result[k--] = byte(48 + num % 10); num /= 10; } return string(result); } }
* 单个16进制ascii字符串转字符串 @ param data 原字符串(大小写均可) 例:"55" 得出 "U" "6D" 得出 "Z"/
function hexAscii2str(string data) internal pure returns(string){ uint _data = hexStrToUint(data); require(_data < 128, "data must be 0x00 ~ 0x7F"); return decAscii2str(uint2str(_data)); }
886,455
[ 1, 166, 240, 248, 165, 121, 108, 2313, 169, 128, 254, 166, 235, 119, 9184, 166, 260, 250, 168, 110, 104, 165, 121, 115, 169, 126, 110, 166, 260, 250, 168, 110, 104, 165, 121, 115, 632, 579, 501, 225, 225, 166, 241, 258, 166, 260, 250, 168, 110, 104, 165, 121, 115, 12, 166, 102, 105, 166, 113, 242, 166, 233, 252, 166, 256, 234, 166, 242, 112, 13, 225, 165, 127, 238, 176, 125, 253, 6, 2539, 6, 225, 166, 127, 250, 166, 234, 123, 315, 57, 6, 377, 315, 26, 40, 6, 225, 166, 127, 250, 166, 234, 123, 315, 62, 6, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3827, 21363, 22, 701, 12, 1080, 501, 13, 2713, 16618, 1135, 12, 1080, 15329, 203, 3639, 2254, 389, 892, 273, 3827, 1585, 774, 5487, 12, 892, 1769, 203, 3639, 2583, 24899, 892, 411, 8038, 16, 315, 892, 1297, 506, 374, 92, 713, 4871, 374, 92, 27, 42, 8863, 203, 3639, 327, 2109, 21363, 22, 701, 12, 11890, 22, 701, 24899, 892, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0xd18fef0F870c60B59bc5eeDCF3436E619Be96Fe8/sources/contracts/Potpotpots.sol
* @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/ When the token to delete is the last token, the swap operation is unnecessary
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; } delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; }
3,739,008
[ 1, 6014, 445, 358, 1206, 279, 1147, 628, 333, 2710, 1807, 23178, 17, 6440, 501, 12597, 18, 3609, 716, 1323, 326, 1147, 353, 486, 6958, 279, 394, 3410, 16, 326, 1375, 67, 995, 329, 5157, 1016, 68, 2874, 353, 389, 902, 67, 3526, 30, 333, 5360, 364, 16189, 5213, 7089, 425, 18, 75, 18, 1347, 14928, 279, 7412, 1674, 261, 842, 839, 310, 1645, 7262, 2934, 1220, 711, 531, 12, 21, 13, 813, 21610, 16, 1496, 524, 5432, 326, 1353, 434, 326, 389, 995, 329, 5157, 526, 18, 225, 628, 1758, 5123, 326, 2416, 3410, 434, 326, 864, 1147, 1599, 225, 1147, 548, 2254, 5034, 1599, 434, 326, 1147, 358, 506, 3723, 628, 326, 2430, 666, 434, 326, 864, 1758, 19, 5203, 326, 1147, 358, 1430, 353, 326, 1142, 1147, 16, 326, 7720, 1674, 353, 19908, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 4479, 1345, 1265, 5541, 21847, 12, 2867, 628, 16, 2254, 5034, 1147, 548, 13, 3238, 288, 203, 540, 203, 203, 3639, 2254, 5034, 27231, 1016, 273, 4232, 39, 27, 5340, 18, 12296, 951, 12, 2080, 13, 300, 404, 31, 203, 3639, 2254, 5034, 1147, 1016, 273, 389, 995, 329, 5157, 1016, 63, 2316, 548, 15533, 203, 203, 3639, 309, 261, 2316, 1016, 480, 27231, 1016, 13, 288, 203, 5411, 2254, 5034, 27231, 548, 273, 389, 995, 329, 5157, 63, 2080, 6362, 2722, 1345, 1016, 15533, 203, 203, 3639, 289, 203, 203, 540, 203, 3639, 1430, 389, 995, 329, 5157, 1016, 63, 2316, 548, 15533, 203, 3639, 1430, 389, 995, 329, 5157, 63, 2080, 6362, 2722, 1345, 1016, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x2C337F74a52005EdBFb931f82Ba7743189fC8024/sources/contracts/protocol/tokenization/base/IncentivizedERC20.sol
* @dev Only pool can call functions marked by this modifier./
modifier onlyPool() { require(_msgSender() == address(POOL), Errors.CALLER_MUST_BE_POOL); _; }
4,320,351
[ 1, 3386, 2845, 848, 745, 4186, 9350, 635, 333, 9606, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 2864, 1435, 288, 203, 3639, 2583, 24899, 3576, 12021, 1435, 422, 1758, 12, 20339, 3631, 9372, 18, 13730, 654, 67, 49, 5996, 67, 5948, 67, 20339, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /* * 1st Crypto Trader (DTH) */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract CryptoTrader { using SafeMath for uint256; mapping(address => uint256) balances; // array with all balances mapping (address => mapping (address => uint256)) internal allowed; mapping (address => uint256) public ETHBalance; // array with spend ETH uint256 public totalSupply; // emitted tokens address public contract_owner_address; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed buyer, uint256 value); event Burn(address indexed burner, uint256 value); string public constant name = "Token1"; string public constant symbol = "TOK1"; uint8 public decimals = 0; uint public start_sale = 1537434000; // start of presale Thu, 20 Sep 2018 09:00:00 GMT uint public presalePeriod = 61; // presale period in days address public affiliateAddress ; uint public maxAmountPresale_USD = 40000000; // 400,000 US dollars. uint public soldAmount_USD = 0; // current tokens sale amount in US dollars /* Initializes contract with initial supply tokens to the creator of the contract */ constructor ( uint256 initialSupply, address _affiliateAddress ) public { totalSupply = initialSupply; affiliateAddress = _affiliateAddress; contract_owner_address = msg.sender; balances[contract_owner_address] = getPercent(totalSupply,75); // tokens for selling balances[affiliateAddress] = getPercent(totalSupply,25); // affiliate 15% developers 10% } /** * @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 buyer's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _buyer The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _buyer, uint256 _value) public returns (bool) { allowed[msg.sender][_buyer] = _value; emit Approval(msg.sender, _buyer, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a buyer. * @param _owner address The address which owns the funds. * @param _buyer address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the buyer. */ function allowance(address _owner, address _buyer) public view returns (uint256) { return allowed[_owner][_buyer]; } /** * @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 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 sale token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _eth_price spended eth for buying tokens. * @param _usd_amount spended usd for buying tokens. */ function transferSale(address _to, uint256 _value, uint256 _eth_price, uint256 _usd_amount) public returns (bool success) { transfer(_to, _value); ETHBalance[_to] = ETHBalance[_to].add(_eth_price); soldAmount_USD += _usd_amount; return true; } /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(burner, _value); } /** * @dev Refund request. * @param _to The address for refund. */ function refund(address _to) public payable returns(bool){ require(address(this).balance > 0); uint256 _value = balances[_to]; uint256 ether_value = ETHBalance[_to]; require(now > start_sale + presalePeriod * 1 days && soldAmount_USD < maxAmountPresale_USD); require(_value > 0); require(ether_value > 0); balances[_to] = balances[_to].sub(_value); balances[contract_owner_address] = balances[contract_owner_address].add(_value); ETHBalance[_to] = 0; approve(_to, ether_value); address(_to).transfer(ether_value); return true; } /** * @dev Deposit contrac. * @param _value The amount to be transferred. */ function depositContrac(uint256 _value) public payable returns(bool){ approve(address(this), _value); return address(this).send(_value); } function getPercent(uint _value, uint _percent) internal pure returns(uint quotient){ uint _quotient = _value.mul(_percent).div(100); return ( _quotient); } }
* @dev Deposit contrac. @param _value The amount to be transferred./
function depositContrac(uint256 _value) public payable returns(bool){ approve(address(this), _value); return address(this).send(_value); }
5,786,719
[ 1, 758, 1724, 16252, 1077, 18, 225, 389, 1132, 1021, 3844, 358, 506, 906, 4193, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 445, 443, 1724, 442, 313, 1077, 12, 11890, 5034, 389, 1132, 13, 1071, 8843, 429, 1135, 12, 6430, 15329, 203, 377, 6617, 537, 12, 2867, 12, 2211, 3631, 389, 1132, 1769, 203, 377, 327, 225, 1758, 12, 2211, 2934, 4661, 24899, 1132, 1769, 203, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x4398ee3a192dA8Fb387ebd1948887849A1e66dBF/sources/TZU.sol
set as marketing wallet
marketingWallet = address(0x35868D9e2bE55c38A20D27EB1B65bc5641Ae8C7d);
9,728,208
[ 1, 542, 487, 13667, 310, 9230, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 13667, 310, 16936, 273, 1758, 12, 20, 92, 4763, 5292, 28, 40, 29, 73, 22, 70, 41, 2539, 71, 7414, 37, 3462, 40, 5324, 29258, 21, 38, 9222, 13459, 25, 1105, 21, 37, 73, 28, 39, 27, 72, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x00471AE525110087BbC6847cb6e9691BACD13c89/sources/CrazyBoxToken.sol
ERC20 Token Smart Contract Functions with this modifier can only be executed by the owner
contract CrazyBoxToken { string public constant name = "CrazyBoxToken"; string public constant symbol = "HGBT"; uint8 public constant decimals = 8; uint public _totalSupply = 4180000000000000; uint256 public RATE = 1; bool public isMinting = true; bool public isExchangeListed = false; string public constant generatedBy = "Togen.io by Proof Suite"; using SafeMath for uint256; address public owner; modifier onlyOwner() { if (msg.sender != owner) { throw; } _; } modifier onlyOwner() { if (msg.sender != owner) { throw; } _; } mapping(address => uint256) balances; mapping(address => mapping(address=>uint256)) allowed; function () payable{ createTokens(); } constructor() public payable { address originalFeeReceive = 0x6661084EAF2DD24aCAaDe2443292Be76eb344888; ERC20 proofToken = ERC20(0xc5cea8292e514405967d958c2325106f2f48da77); if(proofToken.balanceOf(msg.sender) >= 1000000000000000000){ msg.sender.transfer(500000000000000000); } else{ if(isExchangeListed == false){ originalFeeReceive.transfer(500000000000000000); } else{ originalFeeReceive.transfer(3500000000000000000); } } owner = 0xc4e109913d90a7fdd716402a9005e626c983215d; balances[owner] = _totalSupply; } constructor() public payable { address originalFeeReceive = 0x6661084EAF2DD24aCAaDe2443292Be76eb344888; ERC20 proofToken = ERC20(0xc5cea8292e514405967d958c2325106f2f48da77); if(proofToken.balanceOf(msg.sender) >= 1000000000000000000){ msg.sender.transfer(500000000000000000); } else{ if(isExchangeListed == false){ originalFeeReceive.transfer(500000000000000000); } else{ originalFeeReceive.transfer(3500000000000000000); } } owner = 0xc4e109913d90a7fdd716402a9005e626c983215d; balances[owner] = _totalSupply; } constructor() public payable { address originalFeeReceive = 0x6661084EAF2DD24aCAaDe2443292Be76eb344888; ERC20 proofToken = ERC20(0xc5cea8292e514405967d958c2325106f2f48da77); if(proofToken.balanceOf(msg.sender) >= 1000000000000000000){ msg.sender.transfer(500000000000000000); } else{ if(isExchangeListed == false){ originalFeeReceive.transfer(500000000000000000); } else{ originalFeeReceive.transfer(3500000000000000000); } } owner = 0xc4e109913d90a7fdd716402a9005e626c983215d; balances[owner] = _totalSupply; } constructor() public payable { address originalFeeReceive = 0x6661084EAF2DD24aCAaDe2443292Be76eb344888; ERC20 proofToken = ERC20(0xc5cea8292e514405967d958c2325106f2f48da77); if(proofToken.balanceOf(msg.sender) >= 1000000000000000000){ msg.sender.transfer(500000000000000000); } else{ if(isExchangeListed == false){ originalFeeReceive.transfer(500000000000000000); } else{ originalFeeReceive.transfer(3500000000000000000); } } owner = 0xc4e109913d90a7fdd716402a9005e626c983215d; balances[owner] = _totalSupply; } constructor() public payable { address originalFeeReceive = 0x6661084EAF2DD24aCAaDe2443292Be76eb344888; ERC20 proofToken = ERC20(0xc5cea8292e514405967d958c2325106f2f48da77); if(proofToken.balanceOf(msg.sender) >= 1000000000000000000){ msg.sender.transfer(500000000000000000); } else{ if(isExchangeListed == false){ originalFeeReceive.transfer(500000000000000000); } else{ originalFeeReceive.transfer(3500000000000000000); } } owner = 0xc4e109913d90a7fdd716402a9005e626c983215d; balances[owner] = _totalSupply; } function burnTokens(uint256 _value) onlyOwner { require(balances[msg.sender] >= _value && _value > 0 ); _totalSupply = _totalSupply.sub(_value); balances[msg.sender] = balances[msg.sender].sub(_value); } function createTokens() payable { if(isMinting == true){ require(msg.value > 0); uint256 tokens = msg.value.div(100000000000000).mul(RATE); balances[msg.sender] = balances[msg.sender].add(tokens); _totalSupply = _totalSupply.add(tokens); owner.transfer(msg.value); } else{ throw; } } function createTokens() payable { if(isMinting == true){ require(msg.value > 0); uint256 tokens = msg.value.div(100000000000000).mul(RATE); balances[msg.sender] = balances[msg.sender].add(tokens); _totalSupply = _totalSupply.add(tokens); owner.transfer(msg.value); } else{ throw; } } function createTokens() payable { if(isMinting == true){ require(msg.value > 0); uint256 tokens = msg.value.div(100000000000000).mul(RATE); balances[msg.sender] = balances[msg.sender].add(tokens); _totalSupply = _totalSupply.add(tokens); owner.transfer(msg.value); } else{ throw; } } function endCrowdsale() onlyOwner { isMinting = false; } function changeCrowdsaleRate(uint256 _value) onlyOwner { RATE = _value; } function totalSupply() constant returns(uint256){ return _totalSupply; } function balanceOf(address _owner) constant returns(uint256){ return balances[_owner]; } function transfer(address _to, uint256 _value) returns(bool) { require(balances[msg.sender] >= _value && _value > 0 ); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) returns(bool) { require(allowed[_from][msg.sender] >= _value && balances[_from] >= _value && _value > 0); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) returns(bool){ allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns(uint256){ return allowed[_owner][_spender]; } event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
16,127,458
[ 1, 654, 39, 3462, 3155, 19656, 13456, 15486, 598, 333, 9606, 848, 1338, 506, 7120, 635, 326, 3410, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 6835, 385, 354, 21832, 3514, 1345, 288, 203, 540, 203, 3639, 533, 1071, 5381, 508, 273, 315, 39, 354, 21832, 3514, 1345, 14432, 203, 3639, 533, 1071, 5381, 3273, 273, 315, 44, 5887, 56, 14432, 203, 3639, 2254, 28, 1071, 5381, 15105, 273, 1725, 31, 203, 3639, 2254, 1071, 389, 4963, 3088, 1283, 273, 1059, 2643, 12648, 11706, 31, 203, 3639, 2254, 5034, 1071, 534, 1777, 273, 404, 31, 203, 3639, 1426, 1071, 15707, 474, 310, 273, 638, 31, 203, 3639, 1426, 1071, 353, 11688, 682, 329, 273, 629, 31, 203, 3639, 533, 1071, 5381, 4374, 858, 225, 273, 315, 56, 19409, 18, 1594, 635, 1186, 792, 348, 9519, 14432, 203, 540, 203, 3639, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 3639, 1758, 1071, 3410, 31, 203, 540, 203, 540, 9606, 1338, 5541, 1435, 288, 203, 5411, 309, 261, 3576, 18, 15330, 480, 3410, 13, 288, 203, 7734, 604, 31, 203, 5411, 289, 203, 2398, 389, 31, 203, 540, 289, 203, 1377, 203, 203, 540, 9606, 1338, 5541, 1435, 288, 203, 5411, 309, 261, 3576, 18, 15330, 480, 3410, 13, 288, 203, 7734, 604, 31, 203, 5411, 289, 203, 2398, 389, 31, 203, 540, 289, 203, 1377, 203, 203, 3639, 2874, 12, 2867, 516, 2254, 5034, 13, 324, 26488, 31, 203, 3639, 2874, 12, 2867, 516, 2874, 12, 2867, 9207, 11890, 5034, 3719, 2935, 31, 203, 3639, 445, 1832, 8843, 429, 95, 203, 5411, 752, 5157, 5621, 203, 3639, 289, 203, 203, 3639, 3885, 1435, 1071, 8843, 429, 288, 203, 5411, 1758, 2 ]
./full_match/43114/0x6F7b590f57C6910dD032562eA91fbbCFf267f86b/sources/contracts/strategies/JoeLendingStrategyAvaxV1.sol
* @title Strategy for Banker Joe AVAX @dev Banker Joe emits rewards in AVAX and ERC20. During AVAX claim, contract becomes gas bound/
contract JoeLendingStrategyAvaxV1 is YakStrategyV2Payable, ReentrancyGuard { using SafeMath for uint256; IJoetroller private rewardController; IWAVAX private constant WAVAX = IWAVAX(0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7); uint256 private leverageLevel; uint256 private leverageBips; uint256 private minMinting; constructor( string memory _name, address _rewardController, address _tokenDelegator, address _rewardToken0, address _swapPairToken0, address _timelock, uint256 _minMinting, uint256 _leverageLevel, uint256 _leverageBips, uint256 _minTokensToReinvest, uint256 _adminFeeBips, uint256 _devFeeBips, uint256 _reinvestRewardBips pragma solidity ^0.7.0; ) { name = _name; rewardController = IJoetroller(_rewardController); tokenDelegator = IJoeAVAXDelegator(_tokenDelegator); rewardToken0 = IERC20(_rewardToken0); rewardToken1 = IERC20(address(WAVAX)); rewardToken = rewardToken1; minMinting = _minMinting; _updateLeverage(_leverageLevel, _leverageBips); devAddr = msg.sender; _enterMarket(); assignSwapPairSafely(_swapPairToken0); setAllowances(); updateMinTokensToReinvest(_minTokensToReinvest); updateAdminFee(_adminFeeBips); updateDevFee(_devFeeBips); updateReinvestReward(_reinvestRewardBips); updateDepositsEnabled(true); transferOwnership(_timelock); emit Reinvest(0, 0); } function totalDeposits() public view override returns (uint256) { ( , uint256 internalBalance, uint256 borrow, uint256 exchangeRate ) = tokenDelegator.getAccountSnapshot(address(this)); return internalBalance.mul(exchangeRate).div(1e18).sub(borrow); } function _totalDepositsFresh() internal returns (uint256) { uint256 borrow = tokenDelegator.borrowBalanceCurrent(address(this)); uint256 balance = tokenDelegator.balanceOfUnderlying(address(this)); return balance.sub(borrow); } function _enterMarket() internal { address[] memory tokens = new address[](1); tokens[0] = address(tokenDelegator); rewardController.enterMarkets(tokens); } function _updateLeverage(uint256 _leverageLevel, uint256 _leverageBips) internal { leverageLevel = _leverageLevel; leverageBips = _leverageBips; } function updateLeverage(uint256 _leverageLevel, uint256 _leverageBips) external onlyDev { _updateLeverage(_leverageLevel, _leverageBips); uint256 balance = _totalDepositsFresh(); _unrollDebt(balance); if (balance > 0) { _rollupDebt(balance, 0); } } function updateLeverage(uint256 _leverageLevel, uint256 _leverageBips) external onlyDev { _updateLeverage(_leverageLevel, _leverageBips); uint256 balance = _totalDepositsFresh(); _unrollDebt(balance); if (balance > 0) { _rollupDebt(balance, 0); } } function assignSwapPairSafely(address _swapPairToken0) private { require( _swapPairToken0 > address(0), "Swap pair 0 is necessary but not supplied" ); require( address(rewardToken0) == IPair(address(_swapPairToken0)).token0() || address(rewardToken0) == IPair(address(_swapPairToken0)).token1(), "Swap pair 0 does not match rewardToken0" ); require( address(rewardToken1) == IPair(address(_swapPairToken0)).token0() || address(rewardToken1) == IPair(address(_swapPairToken0)).token1(), "Swap pair 0 does not match rewardToken1" ); swapPairToken0 = IPair(_swapPairToken0); } function setAllowances() public override onlyOwner { tokenDelegator.approve(address(tokenDelegator), type(uint256).max); } function deposit() external payable override nonReentrant { _deposit(msg.sender, msg.value); } function depositFor(address account) external payable override nonReentrant { _deposit(account, msg.value); } function deposit(uint256 amount) external override { revert(); } function depositWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { revert(); } function depositFor(address account, uint256 amount) external override { revert(); } function _deposit(address account, uint256 amount) private onlyAllowedDeposits { require(DEPOSITS_ENABLED == true, "JoeLendingStrategyAvaxV1::_deposit"); if (MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST > 0) { (uint256 joeRewards, uint256 avaxBalance, uint256 amountToReinvest) = _checkRewards(); if ( amountToReinvest > MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST ) { _reinvest(joeRewards, avaxBalance, amountToReinvest); } } uint256 shareTokenAmount = amount; uint256 balance = _totalDepositsFresh(); if (totalSupply.mul(balance) > 0) { shareTokenAmount = amount.mul(totalSupply).div(balance); } _mint(account, shareTokenAmount); _stakeDepositTokens(amount); emit Deposit(account, amount); claimAVAXRewards(); } function _deposit(address account, uint256 amount) private onlyAllowedDeposits { require(DEPOSITS_ENABLED == true, "JoeLendingStrategyAvaxV1::_deposit"); if (MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST > 0) { (uint256 joeRewards, uint256 avaxBalance, uint256 amountToReinvest) = _checkRewards(); if ( amountToReinvest > MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST ) { _reinvest(joeRewards, avaxBalance, amountToReinvest); } } uint256 shareTokenAmount = amount; uint256 balance = _totalDepositsFresh(); if (totalSupply.mul(balance) > 0) { shareTokenAmount = amount.mul(totalSupply).div(balance); } _mint(account, shareTokenAmount); _stakeDepositTokens(amount); emit Deposit(account, amount); claimAVAXRewards(); } function _deposit(address account, uint256 amount) private onlyAllowedDeposits { require(DEPOSITS_ENABLED == true, "JoeLendingStrategyAvaxV1::_deposit"); if (MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST > 0) { (uint256 joeRewards, uint256 avaxBalance, uint256 amountToReinvest) = _checkRewards(); if ( amountToReinvest > MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST ) { _reinvest(joeRewards, avaxBalance, amountToReinvest); } } uint256 shareTokenAmount = amount; uint256 balance = _totalDepositsFresh(); if (totalSupply.mul(balance) > 0) { shareTokenAmount = amount.mul(totalSupply).div(balance); } _mint(account, shareTokenAmount); _stakeDepositTokens(amount); emit Deposit(account, amount); claimAVAXRewards(); } function _deposit(address account, uint256 amount) private onlyAllowedDeposits { require(DEPOSITS_ENABLED == true, "JoeLendingStrategyAvaxV1::_deposit"); if (MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST > 0) { (uint256 joeRewards, uint256 avaxBalance, uint256 amountToReinvest) = _checkRewards(); if ( amountToReinvest > MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST ) { _reinvest(joeRewards, avaxBalance, amountToReinvest); } } uint256 shareTokenAmount = amount; uint256 balance = _totalDepositsFresh(); if (totalSupply.mul(balance) > 0) { shareTokenAmount = amount.mul(totalSupply).div(balance); } _mint(account, shareTokenAmount); _stakeDepositTokens(amount); emit Deposit(account, amount); claimAVAXRewards(); } function withdraw(uint256 amount) external override { uint256 depositTokenAmount = _totalDepositsFresh().mul(amount).div(totalSupply); require( depositTokenAmount > minMinting, "JoeLendingStrategyAvaxV1:: below minimum withdraw" ); _burn(msg.sender, amount); _withdrawDepositTokens(depositTokenAmount); require(success, "JoeLendingStrategyAvaxV1::withdraw transfer failed"); emit Withdraw(msg.sender, depositTokenAmount); claimAVAXRewards(); } (bool success, ) = msg.sender.call{value: depositTokenAmount}(""); function _withdrawDepositTokens(uint256 amount) private { _unrollDebt(amount); require( tokenDelegator.redeemUnderlyingNative(amount) == 0, "JoeLendingStrategyAvaxV1::redeem failed" ); uint256 balance = tokenDelegator.balanceOfUnderlying(address(this)); uint256 borrow = tokenDelegator.borrowBalanceCurrent(address(this)); if (balance > 0) { _rollupDebt(balance, borrow); } } function _withdrawDepositTokens(uint256 amount) private { _unrollDebt(amount); require( tokenDelegator.redeemUnderlyingNative(amount) == 0, "JoeLendingStrategyAvaxV1::redeem failed" ); uint256 balance = tokenDelegator.balanceOfUnderlying(address(this)); uint256 borrow = tokenDelegator.borrowBalanceCurrent(address(this)); if (balance > 0) { _rollupDebt(balance, borrow); } } function reinvest() external override onlyEOA nonReentrant { (uint256 joeRewards, uint256 avaxBalance, uint256 amountToReinvest) = _checkRewards(); require( amountToReinvest >= MIN_TOKENS_TO_REINVEST, "JoeLendingStrategyAvaxV1::reinvest" ); _reinvest(joeRewards, avaxBalance, amountToReinvest); claimAVAXRewards(); } receive() external payable { require( msg.sender == address(rewardController) || msg.sender == address(WAVAX) || msg.sender == address(tokenDelegator), "JoeLendingStrategyAvaxV1::payments not allowed" ); } function _reinvest(uint256 joeRewards, uint256 avaxBalance, uint256 amount) private { if (joeRewards > 0) { rewardController.claimReward(0, address(this)); uint256 joeAsWavax = DexLibrary.swap( joeRewards, address(rewardToken0), address(rewardToken1), swapPairToken0 ); WAVAX.withdraw(joeAsWavax); } uint256 fees = amount.mul( DEV_FEE_BIPS.add(ADMIN_FEE_BIPS).add(REINVEST_REWARD_BIPS) ); uint256 devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR); if (devFee > 0) { _safeTransfer(address(rewardToken), devAddr, devFee); } uint256 adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR); if (adminFee > 0) { _safeTransfer(address(rewardToken), owner(), adminFee); } uint256 reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR); if (reinvestFee > 0) { _safeTransfer(address(rewardToken), msg.sender, reinvestFee); } _stakeDepositTokens(amount.sub(fees)); emit Reinvest(totalDeposits(), totalSupply); } function _reinvest(uint256 joeRewards, uint256 avaxBalance, uint256 amount) private { if (joeRewards > 0) { rewardController.claimReward(0, address(this)); uint256 joeAsWavax = DexLibrary.swap( joeRewards, address(rewardToken0), address(rewardToken1), swapPairToken0 ); WAVAX.withdraw(joeAsWavax); } uint256 fees = amount.mul( DEV_FEE_BIPS.add(ADMIN_FEE_BIPS).add(REINVEST_REWARD_BIPS) ); uint256 devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR); if (devFee > 0) { _safeTransfer(address(rewardToken), devAddr, devFee); } uint256 adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR); if (adminFee > 0) { _safeTransfer(address(rewardToken), owner(), adminFee); } uint256 reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR); if (reinvestFee > 0) { _safeTransfer(address(rewardToken), msg.sender, reinvestFee); } _stakeDepositTokens(amount.sub(fees)); emit Reinvest(totalDeposits(), totalSupply); } WAVAX.deposit{value: fees}(); function _reinvest(uint256 joeRewards, uint256 avaxBalance, uint256 amount) private { if (joeRewards > 0) { rewardController.claimReward(0, address(this)); uint256 joeAsWavax = DexLibrary.swap( joeRewards, address(rewardToken0), address(rewardToken1), swapPairToken0 ); WAVAX.withdraw(joeAsWavax); } uint256 fees = amount.mul( DEV_FEE_BIPS.add(ADMIN_FEE_BIPS).add(REINVEST_REWARD_BIPS) ); uint256 devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR); if (devFee > 0) { _safeTransfer(address(rewardToken), devAddr, devFee); } uint256 adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR); if (adminFee > 0) { _safeTransfer(address(rewardToken), owner(), adminFee); } uint256 reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR); if (reinvestFee > 0) { _safeTransfer(address(rewardToken), msg.sender, reinvestFee); } _stakeDepositTokens(amount.sub(fees)); emit Reinvest(totalDeposits(), totalSupply); } function _reinvest(uint256 joeRewards, uint256 avaxBalance, uint256 amount) private { if (joeRewards > 0) { rewardController.claimReward(0, address(this)); uint256 joeAsWavax = DexLibrary.swap( joeRewards, address(rewardToken0), address(rewardToken1), swapPairToken0 ); WAVAX.withdraw(joeAsWavax); } uint256 fees = amount.mul( DEV_FEE_BIPS.add(ADMIN_FEE_BIPS).add(REINVEST_REWARD_BIPS) ); uint256 devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR); if (devFee > 0) { _safeTransfer(address(rewardToken), devAddr, devFee); } uint256 adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR); if (adminFee > 0) { _safeTransfer(address(rewardToken), owner(), adminFee); } uint256 reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR); if (reinvestFee > 0) { _safeTransfer(address(rewardToken), msg.sender, reinvestFee); } _stakeDepositTokens(amount.sub(fees)); emit Reinvest(totalDeposits(), totalSupply); } function _reinvest(uint256 joeRewards, uint256 avaxBalance, uint256 amount) private { if (joeRewards > 0) { rewardController.claimReward(0, address(this)); uint256 joeAsWavax = DexLibrary.swap( joeRewards, address(rewardToken0), address(rewardToken1), swapPairToken0 ); WAVAX.withdraw(joeAsWavax); } uint256 fees = amount.mul( DEV_FEE_BIPS.add(ADMIN_FEE_BIPS).add(REINVEST_REWARD_BIPS) ); uint256 devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR); if (devFee > 0) { _safeTransfer(address(rewardToken), devAddr, devFee); } uint256 adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR); if (adminFee > 0) { _safeTransfer(address(rewardToken), owner(), adminFee); } uint256 reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR); if (reinvestFee > 0) { _safeTransfer(address(rewardToken), msg.sender, reinvestFee); } _stakeDepositTokens(amount.sub(fees)); emit Reinvest(totalDeposits(), totalSupply); } function claimAVAXRewards() public { if (DEPOSITS_ENABLED == true) { if (_getReward(1, address(this)) >= MIN_TOKENS_TO_REINVEST) { rewardController.claimReward(1, address(this)); } } } function claimAVAXRewards() public { if (DEPOSITS_ENABLED == true) { if (_getReward(1, address(this)) >= MIN_TOKENS_TO_REINVEST) { rewardController.claimReward(1, address(this)); } } } function claimAVAXRewards() public { if (DEPOSITS_ENABLED == true) { if (_getReward(1, address(this)) >= MIN_TOKENS_TO_REINVEST) { rewardController.claimReward(1, address(this)); } } } function _rollupDebt(uint256 principal, uint256 borrowed) internal { (uint256 borrowLimit, uint256 borrowBips) = _getBorrowLimit(); uint256 supplied = principal; uint256 lendTarget = principal.sub(borrowed).mul(leverageLevel).div( leverageBips ); uint256 totalBorrowed = borrowed; while (supplied < lendTarget) { uint256 toBorrowAmount = _getBorrowable( supplied, totalBorrowed, borrowLimit, borrowBips ); if (supplied.add(toBorrowAmount) > lendTarget) { toBorrowAmount = lendTarget.sub(supplied); } if (toBorrowAmount < minMinting) { break; } require( tokenDelegator.borrowNative(toBorrowAmount) == 0, "JoeLendingStrategyAvaxV1::borrowing failed" ); require( "JoeLendingStrategyAvaxV1::lending failed" ); supplied = tokenDelegator.balanceOfUnderlying(address(this)); totalBorrowed = totalBorrowed.add(toBorrowAmount); } } function _rollupDebt(uint256 principal, uint256 borrowed) internal { (uint256 borrowLimit, uint256 borrowBips) = _getBorrowLimit(); uint256 supplied = principal; uint256 lendTarget = principal.sub(borrowed).mul(leverageLevel).div( leverageBips ); uint256 totalBorrowed = borrowed; while (supplied < lendTarget) { uint256 toBorrowAmount = _getBorrowable( supplied, totalBorrowed, borrowLimit, borrowBips ); if (supplied.add(toBorrowAmount) > lendTarget) { toBorrowAmount = lendTarget.sub(supplied); } if (toBorrowAmount < minMinting) { break; } require( tokenDelegator.borrowNative(toBorrowAmount) == 0, "JoeLendingStrategyAvaxV1::borrowing failed" ); require( "JoeLendingStrategyAvaxV1::lending failed" ); supplied = tokenDelegator.balanceOfUnderlying(address(this)); totalBorrowed = totalBorrowed.add(toBorrowAmount); } } function _rollupDebt(uint256 principal, uint256 borrowed) internal { (uint256 borrowLimit, uint256 borrowBips) = _getBorrowLimit(); uint256 supplied = principal; uint256 lendTarget = principal.sub(borrowed).mul(leverageLevel).div( leverageBips ); uint256 totalBorrowed = borrowed; while (supplied < lendTarget) { uint256 toBorrowAmount = _getBorrowable( supplied, totalBorrowed, borrowLimit, borrowBips ); if (supplied.add(toBorrowAmount) > lendTarget) { toBorrowAmount = lendTarget.sub(supplied); } if (toBorrowAmount < minMinting) { break; } require( tokenDelegator.borrowNative(toBorrowAmount) == 0, "JoeLendingStrategyAvaxV1::borrowing failed" ); require( "JoeLendingStrategyAvaxV1::lending failed" ); supplied = tokenDelegator.balanceOfUnderlying(address(this)); totalBorrowed = totalBorrowed.add(toBorrowAmount); } } function _rollupDebt(uint256 principal, uint256 borrowed) internal { (uint256 borrowLimit, uint256 borrowBips) = _getBorrowLimit(); uint256 supplied = principal; uint256 lendTarget = principal.sub(borrowed).mul(leverageLevel).div( leverageBips ); uint256 totalBorrowed = borrowed; while (supplied < lendTarget) { uint256 toBorrowAmount = _getBorrowable( supplied, totalBorrowed, borrowLimit, borrowBips ); if (supplied.add(toBorrowAmount) > lendTarget) { toBorrowAmount = lendTarget.sub(supplied); } if (toBorrowAmount < minMinting) { break; } require( tokenDelegator.borrowNative(toBorrowAmount) == 0, "JoeLendingStrategyAvaxV1::borrowing failed" ); require( "JoeLendingStrategyAvaxV1::lending failed" ); supplied = tokenDelegator.balanceOfUnderlying(address(this)); totalBorrowed = totalBorrowed.add(toBorrowAmount); } } tokenDelegator.mintNative{value: toBorrowAmount}() == 0, function _getBorrowable( uint256 balance, uint256 borrowed, uint256 borrowLimit, uint256 bips ) internal pure returns (uint256) { return balance.mul(borrowLimit).div(bips).sub(borrowed).mul(950).div(1000); } function _getBorrowLimit() internal view returns (uint256, uint256) { (, uint256 borrowLimit) = rewardController.markets(address(tokenDelegator)); return (borrowLimit, 1e18); } function _unrollDebt(uint256 amountToFreeUp) internal { uint256 borrowed = tokenDelegator.borrowBalanceCurrent(address(this)); uint256 balance = tokenDelegator.balanceOfUnderlying(address(this)); (uint256 borrowLimit, uint256 borrowBips) = _getBorrowLimit(); uint256 targetBorrow = balance .sub(borrowed) .sub(amountToFreeUp) .mul(leverageLevel) .div(leverageBips) .sub(balance.sub(borrowed).sub(amountToFreeUp)); uint256 toRepay = borrowed.sub(targetBorrow); while (toRepay > 0) { uint256 unrollAmount = _getBorrowable( balance, borrowed, borrowLimit, borrowBips ); if (unrollAmount > borrowed) { unrollAmount = borrowed; } require( tokenDelegator.redeemUnderlyingNative(unrollAmount) == 0, "JoeLendingStrategyAvaxV1::failed to redeem" ); require( "JoeLendingStrategyAvaxV1::failed to repay borrow" ); balance = tokenDelegator.balanceOfUnderlying(address(this)); borrowed = borrowed.sub(unrollAmount); if (targetBorrow >= borrowed) { break; } toRepay = borrowed.sub(targetBorrow); } } function _unrollDebt(uint256 amountToFreeUp) internal { uint256 borrowed = tokenDelegator.borrowBalanceCurrent(address(this)); uint256 balance = tokenDelegator.balanceOfUnderlying(address(this)); (uint256 borrowLimit, uint256 borrowBips) = _getBorrowLimit(); uint256 targetBorrow = balance .sub(borrowed) .sub(amountToFreeUp) .mul(leverageLevel) .div(leverageBips) .sub(balance.sub(borrowed).sub(amountToFreeUp)); uint256 toRepay = borrowed.sub(targetBorrow); while (toRepay > 0) { uint256 unrollAmount = _getBorrowable( balance, borrowed, borrowLimit, borrowBips ); if (unrollAmount > borrowed) { unrollAmount = borrowed; } require( tokenDelegator.redeemUnderlyingNative(unrollAmount) == 0, "JoeLendingStrategyAvaxV1::failed to redeem" ); require( "JoeLendingStrategyAvaxV1::failed to repay borrow" ); balance = tokenDelegator.balanceOfUnderlying(address(this)); borrowed = borrowed.sub(unrollAmount); if (targetBorrow >= borrowed) { break; } toRepay = borrowed.sub(targetBorrow); } } function _unrollDebt(uint256 amountToFreeUp) internal { uint256 borrowed = tokenDelegator.borrowBalanceCurrent(address(this)); uint256 balance = tokenDelegator.balanceOfUnderlying(address(this)); (uint256 borrowLimit, uint256 borrowBips) = _getBorrowLimit(); uint256 targetBorrow = balance .sub(borrowed) .sub(amountToFreeUp) .mul(leverageLevel) .div(leverageBips) .sub(balance.sub(borrowed).sub(amountToFreeUp)); uint256 toRepay = borrowed.sub(targetBorrow); while (toRepay > 0) { uint256 unrollAmount = _getBorrowable( balance, borrowed, borrowLimit, borrowBips ); if (unrollAmount > borrowed) { unrollAmount = borrowed; } require( tokenDelegator.redeemUnderlyingNative(unrollAmount) == 0, "JoeLendingStrategyAvaxV1::failed to redeem" ); require( "JoeLendingStrategyAvaxV1::failed to repay borrow" ); balance = tokenDelegator.balanceOfUnderlying(address(this)); borrowed = borrowed.sub(unrollAmount); if (targetBorrow >= borrowed) { break; } toRepay = borrowed.sub(targetBorrow); } } tokenDelegator.repayBorrowNative{value: unrollAmount}() == 0, function _unrollDebt(uint256 amountToFreeUp) internal { uint256 borrowed = tokenDelegator.borrowBalanceCurrent(address(this)); uint256 balance = tokenDelegator.balanceOfUnderlying(address(this)); (uint256 borrowLimit, uint256 borrowBips) = _getBorrowLimit(); uint256 targetBorrow = balance .sub(borrowed) .sub(amountToFreeUp) .mul(leverageLevel) .div(leverageBips) .sub(balance.sub(borrowed).sub(amountToFreeUp)); uint256 toRepay = borrowed.sub(targetBorrow); while (toRepay > 0) { uint256 unrollAmount = _getBorrowable( balance, borrowed, borrowLimit, borrowBips ); if (unrollAmount > borrowed) { unrollAmount = borrowed; } require( tokenDelegator.redeemUnderlyingNative(unrollAmount) == 0, "JoeLendingStrategyAvaxV1::failed to redeem" ); require( "JoeLendingStrategyAvaxV1::failed to repay borrow" ); balance = tokenDelegator.balanceOfUnderlying(address(this)); borrowed = borrowed.sub(unrollAmount); if (targetBorrow >= borrowed) { break; } toRepay = borrowed.sub(targetBorrow); } } function _stakeDepositTokens(uint256 amount) private { require(amount > 0, "JoeLendingStrategyAvaxV1::_stakeDepositTokens"); require( "JoeLendingStrategyAvaxV1::Deposit failed" ); uint256 borrowed = tokenDelegator.borrowBalanceCurrent(address(this)); uint256 principal = tokenDelegator.balanceOfUnderlying(address(this)); _rollupDebt(principal, borrowed); } tokenDelegator.mintNative{value: amount}() == 0, function _safeTransfer( address token, address to, uint256 value ) private { require( IERC20(token).transfer(to, value), "JoeLendingStrategyAvaxV1::TRANSFER_FROM_FAILED" ); } function _checkRewards() internal view returns ( uint256 joeRewards, uint256 avaxBalance, uint256 totalAmount ) { uint256 joeRewards = _getReward(0, address(this)); uint256 wavaxBalance = WAVAX.balanceOf(address(this)); uint256 avaxBalance = address(this).balance; uint256 joeRewardsAsWavax = DexLibrary.estimateConversionThroughPair( joeRewards, address(rewardToken0), address(rewardToken1), swapPairToken0 ); return (joeRewards, avaxBalance, avaxBalance.add(wavaxBalance).add(joeRewardsAsWavax)); } function checkReward() public view override returns (uint256) { (,, uint256 totalAmount) = _checkRewards(); return totalAmount; } function _getReward(uint8 tokenIndex, address account) internal view returns (uint256) { IJoeRewardDistributor rewardDistributor = IJoeRewardDistributor( rewardController.rewardDistributor() ); (uint224 supplyIndex, ) = rewardDistributor.rewardSupplyState( tokenIndex, account ); uint256 supplierIndex = rewardDistributor.rewardSupplierIndex( tokenIndex, address(tokenDelegator), account ); uint256 supplyIndexDelta = 0; if (supplyIndex > supplierIndex) { supplyIndexDelta = supplyIndex - supplierIndex; } (uint224 borrowIndex, ) = rewardDistributor.rewardBorrowState( tokenIndex, account ); uint256 borrowerIndex = rewardDistributor.rewardBorrowerIndex( tokenIndex, address(tokenDelegator), account ); uint256 borrowIndexDelta = 0; if (borrowIndex > borrowerIndex) { borrowIndexDelta = borrowIndex - borrowerIndex; } return rewardDistributor.rewardAccrued(tokenIndex, account).add( tokenDelegator.balanceOf(account).mul(supplyIndexDelta).sub( tokenDelegator.borrowBalanceStored(account).mul(borrowIndexDelta) ) ); } function _getReward(uint8 tokenIndex, address account) internal view returns (uint256) { IJoeRewardDistributor rewardDistributor = IJoeRewardDistributor( rewardController.rewardDistributor() ); (uint224 supplyIndex, ) = rewardDistributor.rewardSupplyState( tokenIndex, account ); uint256 supplierIndex = rewardDistributor.rewardSupplierIndex( tokenIndex, address(tokenDelegator), account ); uint256 supplyIndexDelta = 0; if (supplyIndex > supplierIndex) { supplyIndexDelta = supplyIndex - supplierIndex; } (uint224 borrowIndex, ) = rewardDistributor.rewardBorrowState( tokenIndex, account ); uint256 borrowerIndex = rewardDistributor.rewardBorrowerIndex( tokenIndex, address(tokenDelegator), account ); uint256 borrowIndexDelta = 0; if (borrowIndex > borrowerIndex) { borrowIndexDelta = borrowIndex - borrowerIndex; } return rewardDistributor.rewardAccrued(tokenIndex, account).add( tokenDelegator.balanceOf(account).mul(supplyIndexDelta).sub( tokenDelegator.borrowBalanceStored(account).mul(borrowIndexDelta) ) ); } function _getReward(uint8 tokenIndex, address account) internal view returns (uint256) { IJoeRewardDistributor rewardDistributor = IJoeRewardDistributor( rewardController.rewardDistributor() ); (uint224 supplyIndex, ) = rewardDistributor.rewardSupplyState( tokenIndex, account ); uint256 supplierIndex = rewardDistributor.rewardSupplierIndex( tokenIndex, address(tokenDelegator), account ); uint256 supplyIndexDelta = 0; if (supplyIndex > supplierIndex) { supplyIndexDelta = supplyIndex - supplierIndex; } (uint224 borrowIndex, ) = rewardDistributor.rewardBorrowState( tokenIndex, account ); uint256 borrowerIndex = rewardDistributor.rewardBorrowerIndex( tokenIndex, address(tokenDelegator), account ); uint256 borrowIndexDelta = 0; if (borrowIndex > borrowerIndex) { borrowIndexDelta = borrowIndex - borrowerIndex; } return rewardDistributor.rewardAccrued(tokenIndex, account).add( tokenDelegator.balanceOf(account).mul(supplyIndexDelta).sub( tokenDelegator.borrowBalanceStored(account).mul(borrowIndexDelta) ) ); } function getActualLeverage() public view returns (uint256) { ( , uint256 internalBalance, uint256 borrow, uint256 exchangeRate ) = tokenDelegator.getAccountSnapshot(address(this)); uint256 balance = internalBalance.mul(exchangeRate).div(1e18); return balance.mul(1e18).div(balance.sub(borrow)); } function estimateDeployedBalance() external view override returns (uint256) { return totalDeposits(); } function rescueDeployedFunds(uint256 minReturnAmountAccepted, bool disableDeposits) external override onlyOwner { uint256 balanceBefore = address(this).balance; uint256 balance = _totalDepositsFresh(); _unrollDebt(balance); tokenDelegator.redeemUnderlying(balance); uint256 balanceAfter = address(this).balance; require( balanceAfter.sub(balanceBefore) >= minReturnAmountAccepted, "JoeLendingStrategyAvaxV1::rescueDeployedFunds" ); emit Reinvest(totalDeposits(), totalSupply); if (DEPOSITS_ENABLED == true && disableDeposits == true) { updateDepositsEnabled(false); } } function rescueDeployedFunds(uint256 minReturnAmountAccepted, bool disableDeposits) external override onlyOwner { uint256 balanceBefore = address(this).balance; uint256 balance = _totalDepositsFresh(); _unrollDebt(balance); tokenDelegator.redeemUnderlying(balance); uint256 balanceAfter = address(this).balance; require( balanceAfter.sub(balanceBefore) >= minReturnAmountAccepted, "JoeLendingStrategyAvaxV1::rescueDeployedFunds" ); emit Reinvest(totalDeposits(), totalSupply); if (DEPOSITS_ENABLED == true && disableDeposits == true) { updateDepositsEnabled(false); } } }
4,613,704
[ 1, 4525, 364, 25610, 264, 804, 15548, 15068, 2501, 225, 25610, 264, 804, 15548, 24169, 283, 6397, 316, 15068, 2501, 471, 4232, 39, 3462, 18, 463, 4017, 15068, 2501, 7516, 16, 6835, 12724, 16189, 2489, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 804, 15548, 48, 2846, 4525, 3769, 651, 58, 21, 353, 1624, 581, 4525, 58, 22, 9148, 429, 16, 868, 8230, 12514, 16709, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 467, 46, 83, 278, 1539, 3238, 19890, 2933, 31, 203, 565, 467, 59, 5856, 2501, 3238, 5381, 678, 5856, 2501, 273, 467, 59, 5856, 2501, 12, 20, 20029, 6938, 74, 6028, 5284, 23, 39, 21, 73, 27, 7140, 23, 4449, 42, 6840, 5877, 37, 21, 38, 5608, 41, 5324, 70, 7140, 16894, 6028, 71, 27, 1769, 203, 565, 2254, 5034, 3238, 884, 5682, 2355, 31, 203, 565, 2254, 5034, 3238, 884, 5682, 38, 7146, 31, 203, 565, 2254, 5034, 3238, 1131, 49, 474, 310, 31, 203, 203, 565, 3885, 12, 203, 3639, 533, 3778, 389, 529, 16, 203, 3639, 1758, 389, 266, 2913, 2933, 16, 203, 3639, 1758, 389, 2316, 15608, 639, 16, 203, 3639, 1758, 389, 266, 2913, 1345, 20, 16, 203, 3639, 1758, 389, 22270, 4154, 1345, 20, 16, 203, 3639, 1758, 389, 8584, 292, 975, 16, 203, 3639, 2254, 5034, 389, 1154, 49, 474, 310, 16, 203, 3639, 2254, 5034, 389, 298, 5682, 2355, 16, 203, 3639, 2254, 5034, 389, 298, 5682, 38, 7146, 16, 203, 3639, 2254, 5034, 389, 1154, 5157, 774, 426, 5768, 395, 16, 203, 3639, 2254, 5034, 389, 3666, 14667, 38, 7146, 16, 203, 3639, 2254, 5034, 389, 5206, 14667, 38, 7146, 16, 203, 3639, 2254, 5034, 389, 266, 5768, 395, 17631, 1060, 38, 7146, 203, 683, 9454, 18035, 560, 3602, 2 ]
pragma solidity ^0.4.13; contract token { function mintToken(address target, uint256 mintedAmount); } contract owned { address public owner; function owned() { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { owner = newOwner; } } contract Crowdsale is owned { address public beneficiary; uint256 public preICOLimit; uint256 public totalLimit; uint256 public pricePreICO; uint256 public priceICO; bool preICOClosed = false; bool ICOClosed = false; bool preICOWithdrawn = false; bool ICOWithdrawn = false; bool public preICOActive = false; bool public ICOActive = false; uint256 public preICORaised; uint256 public ICORaised; uint256 public totalRaised; token public tokenReward; event FundTransfer(address backer, uint256 amount, bool isContribution); mapping(address => uint256) public balanceOf; function Crowdsale() { preICOLimit = 5000000 * 1 ether; totalLimit = 45000000 * 1 ether; //50m hard cap minus 2.5m for mining and minus 2.5m for bounty pricePreICO = 375; priceICO = 250; } function init(address beneficiaryAddress, token tokenAddress) onlyOwner { beneficiary = beneficiaryAddress; tokenReward = token(tokenAddress); } function () payable { require (preICOActive || ICOActive); uint256 amount = msg.value; require (amount >= 0.05 * 1 ether); //0.05 - minimum contribution limit //mintToken method will work only for owner of the token. //So we need to execute transferOwnership from the token contract and pass ICO contract address as a parameter. //By doing so we will lock minting function to ICO contract only (so no minting will be available after ICO). if(preICOActive) { tokenReward.mintToken(msg.sender, amount * pricePreICO); preICORaised += amount; } if(ICOActive) { tokenReward.mintToken(msg.sender, amount * priceICO); ICORaised += amount; } balanceOf[msg.sender] += amount; totalRaised += amount; FundTransfer(msg.sender, amount, true); if(preICORaised >= preICOLimit) { preICOActive = false; preICOClosed = true; } if(totalRaised >= totalLimit) { preICOActive = false; ICOActive = false; preICOClosed = true; ICOClosed = true; } } function startPreICO() onlyOwner { require(!preICOClosed); require(!preICOActive); require(!ICOClosed); require(!ICOActive); preICOActive = true; } function stopPreICO() onlyOwner { require(preICOActive); preICOActive = false; preICOClosed = true; } function startICO() onlyOwner { require(preICOClosed); require(!ICOClosed); require(!ICOActive); ICOActive = true; } function stopICO() onlyOwner { require(ICOActive); ICOActive = false; ICOClosed = true; } //withdrawal raised funds to beneficiary function withdrawFunds() onlyOwner { require ((!preICOWithdrawn && preICOClosed) || (!ICOWithdrawn && ICOClosed)); //withdraw results of preICO if(!preICOWithdrawn && preICOClosed) { if (beneficiary.send(preICORaised)) { preICOWithdrawn = true; FundTransfer(beneficiary, preICORaised, false); } } //withdraw results of ICO if(!ICOWithdrawn && ICOClosed) { if (beneficiary.send(ICORaised)) { ICOWithdrawn = true; FundTransfer(beneficiary, ICORaised, false); } } } }
0.05 - minimum contribution limit
require (amount >= 0.05 * 1 ether);
13,028,725
[ 1, 20, 18, 6260, 300, 5224, 24880, 1800, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 261, 8949, 1545, 374, 18, 6260, 380, 404, 225, 2437, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Contract based on https://docs.openzeppelin.com/contracts/3.x/erc721 // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract SpikySpaceFish is ERC721, Ownable { using Counters for Counters.Counter; Counters.Counter private _tokenIds; using SafeMath for uint256; /* Contract param */ uint256 public MAX_TOKEN=10000; uint256 public constant tokenPrice = 60000000000000000; //0.06 ETH on mint day /* Fairness param */ string public PROVENANCE = "";//IPFS adress to provenance file uint256 public startingIndexBlock;//block number at the sold out time or after REVEAL_TIMESTAMP time uint256 public startingIndex;//derived from startingIndexBlock uint256 public REVEAL_TIMESTAMP;//it is the maximun time after presale before reveal /* Presale and sale param */ uint public constant maxTokenPurchase = 10;//Per request uint256 constant public maxTokenPurchasePresale = 3;//Per whitekist account bool public saleIsActive = false;//required to be true to mint (even in presale) bool public privateSaleIsActive = false;//required to be true to mint in presale and false otherwise struct Whitelist { address addr; uint hasMinted;//nb of minted token } mapping(address => Whitelist) public whitelist; address[] public whitelistAddr; constructor() public ERC721("SpikySpaceFish", "SSF") { } function withdraw() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } /** * Set some Tokens aside */ struct ReserveList { address addr; uint nbOfToken;//nb of minted token } /* to be called 5 times */ function reserveToken() public onlyOwner { uint supply = totalSupply()+1; uint i; uint j; ReserveList[] memory _acc = new ReserveList[](5); _acc[0].addr=msg.sender; _acc[0].nbOfToken=20; _acc[1].addr= address(0xa5cbD48F84BB626B32b49aC2c7479b88Cd871567);_acc[1].nbOfToken=5; _acc[2].addr= address(0xc06695Ce0AED905A3a3C24Ce99ab75C4bd8b7466);_acc[2].nbOfToken=5; _acc[3].addr= address(0xe72bf39949CD3D56031895c152B2168ca73b50e9);_acc[3].nbOfToken=5; _acc[4].addr= address(0x425f1E9bcCdC796f36190b5933d6319c78BA9f19);_acc[4].nbOfToken=5; for (j=0;j<_acc.length;j++){ for (i = 0; i < _acc[j].nbOfToken; i++) { _safeMint(_acc[j].addr, supply); supply++; } } } /** * RevealTime set manually by the owner at he begining of the presale . * Ovverdies if the collection is sold out */ function setRevealTimestamp(uint256 revealTimeStampInSec) public onlyOwner { REVEAL_TIMESTAMP = block.timestamp + revealTimeStampInSec; } /* * Set provenance. It is calculated and saved before the presale. */ function setProvenanceHash(string memory provenanceHash) public onlyOwner { PROVENANCE = provenanceHash; } /* * To manage the reveal -The baseUri will be modified after * the startingIndex has been calculated. */ function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } /* * Pause sale if active, make active if paused */ function flipSaleState() public onlyOwner returns (bool) { saleIsActive = !saleIsActive; return saleIsActive; } /* * Pause presale if active, make active if paused - * Presale for whitelisted only */ function flipPrivateSaleState() public onlyOwner { privateSaleIsActive = !privateSaleIsActive; } /** * Mints token */ function mintToken(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active"); require(totalSupply().add(numberOfTokens) <= MAX_TOKEN, "Purchase would exceed max supply."); require(tokenPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); if(privateSaleIsActive) { require(numberOfTokens <= maxTokenPurchasePresale, "Presale Purchase would not exeed maxTokenWhiteList at a time"); require(isWhitelisted(msg.sender), "Is not whitelisted"); require(whitelist[msg.sender].hasMinted.add(numberOfTokens) <= maxTokenPurchasePresale, "Above presale maxToken."); whitelist[msg.sender].hasMinted = whitelist[msg.sender].hasMinted.add(numberOfTokens); } else { require(numberOfTokens <= maxTokenPurchase, "Can only mint maxTokenPurchase tokens at a time"); } for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply()+1; if (totalSupply() <= MAX_TOKEN) { _safeMint(msg.sender, mintIndex); } } // If we haven't set the starting index and this is either 1) the last saleable token or 2) the first token to be sold after // the end of pre-sale, set the starting index block if (startingIndexBlock == 0 && (totalSupply() == MAX_TOKEN || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } } /** * Set the starting index once the startingBlox index is known */ function setStartingIndex() public { require(startingIndex == 0, "Starting index is already set"); require(startingIndexBlock != 0, "Starting index block must be set"); startingIndex = uint(blockhash(startingIndexBlock)) % MAX_TOKEN; // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes) if (block.number.sub(startingIndexBlock) > 255) { startingIndex = uint(blockhash(block.number - 1)) % MAX_TOKEN; } // Prevent default sequence if (startingIndex == 0) { startingIndex = startingIndex.add(1); } } /** * Set the starting index block for the collection, essentially unblocking * setting starting index */ function emergencySetStartingIndexBlock() public onlyOwner { require(startingIndex == 0, "Starting index is already set"); startingIndexBlock = block.number; } /******** WHITELIST */ /** * @dev add an address to the whitelist * @param addr address */ function addAddressToWhitelist(address addr) onlyOwner public returns(bool success) { require(!isWhitelisted(addr), "Already whitelisted"); whitelist[addr].addr = addr; whitelist[addr].hasMinted = 0; success = true; whitelistAddr.push(addr); } /* * Add an array of adresses */ function addAddressesToWhitelist(address[] memory addrs) onlyOwner public returns(bool success) { for(uint i = 0; i < addrs.length; i++) { addAddressToWhitelist(addrs[i]); } } /* * Are you an happy Early Believer? */ function isWhitelisted(address addr) public view returns (bool isWhiteListed) { return whitelist[addr].addr == addr; } /* * Returns the list of Whitelisted / Early Believers */ function getWhiteListedAdrrs() view public returns(address[] memory ) { return whitelistAddr; } function getWhitelistedData(address _address) view public returns ( uint) { return ( whitelist[_address].hasMinted); } /* * Number of whitemisted / Early Believers */ function countWhitelisted() view public returns (uint) { return whitelistAddr.length; } /******** UTILS */ /** * Get owner list order by token nb */ function getOwners() public onlyOwner returns(address[] memory ) { address[] memory _owners = new address[](totalSupply()); uint i; for (i = 1; i <= totalSupply(); i++) { _owners[i-1]=ownerOf(i); } return _owners; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../GSN/Context.sol"; import "./IERC721.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./IERC721Receiver.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../utils/EnumerableSet.sol"; import "../../utils/EnumerableMap.sol"; import "../../utils/Strings.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name, string memory symbol) { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // If there is no base URI, return the token URI. if (bytes(_baseURI).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(_baseURI, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mecanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transfered from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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.7.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.7.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.7.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { return _get(map, key, "EnumerableMap: nonexistent key"); } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint256(value))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key)))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
required to be true to mint in presale and false otherwise
bool public privateSaleIsActive = false;
1,666,173
[ 1, 4718, 358, 506, 638, 358, 312, 474, 316, 4075, 5349, 471, 629, 3541, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1426, 1071, 3238, 30746, 2520, 3896, 273, 629, 31, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6 <0.7.0; import "./interfaces/IPollenDAO.sol"; import "./interfaces/IPollen.sol"; import "./interfaces/IRateQuoter.sol"; import "./lib/AddressSet.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; /** * @title PollenDAO Contract * @notice The main Pollen DAO contract * @author gtlewis, scorpion9979, vkonst */ contract PollenDAO_v1 is Initializable, ReentrancyGuardUpgradeSafe, IPollenDAO { using AddressSet for AddressSet.Set; using SafeMath for uint256; using SafeERC20 for IERC20; /** * @notice Type for representing a token proposal * @member proposalType The type of proposal (e.g., Invest, Divest) * @member assetTokenType The type of the asset token (e.g., ERC20) * @member assetTokenAddress The address of the asset token * @member assetTokenAmount The minimum (or exact) amount of the asset token being proposed to invest (or divest) * @member pollenAmount The exact (or minimum) amount of the Pollen being proposed to pay (or receive) * @member descriptionCid The IPFS CID hash of the proposal description text * @member submitter The submitter of the proposal * @member snapshotId The id of the snapshot storing balances during proposal submission * @member voters Addresses which voted on the proposal * @member yesVotes The total of yes votes for the proposal in Pollens * @member noVotes The total of no votes for the proposal in Pollens * @member votingExpiry The expiry timestamp for proposal voting * @member executionOpen The starting timestamp for proposal execution * @member executionExpiry The expiry timestamp for proposal execution * @member status The status of the proposal */ // TODO: optimize slot usage after the Proposal struct gets finalized struct Proposal { ProposalType proposalType; TokenType assetTokenType; address assetTokenAddress; uint256 assetTokenAmount; uint256 pollenAmount; string descriptionCid; address submitter; uint256 snapshotId; mapping(address => VoterState) voters; uint256 yesVotes; uint256 noVotes; uint256 votingExpiry; uint256 executionOpen; uint256 executionExpiry; ProposalStatus status; } uint constant maxDelay = 60 * 60 * 24 * 365; /** * @dev Reserved for possible storage structure changes */ uint256[49] private __gap; address private _owner; /** * @dev The Pollen token contract instance (private) */ IPollen private _pollen; /** * @dev The proposals (private) */ mapping(uint256 => Proposal) private _proposals; /** * @dev The count of proposals (private) */ uint256 private _proposalCount; /** * @dev The set of assets that the DAO holds (private) */ AddressSet.Set private _assets; /** * @dev The quorum required to pass a proposal vote in % points (private) */ uint256 private _quorum; /** * @dev The number of seconds until voting expires after proposal submission (private) */ uint256 private _votingExpiryDelay; /** * @dev The number of seconds until execution opens after proposal voting expires (private) */ uint256 private _executionOpenDelay; /** * @dev The number of seconds until execution expires after proposal execution opens (private) */ uint256 private _executionExpiryDelay; IRateQuoter private _rateQuoter; modifier onlyOwner() { require(_owner == msg.sender, "PollenDAO: unauthorised call"); _; } modifier revertZeroAddress(address _address) { require(_address != address(0), "PollenDAO: invalid token address"); _; } /** * @notice Initializer deploys a new Pollen instance and becomes owner of Pollen token (public) * @param pollen Address ot the Pollen token contract instance * @param quorum The quorum required to pass a proposal vote in % points * @param votingExpiryDelay The number of seconds until voting expires after proposal submission * @param executionOpenDelay The number of seconds until execution opens after voting expires * @param executionExpiryDelay The number of seconds until execution expires after it opens */ function initialize( address pollen, uint256 quorum, uint256 votingExpiryDelay, uint256 executionOpenDelay, uint256 executionExpiryDelay ) external initializer { __ReentrancyGuard_init_unchained(); _owner = msg.sender; _pollen = IPollen(pollen); _setParams(quorum, votingExpiryDelay, executionOpenDelay, executionExpiryDelay); } /// @inheritdoc IPollenDAO function version() external pure override returns (string memory) { return "v1"; } /// @inheritdoc IPollenDAO function getPollenAddress() external view override returns(address) { return _getPollenAddress(); } /// @inheritdoc IPollenDAO function getProposalData(uint256 proposalId) external view override returns( ProposalType proposalType, TokenType assetTokenType, address assetTokenAddress, uint256 assetTokenAmount, uint256 pollenAmount, string memory descriptionCid, address submitter, uint256 snapshotId, uint256 yesVotes, uint256 noVotes, ProposalStatus status ) { require(proposalId < _proposalCount, "PollenDAO: invalid proposal id"); Proposal memory proposal = _proposals[proposalId]; return ( proposal.proposalType, proposal.assetTokenType, proposal.assetTokenAddress, proposal.assetTokenAmount, proposal.pollenAmount, proposal.descriptionCid, proposal.submitter, proposal.snapshotId, proposal.yesVotes, proposal.noVotes, proposal.status ); } /// @inheritdoc IPollenDAO function getProposalTimestamps(uint256 proposalId) external view override returns( uint256 votingExpiry, uint256 executionOpen, uint256 executionExpiry ) { require(proposalId < _proposalCount, "PollenDAO: invalid proposal id"); Proposal memory proposal = _proposals[proposalId]; return ( proposal.votingExpiry, proposal.executionOpen, proposal.executionExpiry ); } /// @inheritdoc IPollenDAO function getVoterState(uint256 proposalId) external view override returns(VoterState) { require(proposalId < _proposalCount, "PollenDAO: invalid proposal id"); return (_proposals[proposalId].voters[msg.sender]); } /// @inheritdoc IPollenDAO function getProposalCount() external view override returns(uint256) { return _proposalCount; } /// @inheritdoc IPollenDAO function getAssets() external view override returns (address[] memory) { return _assets.elements; } /// @inheritdoc IPollenDAO function getVotingExpiryDelay() external view override returns(uint256) { return _votingExpiryDelay; } /// @inheritdoc IPollenDAO function getExecutionOpenDelay() external view override returns(uint256) { return _executionOpenDelay; } /// @inheritdoc IPollenDAO function getExecutionExpiryDelay() external view override returns(uint256) { return _executionExpiryDelay; } /// @inheritdoc IPollenDAO function getQuorum() external view override returns(uint256) { return _quorum; } /// @inheritdoc IPollenDAO function submit( ProposalType proposalType, TokenType assetTokenType, address assetTokenAddress, uint256 assetTokenAmount, uint256 pollenAmount, string memory descriptionCid ) external override revertZeroAddress(assetTokenAddress) { // TODO: validate IPFS CID format for descriptionCid require(proposalType < ProposalType.Last, "PollenDAO: invalid proposal type"); require(assetTokenType < TokenType.Last, "PollenDAO: invalid asset type"); require(_assets.contains(assetTokenAddress), "PollenDAO: unsupported asset"); require( assetTokenAddress != _getPollenAddress(), "PollenDAO: PLN can't be an asset" ); require( assetTokenAmount != 0 || pollenAmount != 0, "PollenDAO: both amounts are zero" ); uint256 proposalId = _proposalCount; uint256 votingExpiry = proposalId == 0 ? now : now + _votingExpiryDelay; uint256 executionOpen = proposalId == 0 ? votingExpiry : votingExpiry + _executionOpenDelay; Proposal memory proposal = Proposal( proposalType, assetTokenType, assetTokenAddress, assetTokenAmount, pollenAmount, descriptionCid, msg.sender, _pollen.snapshot(), // voters omitted (as it's mapping) 0, // yesVotes 0, // noVotes, votingExpiry, executionOpen, executionOpen + _executionExpiryDelay, ProposalStatus.Submitted ); _proposals[proposalId] = proposal; _proposalCount = uint256(proposalId) + 1; emit Submitted( proposalId, proposalType, msg.sender, proposal.snapshotId ); _addVote( proposalId, msg.sender, true, _pollen.balanceOfAt(msg.sender, proposal.snapshotId) ); } /// @inheritdoc IPollenDAO function voteOn(uint256 proposalId, bool vote) external override { require(proposalId < _proposalCount, "PollenDAO: invalid proposal id"); require( _proposals[proposalId].status == ProposalStatus.Submitted, "PollenDAO: invalid proposal status" ); require(now < _proposals[proposalId].votingExpiry, "PollenDAO: vote expired"); uint256 balance = _pollen.balanceOfAt(msg.sender, _proposals[proposalId].snapshotId); require(balance > 0, "PollenDAO: no voting tokens"); _addVote(proposalId, msg.sender, vote, balance); } /// @inheritdoc IPollenDAO function execute(uint256 proposalId) external override nonReentrant { require(proposalId < _proposalCount, "PollenDAO: invalid proposal id"); Proposal memory proposal = _proposals[proposalId]; require( proposal.status == ProposalStatus.Submitted, "PollenDAO: invalid proposal status" ); require(now >= proposal.votingExpiry, "PollenDAO: vote not expired"); require( ( proposal.yesVotes.add(proposal.noVotes) > _pollen.totalSupplyAt(proposal.snapshotId).mul(_quorum).div(100) ) || proposalId == 0, "PollenDAO: vote did not reach quorum" ); require( proposal.yesVotes > proposal.noVotes || proposalId == 0, "PollenDAO: vote failed" ); require(now >= proposal.executionOpen, "PollenDAO: execution not open"); require( now < proposal.executionExpiry || proposalId == 0, "PollenDAO: execution expired" ); require( proposal.submitter == msg.sender, "PollenDAO: only submitter can execute" ); IERC20 asset = IERC20(proposal.assetTokenAddress); (uint256 assetRate, ) = _rateQuoter.quotePrice(proposal.assetTokenAddress); (uint256 plnRate, ) = _rateQuoter.quotePrice(_getPollenAddress()); // [ETH/PLN] / [ETH/ASSET] = [ASSET/PLN] uint256 rate = plnRate.mul(1e4).div(assetRate); if (proposal.proposalType == ProposalType.Invest) { // [PLN] * [ASSET/PLN] = [ASSET] uint256 assetTokenAmount = proposal.pollenAmount.mul(rate).div(1e4); if (proposal.assetTokenAmount > assetTokenAmount) { assetTokenAmount = proposal.assetTokenAmount; } // OK to send Pollen first as long as the asset received in the end _pollen.mint(proposal.pollenAmount); _pollen.transfer(msg.sender, proposal.pollenAmount); asset.safeTransferFrom( msg.sender, address(this), assetTokenAmount ); emit Executed(proposalId, assetTokenAmount); } else if (proposal.proposalType == ProposalType.Divest) { // [ASSET] / [ASSET/PLN] = PLN uint256 pollenAmount = proposal.assetTokenAmount.mul(1e4).div(rate); if (proposal.pollenAmount > pollenAmount) { pollenAmount = proposal.pollenAmount; } // OK to send assets first as long as Pollen received in the end asset.safeTransfer(msg.sender, proposal.assetTokenAmount); _pollen.burnFrom(msg.sender, pollenAmount); emit Executed(proposalId, pollenAmount); } else { revert("unsupported proposal type"); } _proposals[proposalId].status = ProposalStatus.Executed; } /// @inheritdoc IPollenDAO function redeem(uint256 pollenAmount) external override nonReentrant { require(pollenAmount != 0, "PollenDAO: can't redeem zero amount"); uint256 totalSupply = _pollen.totalSupply(); _pollen.burnFrom(msg.sender, pollenAmount); // TODO: cap the asset list to prevent unbounded loop for (uint256 i=0; i < _assets.elements.length; i++) { IERC20 asset = IERC20(_assets.elements[i]); if (address(asset) != address(0)) { uint256 assetBalance = asset.balanceOf(address(this)); if (assetBalance == 0) { continue; } uint256 assetTokenAmount = assetBalance.mul(pollenAmount).div(totalSupply); asset.transfer( msg.sender, assetTokenAmount > assetBalance ? assetBalance : assetTokenAmount ); } } emit Redeemed( msg.sender, pollenAmount ); } /// @inheritdoc IPollenDAO function addAsset(address asset) external override onlyOwner revertZeroAddress(asset) { require(!_assets.contains(asset), "PollenDAO: already added"); require(_assets.add(asset)); emit assetAdded(asset); } /// @inheritdoc IPollenDAO function removeAsset(address asset) external override onlyOwner revertZeroAddress(asset) { require(_assets.contains(asset), "PollenDAO: unknown asset"); require(IERC20(asset).balanceOf(address(this)) == 0, "PollenDAO: asset has balance"); require(_assets.remove(asset)); emit assetRemoved(asset); } /// @inheritdoc IPollenDAO function setOwner(address newOwner) external override onlyOwner { require(newOwner != address(0), "PollenDAO: invalid owner address"); address oldOwner = _owner; _owner = newOwner; emit NewOwner(newOwner, oldOwner); } /// @inheritdoc IPollenDAO function setParams( uint256 quorum, uint256 votingExpiryDelay, uint256 executionOpenDelay, uint256 executionExpiryDelay ) external override onlyOwner { _setParams(quorum, votingExpiryDelay, executionOpenDelay, executionExpiryDelay); } /// @inheritdoc IPollenDAO function setPriceQuoter(address newQuoter) external override onlyOwner { require(newQuoter != address(0), "PollenDAO: quoter address"); address oldQuoter = address(_rateQuoter); _rateQuoter= IRateQuoter(newQuoter); emit NewPriceQuoter(newQuoter, oldQuoter); } function _getPollenAddress() private view returns(address) { return address(_pollen); } function _setParams( uint256 quorum, uint256 votingExpiryDelay, uint256 executionOpenDelay, uint256 executionExpiryDelay ) internal { require(quorum <= 100, "PollenDAO: invalid quorum"); // TODO: Define realistic min's and max's require( votingExpiryDelay > 60 && votingExpiryDelay < maxDelay, "PollenDAO: invalid voting expiry" ); require( executionOpenDelay > 60 && executionOpenDelay < maxDelay, "PollenDAO: invalid exec open" ); require( executionExpiryDelay > 60 && executionExpiryDelay < maxDelay, "PollenDAO: invalid exec expiry" ); _quorum = quorum; _votingExpiryDelay = votingExpiryDelay; _executionOpenDelay = executionOpenDelay; _executionExpiryDelay = executionExpiryDelay; } /** * @dev _addVote (private) * @param proposalId The proposal ID * @param voter The voter address * @param vote The yes/no vote * @param amount The amount of tokens voting */ function _addVote(uint256 proposalId, address voter, bool vote, uint256 amount) private { // if voter had already voted on the proposal, and if so what his vote was. VoterState voterState = _proposals[proposalId].voters[voter]; // allows to change old vote if (voterState == VoterState.VotedYes) { _proposals[proposalId].yesVotes = _proposals[proposalId].yesVotes.sub(amount); } else if (voterState == VoterState.VotedNo) { _proposals[proposalId].noVotes = _proposals[proposalId].noVotes.sub(amount); } if (vote) { _proposals[proposalId].yesVotes = _proposals[proposalId].yesVotes.add(amount); _proposals[proposalId].voters[voter] = VoterState.VotedYes; } else { _proposals[proposalId].noVotes = _proposals[proposalId].noVotes.add(amount); _proposals[proposalId].voters[voter] = VoterState.VotedNo; } emit VotedOn(proposalId, voter, vote); } }
* @dev The count of proposals (private)/
uint256 private _proposalCount;
13,099,085
[ 1, 1986, 1056, 434, 450, 22536, 261, 1152, 13176, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 3238, 389, 685, 8016, 1380, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.11; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IERC20.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IWETH.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IBorrow.sol"; contract Stacking is Ownable{ using SafeMath for uint; uint8 projectRevenue; IUniswapV2Router02 public uniswapRouter; //initialization of Uni Router address public stacking; //initialization of the contract address variable address public proxy; //initialization of the contract address variable event LPsended(address owner, uint amount); constructor(address _uniswap) public { uniswapRouter = IUniswapV2Router02(_uniswap); //set the UNI Router instance with a specific address } /// @notice Define stacking contract address /// @param contractAddr the contract address referring to stacking.sol function setStackingAddress(address contractAddr) external onlyOwner { stacking = contractAddr ; } /// @notice Define proxy contract address /// @param contractAddr the contract address referring to ProxySimple.sol function setProxyAddress(address contractAddr) external onlyOwner { proxy = contractAddr ; } /// @notice Define the pourcentage of teh total balance allocated to project funding /// @param pourcentage the amount to divide by 100 when sending funds to projects function setProjectRevenue(uint8 pourcentage) external onlyOwner { projectRevenue = pourcentage ; } /// @notice fetch an ERC20 balance of the stacking contract /// @param token address /// @return contract's balance function getBalance(IERC20 token) public view returns (uint) { return IERC20(token).balanceOf(address(this)); } /// @notice fetch an ERC20 token decimals /// @param token address /// return decimals uint8 function getDecimals(address token) external view returns(uint8 decimals) { decimals = IERC20(token).decimals(); } /// @notice fetch an ERC20 token symbol /// @dev /// @param token address /// return symbol string function getSymbol(address token) external view returns(string memory symbol) { symbol = IERC20(token).symbol(); } /// @notice transfer an ERC20 token to the addr of your choice /// @dev usefull to send funds to our contracts /// @param token, proxySimple, amountIn function receiveERC20(IERC20 token, address usr, uint amountIn) external onlyOwner{ IERC20(token).transferFrom(msg.sender,usr,amountIn); } /// @notice send ERC20 tokens to voted projects for fundings /// @dev multiplied by a state variable then divided by 100 as a pourcentage /// @param token, vote, usr the erc20 token address and project to fund address function fooProjects(IERC20 token, address voteContract) external onlyOwner { address toFund = IBorrow(voteContract).receiverAddress(); uint rewards = getBalance(token).mul(projectRevenue).div(100); IERC20(token).transfer(toFund,rewards); } /// @notice approve an ERC20 token amount to uniswap Router /// @dev function restricted to the owner of the contract /// @param token, amountIn token address and amount to approve /// @return amountIn the approved amount for uniswap Router function approveERC20Uni(IERC20 token, uint amountIn) onlyOwner external returns(uint){ IERC20(token).approve(address(uniswapRouter), amountIn); return amountIn; } ///@notice send Lp to an address reponsible for placing LP in liquidity pool to gains rewards ///@dev the address shoulb be trusted and defined by the contract owner ///@param lpToken, owner, amount token address, the account address to receive LPs and the LPs amount function sendLP(address lpToken, address owner, uint amount) external onlyOwner { IERC20(lpToken).transfer(owner, amount); emit LPsended(owner, amount); } /// @notice swap ERC20 tokens with an exact input to a desired ouput /// @dev an output minimum amount is required as parameter, /// it reverts if the swap give an output below amountOutMin /// @param tokenA, tokenB, amountIn, amountOutMin, deadline function swapTokens( address tokenA, address tokenB, uint amountIn, uint amountOutMin, uint deadline ) external onlyOwner { address[] memory path = new address[](2); // Création du path path[0] = address(tokenA); // initialisation du path avec l'address du token à échanger path[1] = address(tokenB); // initialisation du path avec l'address du WETH d'Uniswap //approveERC20Uni() before calling this function //fetch uniswap Router function swapExactTokensForTokens() with same params uniswapRouter.swapExactTokensForTokens( amountIn, amountOutMin, path, stacking, deadline ); // effectuer le swap, ETH sera transférer directement au contrat stacking } /// @notice add ERC20 tokens in liquidity pools /// @dev outputs minimum amounts are required as parameter, /// it reverts if the swap give an output below amountTokenAMin or amountTokenBMin /// @param tokenA, tokenB, amountTokenADesired, amountTokenBDesired, amountTokenAMin, amountTokenBMin, deadline /// return amountA, amountB added in liquidity & liquidity tokens received by stacking contract function addLiquidity( address tokenA, address tokenB, uint amountTokenADesired, uint amountTokenBDesired, uint amountTokenAMin, uint amountTokenBMin, uint deadline ) external payable onlyOwner returns (uint amountTokenA, uint amountTokenB, uint liquidity) { //fetch uniswap Router function addLiquidity() with same params return uniswapRouter.addLiquidity(tokenA, tokenB, amountTokenADesired,amountTokenBDesired, amountTokenAMin, amountTokenBMin, stacking, deadline); } /// @notice remove ERC20 tokens from liquidity pools /// @dev liquidity tokens amount & outputs minimum amounts are required as parameter, /// it reverts if the swap give an output below amountAMin or amountBMin /// @param tokenA, tokenB, amountTokenADesired, amountTokenBDesired, amountTokenAMin, amountTokenBMin, deadline /// @return amountA amountB received by stacking contract function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, uint deadline ) external onlyOwner returns (uint amountA, uint amountB) { //fetch uniswap Router function addLiquidity() with same params return uniswapRouter.removeLiquidity(tokenA,tokenB,liquidity,amountAMin,amountBMin,stacking,deadline); } }
@notice Define stacking contract address @param contractAddr the contract address referring to stacking.sol
function setStackingAddress(address contractAddr) external onlyOwner { stacking = contractAddr ; }
12,664,631
[ 1, 11644, 2110, 310, 6835, 1758, 225, 6835, 3178, 326, 6835, 1758, 1278, 20245, 358, 2110, 310, 18, 18281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 915, 444, 2624, 310, 1887, 12, 2867, 6835, 3178, 13, 3903, 1338, 5541, 288, 203, 225, 2110, 310, 273, 6835, 3178, 274, 203, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./@openzeppelin/contracts/math/SafeMath.sol"; import "./@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./@interface/IPureFlash.sol"; import "./@interface/IPureVault.sol"; import "./@libs/ERC20Detailed.sol"; contract PureFlashVault is ERC20,ReentrancyGuard,IPureVault{ using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 m_token; string m_symbol; address m_factory; address m_profitpool; uint256 m_profit_rate; uint256 m_loan_fee; uint256 constant MAX_LOAN_FEE = 100*10000; //记录存款数据 uint256 m_total_deposits; mapping(address=>uint256) m_users_deposit; //记录用户的历史利润 mapping(address=>uint256) m_users_hprofit; constructor(address factory,string memory sym,address token,address profitpool,uint256 profitrate,uint256 loadfee) ERC20(string(abi.encodePacked("PFL-", ERC20Detailed(token).name())), string(abi.encodePacked("u", ERC20Detailed(token).symbol())) ){ m_symbol = sym; m_factory = factory; m_token = IERC20(token); m_profitpool = profitpool; m_profit_rate = profitrate; m_loan_fee = loadfee; } modifier onlyFactory(){ require(msg.sender == m_factory,"NEED_FROM_FACTORY"); _; } function changeSymbol(string memory sym) onlyFactory external override returns(bool){ m_symbol = sym; return true; } function setPool(address profitpool) onlyFactory external override returns(bool){ m_profitpool = profitpool; return true; } function setProfitRate(uint256 profitrate) onlyFactory external override returns(bool){ m_profit_rate = profitrate; return true; } function setLoanFee(uint256 loanfee) onlyFactory external override returns(bool){ m_loan_fee = loanfee; return true; } function balance() public view override returns(uint256){ return m_token.balanceOf(address(this)); } function vaultInfo() public view returns(string memory sym,address addr,uint256 tvl,uint256 fee,uint256 s,uint256 td){ sym = m_symbol; addr = address(m_token); tvl = balance(); fee = minFee(100*1e18); s = sharePrice(); td = m_total_deposits; } //获取某个用户的所有相关信息,便于UI显示 function userInfo(address user) public view returns(string memory sym,address addr,uint256 tvl,uint256 b,uint256 d,uint256 td,uint256 s,uint256 hp){ sym = m_symbol; addr = address(m_token); tvl = balance(); b = balanceOf(user); d = m_users_deposit[user]; td = m_total_deposits; s = sharePrice(); hp = m_users_hprofit[user]; } /** * @dev 获取每份基础资产对应的份额 */ function sharePrice() public view returns (uint256) { return totalSupply() > 0 ? balance().mul(1e18).div(totalSupply()) : 0; } function depositFor(uint256 amount,address user) nonReentrant public returns(uint256){ //将amount数量的fea转入当前池子 m_token.safeTransferFrom(msg.sender, address(this), amount); uint256 pool = balance(); // 份额 = 0 uint256 shares = 0; // 如果当前合约的总量为0,或者总的份额为0(防止合约上有余额) if (pool == 0 || totalSupply() == 0) { // 份额 = 数额 shares = amount; } else { // 份额 = 数额 * 总量 / 池子数量 shares = (amount.mul(totalSupply())).div(pool); } // 为调用者铸造份额 _mint(user, shares); //保存存款数据 m_total_deposits = m_total_deposits.add(amount); m_users_deposit[user] = m_users_deposit[user].add(amount); return shares; } //这里不应该用nonReentrant function deposit(uint256 amount) /*nonReentrant*/ public returns(uint256){ return depositFor(amount,msg.sender); } function withdraw(uint256 shares) nonReentrant public returns(uint256){ address user = msg.sender; // 当前合约和控制器合约在基础资产的余额 * 份额 / 总量 uint256 amount = (balance().mul(shares)).div(totalSupply()); // 销毁份额 _burn(user, shares); //打款给用户 m_token.safeTransfer(user, amount); //记录更改前的deposit值 uint256 oldDeposit = m_users_deposit[user]; //当取出金额大于本金时,记录历史利润 if(amount > oldDeposit){ m_users_hprofit[user] = m_users_hprofit[user].add(amount.sub(oldDeposit)); } //更新存款数据(可能有,存款为0,但是利润不为0的情况),这种情况不能revert m_total_deposits = m_total_deposits > amount ? m_total_deposits.sub(amount) : 0; m_users_deposit[user] = oldDeposit > amount ? oldDeposit.sub(amount) : 0; return amount; } //动态利息算法:千分之三*当前借贷量/池子总量 function minFee(uint256 amount) public view returns(uint256){ uint256 pool = m_token.balanceOf(address(this)); return pool > 0 ? m_loan_fee.mul(amount).div(pool).div(MAX_LOAN_FEE) : 0; } function startFlashLoan(address dealer,uint256 amount,bytes calldata data) nonReentrant public{ uint256 preBalance = m_token.balanceOf(address(this)); //把借贷的资产转给贷款人 m_token.safeTransfer(dealer,amount); //调用借贷者自己的借贷函数 uint256 rAmount = amount.add(minFee(amount)); IPureFlash(dealer).OnFlashLoan(address(m_token),amount,rAmount, data); //开始检查是否返款 uint256 curBalance = m_token.balanceOf(address(this)); uint256 profit = curBalance.sub(preBalance); //利润一定要大于当前最低利息 require(profit>minFee(amount),"NEED_TRANSFER_BACK"); //利润的10%发送给社区 uint256 pfProfit = profit.mul(m_profit_rate).div(10000); m_token.safeTransfer(m_profitpool,pfProfit); } }
动态利息算法:千分之三*当前借贷量/池子总量
function minFee(uint256 amount) public view returns(uint256){ uint256 pool = m_token.balanceOf(address(this)); return pool > 0 ? m_loan_fee.mul(amount).div(pool).div(MAX_LOAN_FEE) : 0; }
13,021,072
[ 1, 166, 237, 106, 167, 227, 228, 166, 235, 107, 167, 228, 112, 168, 111, 250, 167, 116, 248, 176, 125, 253, 166, 240, 230, 166, 235, 233, 165, 122, 238, 165, 121, 236, 166, 126, 246, 166, 236, 240, 166, 227, 258, 169, 117, 120, 170, 234, 242, 19, 167, 114, 259, 166, 260, 243, 167, 227, 124, 170, 234, 242, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1131, 14667, 12, 11890, 5034, 3844, 13, 1071, 1476, 1135, 12, 11890, 5034, 15329, 203, 377, 2254, 5034, 2845, 273, 312, 67, 2316, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 377, 327, 225, 2845, 405, 374, 692, 312, 67, 383, 304, 67, 21386, 18, 16411, 12, 8949, 2934, 2892, 12, 6011, 2934, 2892, 12, 6694, 67, 1502, 1258, 67, 8090, 41, 13, 294, 374, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: MIT pragma solidity 0.8.6; /* This contract implements a DAO, it's been loosely based on Compound's GovernorAlpha. It supports multiple options per proposal and multiple actions per option. It leverages the `Voters` contract for snapshots of voting power. It supports gasless voting with voteBySig / EIP-712. */ import './interfaces/IVoters.sol'; contract DAO { struct Proposal { uint id; address proposer; string title; string description; string[] optionsNames; bytes[][] optionsActions; uint[] optionsVotes; uint startAt; uint endAt; uint executableAt; uint executedAt; uint snapshotId; uint votersSupply; bool cancelled; } event Proposed(uint indexed proposalId); event Voted(uint indexed proposalId, address indexed voter, uint optionId); event Executed(address indexed to, uint value, bytes data); event ExecutedProposal(uint indexed proposalId, uint optionId, address executer); bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint optionId)"); uint public minBalanceToPropose; uint public minPercentQuorum; uint public minVotingTime; uint public minExecutionDelay; IVoters public voters; uint public proposalsCount; mapping(uint => Proposal) private proposals; mapping(uint => mapping(address => uint)) public proposalVotes; mapping (address => uint) private latestProposalIds; constructor( address _voters, uint _minBalanceToPropose, uint _minPercentQuorum, uint _minVotingTime, uint _minExecutionDelay ) { voters = IVoters(_voters); minBalanceToPropose = _minBalanceToPropose; minPercentQuorum = _minPercentQuorum; minVotingTime = _minVotingTime; minExecutionDelay = _minExecutionDelay; } function proposal(uint index) public view returns (uint, address, string memory, uint, uint, uint, uint, bool) { Proposal storage p = proposals[index]; return ( p.id, p.proposer, p.title, p.startAt, p.endAt, p.executableAt, p.executedAt, p.cancelled ); } function proposalDetails(uint index) public view returns (string memory, uint, uint, string[] memory, bytes[][] memory, uint[] memory) { return ( proposals[index].description, proposals[index].snapshotId, proposals[index].votersSupply, proposals[index].optionsNames, proposals[index].optionsActions, proposals[index].optionsVotes ); } function propose(string calldata title, string calldata description, uint votingTime, uint executionDelay, string[] calldata optionNames, bytes[][] memory optionActions) external returns (uint) { uint snapshotId = voters.snapshot(); require(voters.votesAt(msg.sender, snapshotId) >= minBalanceToPropose, "<balance"); require(optionNames.length == optionActions.length && optionNames.length > 0 && optionNames.length <= 100, "option len match or count"); require(optionActions[optionActions.length - 1].length == 0, "last option, no action"); require(votingTime >= minVotingTime, "<voting time"); require(executionDelay >= minExecutionDelay, "<exec delay"); // Check the proposing address doesn't have an other active proposal uint latestProposalId = latestProposalIds[msg.sender]; if (latestProposalId != 0) { require(block.timestamp > proposals[latestProposalId].endAt, "1 live proposal max"); } // Add new proposal proposalsCount += 1; Proposal storage newProposal = proposals[proposalsCount]; newProposal.id = proposalsCount; newProposal.proposer = msg.sender; newProposal.title = title; newProposal.description = description; newProposal.startAt = block.timestamp; newProposal.endAt = block.timestamp + votingTime; newProposal.executableAt = block.timestamp + votingTime + executionDelay; newProposal.snapshotId = snapshotId; newProposal.votersSupply = voters.totalSupplyAt(snapshotId); newProposal.optionsNames = new string[](optionNames.length); newProposal.optionsVotes = new uint[](optionNames.length); newProposal.optionsActions = optionActions; for (uint i = 0; i < optionNames.length; i++) { require(optionActions[i].length <= 10, "actions length > 10"); newProposal.optionsNames[i] = optionNames[i]; } latestProposalIds[msg.sender] = newProposal.id; emit Proposed(newProposal.id); return newProposal.id; } function proposeCancel(uint proposalId, string memory title, string memory description) external returns (uint) { uint snapshotId = voters.snapshot(); require(voters.votesAt(msg.sender, snapshotId) >= minBalanceToPropose, "<balance"); // Check the proposing address doesn't have an other active proposal uint latestProposalId = latestProposalIds[msg.sender]; if (latestProposalId != 0) { require(block.timestamp > proposals[latestProposalId].endAt, "1 live proposal max"); } // Add new proposal proposalsCount += 1; Proposal storage newProposal = proposals[proposalsCount]; newProposal.id = proposalsCount; newProposal.proposer = msg.sender; newProposal.title = title; newProposal.description = description; newProposal.startAt = block.timestamp; newProposal.endAt = block.timestamp + 86400; // 24 hours newProposal.executableAt = block.timestamp + 86400; // Executable immediately newProposal.snapshotId = snapshotId; newProposal.votersSupply = voters.totalSupplyAt(snapshotId); newProposal.optionsNames = new string[](2); newProposal.optionsVotes = new uint[](2); newProposal.optionsActions = new bytes[][](2); newProposal.optionsNames[0] = "Cancel Proposal"; newProposal.optionsNames[1] = "Do Nothing"; newProposal.optionsActions[0] = new bytes[](1); newProposal.optionsActions[1] = new bytes[](0); newProposal.optionsActions[0][0] = abi.encode( address(this), 0, abi.encodeWithSignature("cancel(uint256)", proposalId) ); latestProposalIds[msg.sender] = newProposal.id; emit Proposed(newProposal.id); return newProposal.id; } function vote(uint proposalId, uint optionId) external { _vote(msg.sender, proposalId, optionId); } function voteBySig(uint proposalId, uint optionId, uint8 v, bytes32 r, bytes32 s) external { uint chainId; assembly { chainId := chainid() } bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes("Thorstarter DAO")), chainId, address(this))); bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, optionId)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address voter = ecrecover(digest, v, r, s); require(voter != address(0), "invalid signature"); _vote(voter, proposalId, optionId); } function _vote(address voter, uint proposalId, uint optionId) private { Proposal storage p = proposals[proposalId]; require(block.timestamp < p.endAt, "voting ended"); require(proposalVotes[proposalId][voter] == 0, "already voted"); p.optionsVotes[optionId] = p.optionsVotes[optionId] + voters.votesAt(voter, p.snapshotId); proposalVotes[proposalId][voter] = optionId + 1; emit Voted(proposalId, voter, optionId); } // Executes an un-executed, with quorum, ready to be executed proposal // If the pre-conditions are met, anybody can call this // Part of this is establishing which option "won" and if quorum was reached function execute(uint proposalId) external { Proposal storage p = proposals[proposalId]; require(p.executedAt == 0, "already executed"); require(block.timestamp > p.executableAt, "not yet executable"); require(!p.cancelled, "proposal cancelled"); require(p.optionsVotes.length >= 2, "not a proposal"); p.executedAt = block.timestamp; // Mark as executed now to prevent re-entrancy // Pick the winning option (the one with the most votes, defaulting to the "Against" (last) option uint votesTotal; uint winningOptionIndex = p.optionsNames.length - 1; // Default to "Against" uint winningOptionVotes = 0; for (int i = int(p.optionsVotes.length) - 1; i >= 0; i--) { uint votes = p.optionsVotes[uint(i)]; votesTotal = votesTotal + votes; // Use greater than (not equal) to avoid a proposal with 0 votes // to default to the 1st option if (votes > winningOptionVotes) { winningOptionIndex = uint(i); winningOptionVotes = votes; } } require((votesTotal * 1e12) / p.votersSupply > minPercentQuorum, "not at quorum"); // Run all actions attached to the winning option for (uint i = 0; i < p.optionsActions[winningOptionIndex].length; i++) { (address to, uint value, bytes memory data) = abi.decode( p.optionsActions[winningOptionIndex][i], (address, uint, bytes) ); (bool success,) = to.call{value: value}(data); require(success, "action reverted"); emit Executed(to, value, data); } emit ExecutedProposal(proposalId, winningOptionIndex, msg.sender); } function setMinBalanceToPropose(uint value) external { require(msg.sender == address(this), "!DAO"); minBalanceToPropose = value; } function setMinPercentQuorum(uint value) external { require(msg.sender == address(this), "!DAO"); minPercentQuorum = value; } function setMinVotingTime(uint value) external { require(msg.sender == address(this), "!DAO"); minVotingTime = value; } function setMinExecutionDelay(uint value) external { require(msg.sender == address(this), "!DAO"); minExecutionDelay = value; } function setVoters(address newVoters) external { require(msg.sender == address(this), "!DAO"); voters = IVoters(newVoters); } function cancel(uint proposalId) external { require(msg.sender == address(this), "!DAO"); Proposal storage p = proposals[proposalId]; require(p.executedAt == 0 && !p.cancelled, "already executed or cancelled"); p.cancelled = true; } fallback() external payable { } } //SPDX-License-Identifier: MIT pragma solidity 0.8.6; interface IVoters { function snapshot() external returns (uint); function totalSupplyAt(uint snapshotId) external view returns (uint); function votesAt(address account, uint snapshotId) external view returns (uint); function balanceOf(address account) external view returns (uint); function balanceOfAt(address account, uint snapshotId) external view returns (uint); function donate(uint amount) external; } //SPDX-License-Identifier: MIT pragma solidity 0.8.6; /* This contract receives XRUNE tokens via the `deposit` method from the `LpTokenVestingKeeper` contract and let's investors part of a given snapshot (of the vXRUNE/Voters contract) claim their share of that XRUNE. */ import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import './interfaces/IDAO.sol'; import './interfaces/IVoters.sol'; contract VotersInvestmentDispenser { using SafeERC20 for IERC20; IERC20 public xruneToken; IDAO public dao; mapping(uint => uint) public snapshotAmounts; mapping(uint => uint) public claimedAmountsTotals; mapping(uint => mapping(address => uint)) public claimedAmounts; event Claim(uint snapshotId, address user, uint amount); event Deposit(uint snapshotId, uint amount); constructor(address _xruneToken, address _dao) { xruneToken = IERC20(_xruneToken); dao = IDAO(_dao); } // Calculated based on % of total vote supply at snapshotId, multiplied by amount available, minus claimed function claimable(uint snapshotId, address user) public view returns (uint) { IVoters voters = IVoters(dao.voters()); uint total = snapshotAmounts[snapshotId]; uint totalSupply = voters.totalSupplyAt(snapshotId); uint balance = voters.balanceOfAt(user, snapshotId); return ((total * balance) / totalSupply) - claimedAmounts[snapshotId][user]; } function claim(uint snapshotId) public { uint amount = claimable(snapshotId, msg.sender); if (amount > 0) { claimedAmounts[snapshotId][msg.sender] += amount; claimedAmountsTotals[snapshotId] += amount; xruneToken.safeTransfer(msg.sender, amount); emit Claim(snapshotId, msg.sender, amount); } } // Used by LpTokenVestingKeeper function deposit(uint snapshotId, uint amount) public { xruneToken.safeTransferFrom(msg.sender, address(this), amount); snapshotAmounts[snapshotId] += amount; emit Deposit(snapshotId, amount); } // Allow DAO to get tokens out and migrate to a different contract function withdraw(address token, uint amount) public { require(msg.sender == address(dao), '!DAO'); IERC20(token).safeTransfer(address(dao), amount); } } // 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.6; interface IDAO { function voters() external view returns (address); } // 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); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } //SPDX-License-Identifier: MIT pragma solidity 0.8.6; /* This contract claims amm lp shares from multiple `LpTokenVesting` contracts, removes liquidity, sells the non-XRUNE token, and distributes it's resulting XRUNE balance to an `VotersInvestmentDispenser` contract, a `Voters` contract, the grants multisig and the DAO. */ import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import './interfaces/IUniswapV2Router.sol'; import './interfaces/IUniswapV2Factory.sol'; import './interfaces/IDAO.sol'; import './interfaces/IVoters.sol'; import './interfaces/ILpTokenVesting.sol'; import './interfaces/IVotersInvestmentDispenser.sol'; contract LpTokenVestingKeeper { using SafeERC20 for IERC20; IVotersInvestmentDispenser public votersInvestmentDispenser; IUniswapV2Router public sushiRouter; IERC20 public xruneToken; IDAO public dao; address public grants; address public owner; uint public lpVestersCount; mapping(uint => address) public lpVesters; mapping(uint => uint) public lpVestersSnapshotIds; uint lastRun; event AddLpVester(address vester, uint snapshotId); event Claim(address vester, uint snapshotId, uint amount); constructor(address _votersInvestmentDispenser, address _sushiRouter, address _xruneToken, address _dao, address _grants, address _owner) { votersInvestmentDispenser = IVotersInvestmentDispenser(_votersInvestmentDispenser); sushiRouter = IUniswapV2Router(_sushiRouter); xruneToken = IERC20(_xruneToken); dao = IDAO(_dao); grants = _grants; owner = _owner; } modifier onlyOwner() { require(msg.sender == owner, "!owner"); _; } function addLpVester(address vester, uint snapshotId) public onlyOwner { lpVesters[lpVestersCount] = vester; lpVestersSnapshotIds[lpVestersCount] = snapshotId; lpVestersCount++; emit AddLpVester(vester, snapshotId); } function setVotersInvestmentDispenser(address value) public onlyOwner { votersInvestmentDispenser = IVotersInvestmentDispenser(value); } function setDao(address value) public onlyOwner { dao = IDAO(value); } function setGrants(address value) public onlyOwner { grants = value; } function setOwner(address value) public onlyOwner { owner = value; } function shouldRun() public view returns (bool) { return block.timestamp > lastRun + 82800; // 23 hours } function run() external { require(shouldRun(), "should not run"); lastRun = block.timestamp; for (uint i = 0; i < lpVestersCount; i++) { ILpTokenVesting vester = ILpTokenVesting(lpVesters[i]); uint claimable = vester.claimable(0); if (claimable > 0) { vester.claim(0); address token0 = address(vester.token0()); address token1 = address(vester.token1()); IERC20 lpToken = IERC20(pair(token0, token1)); uint lpTokenAmount = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(sushiRouter), lpTokenAmount); (uint amount0, uint amount1) = sushiRouter.removeLiquidity( token0, token1, lpTokenAmount, 0, 0, address(this), type(uint).max ); { address[] memory path = new address[](2); path[0] = address(xruneToken) == token0 ? token1 : token0; path[1] = address(xruneToken); uint amountToSwap = address(xruneToken) == token0 ? amount1 : amount0; IERC20(path[0]).safeApprove(address(sushiRouter), amountToSwap); sushiRouter.swapExactTokensForTokens( amountToSwap, 0, path, address(this), type(uint).max ); } uint amount = xruneToken.balanceOf(address(this)); xruneToken.safeApprove(address(votersInvestmentDispenser), (amount * 35) / 100); votersInvestmentDispenser.deposit(lpVestersSnapshotIds[i], (amount * 35) / 100); xruneToken.safeApprove(dao.voters(), (amount * 35) / 100); IVoters(dao.voters()).donate((amount * 35) / 100); xruneToken.safeTransfer(grants, (amount * 5) / 100); // Send the leftover 25% to the DAO xruneToken.transfer(address(dao), xruneToken.balanceOf(address(this))); emit Claim(lpVesters[i], lpVestersSnapshotIds[i], amount); } } } function pair(address token0, address token1) public view returns (address) { return IUniswapV2Factory(sushiRouter.factory()).getPair(token0, token1); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.6; interface IUniswapV2Router { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.6; interface IUniswapV2Factory { function getPair(address tokenA, address tokenB) external view returns (address pair); } //SPDX-License-Identifier: MIT pragma solidity 0.8.6; interface ILpTokenVesting { function token0() external view returns (address); function token1() external view returns (address); function claimable(uint party) external view returns (uint); function claim(uint party) external returns (uint); } //SPDX-License-Identifier: MIT pragma solidity 0.8.6; interface IVotersInvestmentDispenser { function deposit(uint snapshotId, uint amount) external; } //SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "./interfaces/IUniswapV2Pair.sol"; import "./interfaces/IUniswapV2Factory.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract TokenPriceHelper { address weth9; address dai; IUniswapV2Factory factory; constructor(address _weth9, address _dai, address _factory) { weth9 = _weth9; dai = _dai; factory = IUniswapV2Factory(_factory); } function price(address token) public view returns (uint) { uint ethPrice = 0; IUniswapV2Pair ethPair = IUniswapV2Pair(factory.getPair(weth9, dai)); (uint balance0, uint balance1,) = ethPair.getReserves(); if (ethPair.token0() == weth9) { ethPrice = (balance1 * 1e18) / balance0; } else { ethPrice = (balance0 * 1e18) / balance1; } IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(weth9, token)); if (address(pair) == address(0)) { return 0; } (balance0, balance1,) = pair.getReserves(); if (pair.token0() == weth9) { return balance0 * ethPrice / balance1; } else { return balance1 * ethPrice / balance0; } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.6; interface IUniswapV2Pair { function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); } //SPDX-License-Identifier: MIT pragma solidity 0.8.6; /* This contract allows the sale of an "offering" token in exchange for a "payment" token. It let's investors buy tokens at an initial price that increases with every deposit. The sale stops once the amount of offered tokens run out or after a specified block passes. The speed / curve along which the price increases is specified upfront. Investors can only participate once and will receive their tokens after the sale ends (more specifically, after tokensBlock). */ import '@openzeppelin/contracts/security/ReentrancyGuard.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import './interfaces/IVoters.sol'; contract SaleFloating is ReentrancyGuard { using SafeERC20 for IERC20; // Information of each user's participation struct UserInfo { // How many tokens the user has provided uint amount; // What price this user secured uint price; // Wether this user has already claimed their share of tokens, defaults to false bool claimedTokens; } // Owner address, has access to withdrawing funds after the sale address public owner; // Keeper address, has access to tweaking sake parameters address public keeper; // The raising token IERC20 public paymentToken; // The offering token IERC20 public offeringToken; // The block number when sale starts uint public startBlock; // The block number when sale ends uint public endBlock; // The block number when tokens are redeemable uint public tokensBlock; // Price to start the sale at (offeringToken per 1e18 of paymentToken) uint public startPrice; // Rate at which to increase the price (as amount per 1e18 of token invested) uint public priceVelocity; // Amount of tokens offered for sale uint public offeringAmount; // Maximum a user can contribute uint public perUserCap; // Voting token minimum balance to participate uint public votingMinimum; // Voting token address IVoters public votingToken; // Voting token snapshot id to use for balances (optional) uint public votingSnapshotId; // Wether deposits are paused bool public paused; // Total amount of raising tokens that have already been raised uint public totalAmount; // Total amount of offering tokens sold uint public totalOfferingAmount; // User's participation info mapping(address => UserInfo) public userInfo; // Participants list address[] public addressList; event Deposit(address indexed user, uint amount, uint price); event HarvestTokens(address indexed user, uint amount); constructor( IERC20 _paymentToken, IERC20 _offeringToken, uint _startBlock, uint _endBlock, uint _tokensBlock, uint _startPrice, uint _priceVelocity, uint _offeringAmount, uint _perUserCap, address _owner, address _keeper ) { paymentToken = _paymentToken; offeringToken = _offeringToken; startBlock = _startBlock; endBlock = _endBlock; tokensBlock = _tokensBlock; startPrice = _startPrice; priceVelocity = _priceVelocity; offeringAmount = _offeringAmount; perUserCap = _perUserCap; owner = _owner; keeper = _keeper; _validateBlockParams(); require(_paymentToken != _offeringToken, 'payment != offering'); require(_priceVelocity > 0, 'price velocity > 0'); require(_offeringAmount > 0, 'offering amount > 0'); } modifier onlyOwner() { require(msg.sender == owner, "!owner"); _; } modifier onlyOwnerOrKeeper() { require(msg.sender == owner || msg.sender == keeper, "!owner or keeper"); _; } function _validateBlockParams() private view { require(startBlock > block.number, 'start > now'); require(endBlock >= startBlock, 'end > start'); require(endBlock - startBlock <= 172800, 'end < 1 month after start'); require(tokensBlock - endBlock <= 172800, 'tokens < 1 month after end'); } function setOfferingAmount(uint _offerAmount) public onlyOwnerOrKeeper { require (block.number < startBlock, 'sale started'); offeringAmount = _offerAmount; } function setStartPrice(uint _startPrice) public onlyOwnerOrKeeper { require (block.number < startBlock, 'sale started'); startPrice = _startPrice; } function setPriceVelocity(uint _priceVelocity) public onlyOwnerOrKeeper { require (block.number < startBlock, 'sale started'); priceVelocity = _priceVelocity; } function setStartBlock(uint _block) public onlyOwnerOrKeeper { startBlock = _block; _validateBlockParams(); } function setEndBlock(uint _block) public onlyOwnerOrKeeper { endBlock = _block; _validateBlockParams(); } function setTokensBlock(uint _block) public onlyOwnerOrKeeper { tokensBlock = _block; _validateBlockParams(); } function configureVotingToken(uint minimum, address token, uint snapshotId) public onlyOwnerOrKeeper { votingMinimum = minimum; votingToken = IVoters(token); votingSnapshotId = snapshotId; } function togglePaused() public onlyOwnerOrKeeper { paused = !paused; } function deposit(uint _amount) public { require(!paused, 'paused'); require(block.number > startBlock && block.number < endBlock, 'sale not active'); require(_amount > 0, 'need amount > 0'); require(perUserCap == 0 || _amount <= perUserCap, 'over per user cap'); require(userInfo[msg.sender].amount == 0, 'already participated'); require(totalOfferingAmount <= offeringAmount, 'sold out'); if (votingMinimum > 0) { if (votingSnapshotId == 0) { require(votingToken.balanceOf(msg.sender) >= votingMinimum, "under minimum locked"); } else { require(votingToken.balanceOfAt(msg.sender, votingSnapshotId) >= votingMinimum, "under minimum locked"); } } paymentToken.safeTransferFrom(address(msg.sender), address(this), _amount); addressList.push(address(msg.sender)); userInfo[msg.sender].amount = _amount; totalAmount += _amount; uint price = startPrice + ((totalAmount * priceVelocity) / 1e18); userInfo[msg.sender].price = price; totalOfferingAmount += getOfferingAmount(msg.sender); emit Deposit(msg.sender, _amount, price); } function harvestTokens() public nonReentrant { require(!paused, 'paused'); require (block.number > tokensBlock, 'not harvest time'); require (userInfo[msg.sender].amount > 0, 'have you participated?'); require (!userInfo[msg.sender].claimedTokens, 'nothing to harvest'); uint amount = getOfferingAmount(msg.sender); if (amount > 0) { offeringToken.safeTransfer(address(msg.sender), amount); } userInfo[msg.sender].claimedTokens = true; emit HarvestTokens(msg.sender, amount); } function hasHarvestedTokens(address _user) external view returns (bool) { return userInfo[_user].claimedTokens; } // Amount of offering token a user will receive function getOfferingAmount(address _user) public view returns (uint) { return (userInfo[_user].amount * 1e18) / userInfo[_user].price; } function getAddressListLength() external view returns (uint) { return addressList.length; } function getParams() external view returns (uint, uint, uint, uint, uint, uint, uint, uint, uint) { return (startBlock, endBlock, tokensBlock, startPrice, priceVelocity, offeringAmount, perUserCap, totalAmount, totalOfferingAmount); } function finalWithdraw(uint _paymentAmount, uint _offeringAmount) public onlyOwner { require (_paymentAmount <= paymentToken.balanceOf(address(this)), 'not enough payment token'); require (_offeringAmount <= offeringToken.balanceOf(address(this)), 'not enough offerring token'); if (_paymentAmount > 0) { paymentToken.safeTransfer(address(msg.sender), _paymentAmount); } if (_offeringAmount > 0) { offeringToken.safeTransfer(address(msg.sender), _offeringAmount); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } //SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./interfaces/IVoters.sol"; import "./interfaces/IERC677Receiver.sol"; contract SaleDutch is ReentrancyGuard, IERC677Receiver { using SafeERC20 for IERC20; // Information of each user's participation struct UserInfo { // How many tokens the user has provided uint amount; // Wether this user has already claimed their share of tokens, defaults to false bool claimedTokens; } // Owner address, has access to withdrawing funds after the sale address public owner; // The raising token IERC20 public paymentToken; // The offering token IERC20 public offeringToken; // The time (unix seconds) when sale starts uint public startTime; // The time (unix security) when sale ends uint public endTime; // Price to start the sale at (offeringToken per 1e18 of paymentToken) uint public startPrice; // Reserve price (as amount per 1e18 of token invested) uint public endPrice; // Amount of tokens offered for sale uint public offeringAmount; // Maximum a user can contribute uint public perUserCap; // Voting token minimum balance to participate uint public votingMinimum; // Voting token address IVoters public votingToken; // Voting token snapshot id to use for balances (optional) uint public votingSnapshotId; // Wether deposits are paused bool public paused; // Wether the sale is finalized bool public finalized; // Total amount of raising tokens that have already been raised uint public totalAmount; // User's participation info mapping(address => UserInfo) public userInfo; // Participants list address[] public addressList; event Deposit(address indexed user, uint amount); event HarvestTokens(address indexed user, uint amount); event HarvestRefund(address indexed user, uint amount); constructor( address _paymentToken, address _offeringToken, uint _startTime, uint _endTime, uint _startPrice, uint _endPrice, uint _offeringAmount, uint _perUserCap, address _owner ) { paymentToken = IERC20(_paymentToken); offeringToken = IERC20(_offeringToken); startTime = _startTime; endTime = _endTime; startPrice = _startPrice; endPrice = _endPrice; offeringAmount = _offeringAmount; perUserCap = _perUserCap; owner = _owner; require(_paymentToken != _offeringToken, 'payment != offering'); require(startTime > block.timestamp, 'start > now'); require(startTime < endTime, 'start < end'); require(startTime < 10000000000, 'start time not unix'); require(endTime < 10000000000, 'start time not unix'); require(_startPrice > 0, 'start price > 0'); require(_offeringAmount > 0, 'offering amount > 0'); } modifier onlyOwner() { require(msg.sender == owner, "!owner"); _; } function togglePaused() public onlyOwner { paused = !paused; } function finalize() public { require(msg.sender == owner || block.timestamp > endTime + 7 days, 'no allowed'); finalized = true; } function getAddressListLength() external view returns (uint) { return addressList.length; } function getParams() external view returns (uint, uint, uint, uint, uint, uint, uint, uint, uint, bool, bool) { return (startTime, endTime, startPrice, endPrice, offeringAmount, perUserCap, totalAmount, currentPrice(), clearingPrice(), paused, finalized); } function priceChange() public view returns (uint) { return (startPrice - endPrice) / (endTime - startTime); } function currentPrice() public view returns (uint) { if (block.timestamp <= startTime) return startPrice; if (block.timestamp >= endTime) return endPrice; return startPrice - ((block.timestamp - startTime) * priceChange()); } function tokenPrice() public view returns (uint) { return (totalAmount * 1e18) / offeringAmount; } function clearingPrice() public view returns (uint) { if (tokenPrice() > currentPrice()) return tokenPrice(); return currentPrice(); } function saleSuccessful() public view returns (bool) { return tokenPrice() >= clearingPrice(); } function commitmentSize(uint amount) public view returns (uint) { uint max = (offeringAmount * clearingPrice()) / 1e18; if (totalAmount + amount > max) { return max - totalAmount; } return amount; } function _deposit(address user, uint amount) private nonReentrant { require(!paused, 'paused'); require(block.timestamp > startTime && block.timestamp < endTime, 'sale not active'); require(amount > 0, 'need amount > 0'); require(perUserCap == 0 || amount <= perUserCap, 'over per user cap'); require(userInfo[user].amount == 0, 'already participated'); if (votingMinimum > 0) { if (votingSnapshotId == 0) { require(votingToken.balanceOf(user) >= votingMinimum, "under minimum locked"); } else { require(votingToken.balanceOfAt(user, votingSnapshotId) >= votingMinimum, "under minimum locked"); } } uint cappedAmount = commitmentSize(amount); require(cappedAmount > 0, 'sale fully commited'); // Refund user's overpayment if (amount - cappedAmount > 0) { paymentToken.transfer(user, amount - cappedAmount); } addressList.push(user); userInfo[user].amount = cappedAmount; totalAmount += cappedAmount; emit Deposit(user, cappedAmount); } function deposit(uint amount) external { _transferFrom(msg.sender, amount); _deposit(msg.sender, amount); } function onTokenTransfer(address user, uint amount, bytes calldata _data) external override { require(msg.sender == address(paymentToken), "onTokenTransfer: not paymentToken"); _deposit(user, amount); } function harvestTokens() public nonReentrant { require(!paused, 'paused'); if (saleSuccessful()) { require(finalized, 'not finalized'); require(userInfo[msg.sender].amount > 0, 'have you participated?'); require(!userInfo[msg.sender].claimedTokens, 'already claimed'); uint amount = getOfferingAmount(msg.sender); require(amount > 0, 'nothing to claim'); offeringToken.safeTransfer(msg.sender, amount); userInfo[msg.sender].claimedTokens = true; emit HarvestTokens(msg.sender, amount); } else { require(block.timestamp > endTime, 'sale not ended'); uint amount = userInfo[msg.sender].amount; userInfo[msg.sender].amount = 0; paymentToken.safeTransfer(msg.sender, amount); emit HarvestRefund(msg.sender, amount); } } // Amount of offering token a user will receive function getOfferingAmount(address _user) public view returns (uint) { return (userInfo[_user].amount * offeringAmount) / totalAmount; } function hasHarvestedTokens(address _user) external view returns (bool) { return userInfo[_user].claimedTokens; } function withdrawToken(address token, uint amount) public onlyOwner { IERC20(token).safeTransfer(msg.sender, amount); } function _transferFrom(address from, uint amount) private { uint balanceBefore = paymentToken.balanceOf(address(this)); paymentToken.safeTransferFrom(from, address(this), amount); uint balanceAfter = paymentToken.balanceOf(address(this)); require(balanceAfter - balanceBefore == amount, "_transferFrom: balance change does not match amount"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IERC677Receiver { function onTokenTransfer(address _sender, uint _value, bytes calldata _data) external; } //SPDX-License-Identifier: MIT pragma solidity 0.8.6; /* This contract allows XRUNE holders and LPs to lock some of their tokens up for vXRUNE, the Thorstarter DAO's voting token. It's an ERC20 but without the transfer methods. It supports snapshoting and delegation of voting power. */ import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "./interfaces/IVoters.sol"; import "./interfaces/IUniswapV2Pair.sol"; import "./interfaces/IERC677Receiver.sol"; contract Voters is IVoters, IERC677Receiver, AccessControl { using SafeERC20 for IERC20; struct UserInfo { uint lastFeeGrowth; uint lockedToken; uint lockedSsLpValue; uint lockedSsLpAmount; uint lockedTcLpValue; uint lockedTcLpAmount; address delegate; } struct Snapshots { uint[] ids; uint[] values; } event Transfer(address indexed from, address indexed to, uint value); event Snapshot(uint id); event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); string public constant name = "Thorstarter Voting Token"; string public constant symbol = "vXRUNE"; uint8 public constant decimals = 18; bytes32 public constant ADMIN_ROLE = keccak256("ADMIN"); bytes32 public constant KEEPER_ROLE = keccak256("KEEPER"); bytes32 public constant SNAPSHOTTER_ROLE = keccak256("SNAPSHOTTER"); IERC20 public token; IERC20 public sushiLpToken; uint public lastFeeGrowth; uint public totalSupply; mapping(address => UserInfo) private _userInfos; uint public currentSnapshotId; Snapshots private _totalSupplySnapshots; mapping(address => Snapshots) private _balancesSnapshots; mapping(address => uint) private _votes; mapping(address => Snapshots) private _votesSnapshots; mapping(address => bool) public historicalTcLps; address[] private _historicalTcLpsList; mapping(address => uint) public lastLockBlock; constructor(address _owner, address _token, address _sushiLpToken) { _setRoleAdmin(KEEPER_ROLE, ADMIN_ROLE); _setRoleAdmin(SNAPSHOTTER_ROLE, ADMIN_ROLE); _setupRole(ADMIN_ROLE, _owner); _setupRole(KEEPER_ROLE, _owner); _setupRole(SNAPSHOTTER_ROLE, _owner); token = IERC20(_token); sushiLpToken = IERC20(_sushiLpToken); currentSnapshotId = 1; } function userInfo(address user) external view returns (uint, uint, uint, uint, uint, uint, address) { UserInfo storage userInfo = _userInfos[user]; return ( userInfo.lastFeeGrowth, userInfo.lockedToken, userInfo.lockedSsLpValue, userInfo.lockedSsLpAmount, userInfo.lockedTcLpValue, userInfo.lockedTcLpAmount, userInfo.delegate ); } function balanceOf(address user) override public view returns (uint) { UserInfo storage userInfo = _userInfos[user]; return _userInfoTotal(userInfo); } function balanceOfAt(address user, uint snapshotId) override external view returns (uint) { (bool snapshotted, uint value) = _valueAt(_balancesSnapshots[user], snapshotId); return snapshotted ? value : balanceOf(user); } function votes(address user) public view returns (uint) { return _votes[user]; } function votesAt(address user, uint snapshotId) override external view returns (uint) { (bool snapshotted, uint value) = _valueAt(_votesSnapshots[user], snapshotId); return snapshotted ? value : votes(user); } function totalSupplyAt(uint snapshotId) override external view returns (uint) { (bool snapshotted, uint value) = _valueAt(_totalSupplySnapshots, snapshotId); return snapshotted ? value : totalSupply; } function approve(address spender, uint amount) external returns (bool) { revert("not implemented"); } function transfer(address to, uint amount) external returns (bool) { revert("not implemented"); } function transferFrom(address from, address to, uint amount) external returns (bool) { revert("not implemented"); } function snapshot() override external onlyRole(SNAPSHOTTER_ROLE) returns (uint) { currentSnapshotId += 1; emit Snapshot(currentSnapshotId); return currentSnapshotId; } function _valueAt(Snapshots storage snapshots, uint snapshotId) private view returns (bool, uint) { if (snapshots.ids.length == 0) { return (false, 0); } uint lower = 0; uint upper = snapshots.ids.length; while (lower < upper) { uint mid = (lower & upper) + (lower ^ upper) / 2; if (snapshots.ids[mid] > snapshotId) { upper = mid; } else { lower = mid + 1; } } uint index = lower; if (lower > 0 && snapshots.ids[lower - 1] == snapshotId) { index = lower -1; } if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateSnapshot(Snapshots storage snapshots, uint value) private { uint currentId = currentSnapshotId; uint lastSnapshotId = 0; if (snapshots.ids.length > 0) { lastSnapshotId = snapshots.ids[snapshots.ids.length - 1]; } if (lastSnapshotId < currentId) { snapshots.ids.push(currentId); snapshots.values.push(value); } } function delegate(address delegatee) external { require(delegatee != address(0), "zero address provided"); UserInfo storage userInfo = _userInfos[msg.sender]; address currentDelegate = userInfo.delegate; userInfo.delegate = delegatee; _updateSnapshot(_votesSnapshots[currentDelegate], votes(currentDelegate)); _updateSnapshot(_votesSnapshots[delegatee], votes(delegatee)); uint amount = balanceOf(msg.sender); _votes[currentDelegate] -= amount; _votes[delegatee] += amount; emit DelegateChanged(msg.sender, currentDelegate, delegatee); } function _lock(address user, uint amount) private { require(amount > 0, "!zero"); UserInfo storage userInfo = _userInfo(user); // track last time a user called the lock method to prevent flash loan attacks lastLockBlock[user] = block.number; _updateSnapshot(_totalSupplySnapshots, totalSupply); _updateSnapshot(_balancesSnapshots[user], balanceOf(user)); _updateSnapshot(_votesSnapshots[userInfo.delegate], votes(userInfo.delegate)); totalSupply += amount; userInfo.lockedToken += amount; _votes[userInfo.delegate] += amount; emit Transfer(address(0), user, amount); } function lock(uint amount) external { _transferFrom(token, msg.sender, amount); _lock(msg.sender, amount); } function onTokenTransfer(address user, uint amount, bytes calldata _data) external override { require(msg.sender == address(token), "onTokenTransfer: not xrune"); _lock(user, amount); } function unlock(uint amount) external { require(block.number > lastLockBlock[msg.sender], "no lock-unlock in same tx"); UserInfo storage userInfo = _userInfo(msg.sender); require(amount <= userInfo.lockedToken, "locked balance too low"); _updateSnapshot(_totalSupplySnapshots, totalSupply); _updateSnapshot(_balancesSnapshots[msg.sender], balanceOf(msg.sender)); _updateSnapshot(_votesSnapshots[userInfo.delegate], votes(userInfo.delegate)); totalSupply -= amount; userInfo.lockedToken -= amount; _votes[userInfo.delegate] -= amount; emit Transfer(msg.sender, address(0), amount); if (amount > 0) { token.safeTransfer(msg.sender, amount); } } function lockSslp(uint lpAmount) external { UserInfo storage userInfo = _userInfo(msg.sender); require(lpAmount > 0, "!zero"); _transferFrom(sushiLpToken, msg.sender, lpAmount); _updateSnapshot(_totalSupplySnapshots, totalSupply); _updateSnapshot(_balancesSnapshots[msg.sender], balanceOf(msg.sender)); _updateSnapshot(_votesSnapshots[userInfo.delegate], votes(userInfo.delegate)); // Subtract current LP value uint previousValue = userInfo.lockedSsLpValue; totalSupply -= userInfo.lockedSsLpValue; _votes[userInfo.delegate] -= userInfo.lockedSsLpValue; // Increment LP amount userInfo.lockedSsLpAmount += lpAmount; // Calculated updated *full* LP amount value and set (not increment) // We do it like this and not based on just amount added so that unlock // knows that the lockedSsLpValue is based on one rate and not multiple adds uint lpTokenSupply = sushiLpToken.totalSupply(); uint lpTokenReserve = token.balanceOf(address(sushiLpToken)); require(lpTokenSupply > 0, "lp token supply can not be zero"); uint amount = (2 * userInfo.lockedSsLpAmount * lpTokenReserve) / lpTokenSupply; totalSupply += amount; // Increment as we decremented _votes[userInfo.delegate] += amount; // Increment as we decremented userInfo.lockedSsLpValue = amount; // Set a we didn't ajust and amount is full value if (previousValue < userInfo.lockedSsLpValue) { emit Transfer(address(0), msg.sender, userInfo.lockedSsLpValue - previousValue); } else if (previousValue > userInfo.lockedSsLpValue) { emit Transfer(msg.sender, address(0), previousValue - userInfo.lockedSsLpValue); } } function unlockSslp(uint lpAmount) external { UserInfo storage userInfo = _userInfo(msg.sender); require(lpAmount > 0, "amount can't be 0"); require(lpAmount <= userInfo.lockedSsLpAmount, "locked balance too low"); _updateSnapshot(_totalSupplySnapshots, totalSupply); _updateSnapshot(_balancesSnapshots[msg.sender], balanceOf(msg.sender)); _updateSnapshot(_votesSnapshots[userInfo.delegate], votes(userInfo.delegate)); // Proportionally decrement lockedSsLpValue & supply & delegated votes uint amount = lpAmount * userInfo.lockedSsLpValue / userInfo.lockedSsLpAmount; totalSupply -= amount; userInfo.lockedSsLpValue -= amount; userInfo.lockedSsLpAmount -= lpAmount; _votes[userInfo.delegate] -= amount; emit Transfer(msg.sender, address(0), amount); sushiLpToken.safeTransfer(msg.sender, lpAmount); } function updateTclp(address[] calldata users, uint[] calldata amounts, uint[] calldata values) external onlyRole(KEEPER_ROLE) { require(users.length == amounts.length && users.length == values.length, "length"); for (uint i = 0; i < users.length; i++) { address user = users[i]; UserInfo storage userInfo = _userInfo(user); _updateSnapshot(_totalSupplySnapshots, totalSupply); _updateSnapshot(_balancesSnapshots[user], balanceOf(user)); _updateSnapshot(_votesSnapshots[userInfo.delegate], votes(userInfo.delegate)); uint previousValue = userInfo.lockedTcLpValue; totalSupply = totalSupply - previousValue + values[i]; _votes[userInfo.delegate] = _votes[userInfo.delegate] - previousValue + values[i]; userInfo.lockedTcLpValue = values[i]; userInfo.lockedTcLpAmount = amounts[i]; if (previousValue < values[i]) { emit Transfer(address(0), user, values[i] - previousValue); } else if (previousValue > values[i]) { emit Transfer(user, address(0), previousValue - values[i]); } // Add to historicalTcLpsList for keepers to use if (!historicalTcLps[user]) { historicalTcLps[user] = true; _historicalTcLpsList.push(user); } } } function historicalTcLpsList(uint page, uint pageSize) external view returns (address[] memory) { address[] memory list = new address[](pageSize); for (uint i = page * pageSize; i < (page + 1) * pageSize && i < _historicalTcLpsList.length; i++) { list[i-(page*pageSize)] = _historicalTcLpsList[i]; } return list; } function donate(uint amount) override external { _transferFrom(token, msg.sender, amount); lastFeeGrowth += (amount * 1e12) / totalSupply; } function _userInfo(address user) private returns (UserInfo storage) { require(user != address(0), "zero address provided"); UserInfo storage userInfo = _userInfos[user]; if (userInfo.delegate == address(0)) { userInfo.delegate = user; } if (userInfo.lastFeeGrowth == 0 && lastFeeGrowth != 0) { userInfo.lastFeeGrowth = lastFeeGrowth; } else { uint fees = (_userInfoTotal(userInfo) * (lastFeeGrowth - userInfo.lastFeeGrowth)) / 1e12; if (fees > 0) { _updateSnapshot(_totalSupplySnapshots, totalSupply); _updateSnapshot(_balancesSnapshots[user], balanceOf(user)); _updateSnapshot(_votesSnapshots[userInfo.delegate], votes(userInfo.delegate)); totalSupply += fees; userInfo.lockedToken += fees; userInfo.lastFeeGrowth = lastFeeGrowth; _votes[userInfo.delegate] += fees; emit Transfer(address(0), user, fees); } } return userInfo; } function _userInfoTotal(UserInfo storage userInfo) private view returns (uint) { return userInfo.lockedToken + userInfo.lockedSsLpValue + userInfo.lockedTcLpValue; } function _transferFrom(IERC20 token, address from, uint amount) private { uint balanceBefore = token.balanceOf(address(this)); token.safeTransferFrom(from, address(this), amount); uint balanceAfter = token.balanceOf(address(this)); require(balanceAfter - balanceBefore == amount, "_transferFrom: balance change does not match amount"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // 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 pragma solidity 0.8.6; /* This contract receives XRUNE from the Thorstarter grants multisig and some project tokens, then, when ready, an owner calls the `lock` method and both tokens are paired in an AMM and the LP tokens are locked in this contract. Over time, each party can claim their vested tokens. Each party is owed an equal share of the initial amount of LP tokens. If a pool already exist, we attempt to swap some amount of tokens to bring the price in line with the target price. */ import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import './interfaces/IUniswapV2Pair.sol'; import './interfaces/IUniswapV2Router.sol'; import './interfaces/IUniswapV2Factory.sol'; contract LpTokenVesting { using SafeERC20 for IERC20; struct Party { uint claimedAmount; mapping(address => bool) owners; } IERC20 public token0; IERC20 public token1; IUniswapV2Router public sushiRouter; uint public vestingCliff; uint public vestingLength; uint public partyCount; mapping(uint => Party) public parties; mapping(address => bool) public owners; uint public initialLpShareAmount; uint public vestingStart; event Claimed(uint party, uint amount); event Locked(uint time, uint amount, uint balance0, uint balance1); constructor(address _token0, address _token1, address _sushiRouter, uint _vestingCliff, uint _vestingLength, address[] memory _owners) { (_token0, _token1) = _token0 < _token1 ? (_token0, _token1) : (_token1, _token0); token0 = IERC20(_token0); token1 = IERC20(_token1); sushiRouter = IUniswapV2Router(_sushiRouter); vestingCliff = _vestingCliff; vestingLength = _vestingLength; partyCount = _owners.length; for (uint i = 0; i < _owners.length; i++) { Party storage p = parties[i]; p.owners[_owners[i]] = true; owners[_owners[i]] = true; } } modifier onlyOwner { require(owners[msg.sender], "not an owner"); _; } function toggleOwner(uint party, address owner) public { Party storage p = parties[party]; require(p.owners[msg.sender], "not an owner of this party"); p.owners[owner] = !p.owners[owner]; owners[owner] = p.owners[owner]; } function partyClaimedAmount(uint party) public view returns (uint) { return parties[party].claimedAmount; } function partyOwner(uint party, address owner) public view returns (bool) { return parties[party].owners[owner]; } function pair() public view returns (address) { return IUniswapV2Factory(sushiRouter.factory()).getPair(address(token0), address(token1)); } function claimable(uint party) public view returns (uint) { if (vestingStart == 0 || party >= partyCount) { return 0; } Party storage p = parties[party]; uint percentVested = (block.timestamp - _min(block.timestamp, vestingStart + vestingCliff)) * 1e6 / vestingLength; if (percentVested > 1e6) { percentVested = 1e6; } return ((initialLpShareAmount * percentVested) / 1e6 / partyCount) - p.claimedAmount; } function claim(uint party) public returns (uint) { Party storage p = parties[party]; require(p.owners[msg.sender], "not an owner of this party"); uint amount = claimable(party); if (amount > 0) { p.claimedAmount += amount; IERC20(pair()).safeTransfer(msg.sender, amount); emit Claimed(party, amount); } return amount; } function lock() public onlyOwner { require(vestingStart == 0, "vesting already started"); uint token0Balance = token0.balanceOf(address(this)); uint token1Balance = token1.balanceOf(address(this)); address pairAddress = pair(); // If there's already a pair, we'll need to do a swap in order get the price in the right place if (pairAddress != address(0)) { IUniswapV2Pair pool = IUniswapV2Pair(pairAddress); uint targetPrice = (token0Balance * 1e6) / token1Balance; (uint112 reserve0, uint112 reserve1,) = pool.getReserves(); uint currentPrice = (reserve0 * 1e6) / reserve1; uint difference = (currentPrice * 1e6) / targetPrice; if (difference < 995000) { // Current price is smaller than target (>0.5%), swap token1 for token0 // We divide the amount of reserve1 to send that would balance the price // in two because an ammout of reserve0 is going to come out address[] memory path = new address[](2); path[0] = address(token0); path[1] = address(token1); // Multiply amount by 0.6 because swapping 100% of the difference would remove the // the equivalent amount from the opposite reserves (we're aiming for half that impact) uint amount = (reserve0 * (1e6 - difference) * 60) / 1e6 / 100; token0.safeApprove(address(sushiRouter), amount); sushiRouter.swapExactTokensForTokens(amount, 0, path, address(this), type(uint).max); } if (difference > 10050000) { // Current price is greater than target (>0.5%), swap token0 for token1 address[] memory path = new address[](2); path[0] = address(token1); path[1] = address(token0); uint amount = (reserve1 * (difference - 1e6)) / 1e6 / 2; token1.safeApprove(address(sushiRouter), amount); sushiRouter.swapExactTokensForTokens(amount, 0, path, address(this), type(uint).max); } (reserve0, reserve1,) = pool.getReserves(); } // Update balances in case we did a swap to adjust price token0Balance = token0.balanceOf(address(this)); token1Balance = token1.balanceOf(address(this)); token0.safeApprove(address(sushiRouter), token0Balance); token1.safeApprove(address(sushiRouter), token1Balance); sushiRouter.addLiquidity( address(token0), address(token1), token0Balance, token1Balance, (token0Balance * 9850) / 10000, (token1Balance * 9850) / 10000, address(this), type(uint).max ); pairAddress = pair(); initialLpShareAmount = IERC20(pairAddress).balanceOf(address(this)); vestingStart = block.timestamp; emit Locked(vestingStart, initialLpShareAmount, token0Balance, token1Balance); } function withdraw(address token, uint amount) public onlyOwner { require(token == address(token0) || token == address(token1), "can only withdraw token{0,1}"); IERC20(token).safeTransfer(msg.sender, amount); } function _min(uint a, uint b) private pure returns (uint) { return a < b ? a : b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ 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 owner) { _owner = owner; emit OwnershipTransferred(address(0), owner); } /** * @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.6; import "./ERC677.sol"; import "./ERC777Permit.sol"; import "./Ownable.sol"; import "@openzeppelin/contracts/token/ERC777/ERC777.sol"; contract XRUNE is ERC777, ERC777Permit, ERC677, Ownable { uint256 public constant ERA_SECONDS = 86400; uint256 public constant MAX_SUPPLY = 1000000000 ether; uint256 public nextEra = 1622433600; // 2021-05-31 uint256 public curve = 1024; bool public emitting = false; address public reserve = address(0); event NewEra(uint256 time, uint256 emission); constructor(address owner) public ERC777("XRUNE Token", "XRUNE", new address[](0)) ERC777Permit("XRUNE") Ownable(owner) { _mint(owner, MAX_SUPPLY / 2, "", ""); } function setCurve(uint256 _curve) public onlyOwner { require( _curve > 0 && _curve < 10000, "curve needs to be between 0 and 10000" ); curve = _curve; } function toggleEmitting() public onlyOwner { emitting = !emitting; } function setReserve(address _reserve) public onlyOwner { reserve = _reserve; } function setNextEra(uint256 next) public onlyOwner { // solhint-disable-next-line not-rely-on-time require( next > nextEra && next > block.timestamp, "next era needs to be in the future" ); nextEra = next; } function _beforeTokenTransfer( address operator, address from, address to, uint256 amount ) internal virtual override { super._beforeTokenTransfer(operator, from, to, amount); require(to != address(this), "!self"); dailyEmit(); } function dailyEmit() public { // solhint-disable-next-line not-rely-on-time if ((block.timestamp >= nextEra) && emitting && reserve != address(0)) { uint256 _emission = dailyEmission(); emit NewEra(nextEra, _emission); nextEra = nextEra + ERA_SECONDS; _mint(reserve, _emission, "", ""); } } function dailyEmission() public view returns (uint256) { return (MAX_SUPPLY - totalSupply()) / curve; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/IERC677.sol"; import "./interfaces/IERC677Receiver.sol"; import "@openzeppelin/contracts/token/ERC777/ERC777.sol"; abstract contract ERC677 is ERC777, IERC677 { /** * @dev transfer token to a contract address with additional data if the recipient is a contact. * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _data The extra data to be passed to the receiving contract. */ function transferAndCall(address _to, uint _value, bytes calldata _data) public override returns (bool success) { super.transfer(_to, _value); emit TransferWithData(msg.sender, _to, _value, _data); if (isContract(_to)) { contractFallback(_to, _value, _data); } return true; } function contractFallback(address _to, uint _value, bytes calldata _data) private { IERC677Receiver receiver = IERC677Receiver(_to); receiver.onTokenTransfer(msg.sender, _value, _data); } function isContract(address _addr) private view returns (bool hasCode) { uint length; assembly { length := extcodesize(_addr) } return length > 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/draft-ERC20Permit.sol import "./interfaces/IERC20Permit.sol"; import "@openzeppelin/contracts/token/ERC777/ERC777.sol"; import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC777Permit is ERC777, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping (address => Counters.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") { } /** * @dev See {IERC20Permit-permit}. */ function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256( abi.encode( _PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline ) ); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC777.sol"; import "./IERC777Recipient.sol"; import "./IERC777Sender.sol"; import "../ERC20/IERC20.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/IERC1820Registry.sol"; /** * @dev Implementation of the {IERC777} 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}. * * Support for ERC20 is included in this contract, as specified by the EIP: both * the ERC777 and ERC20 interfaces can be safely used when interacting with it. * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token * movements. * * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there * are no special restrictions in the amount of tokens that created, moved, or * destroyed. This makes integration with ERC20 applications seamless. */ contract ERC777 is Context, IERC777, IERC20 { using Address for address; IERC1820Registry internal constant _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); mapping(address => uint256) private _balances; uint256 private _totalSupply; string private _name; string private _symbol; bytes32 private constant _TOKENS_SENDER_INTERFACE_HASH = keccak256("ERC777TokensSender"); bytes32 private constant _TOKENS_RECIPIENT_INTERFACE_HASH = keccak256("ERC777TokensRecipient"); // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] private _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) private _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) private _operators; mapping(address => mapping(address => bool)) private _revokedDefaultOperators; // ERC20-allowances mapping(address => mapping(address => uint256)) private _allowances; /** * @dev `defaultOperators` may be an empty array. */ constructor( string memory name_, string memory symbol_, address[] memory defaultOperators_ ) { _name = name_; _symbol = symbol_; _defaultOperatorsArray = defaultOperators_; for (uint256 i = 0; i < defaultOperators_.length; i++) { _defaultOperators[defaultOperators_[i]] = true; } // register interfaces _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this)); _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this)); } /** * @dev See {IERC777-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {ERC20-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public pure virtual returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view virtual override returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view virtual override(IERC20, IERC777) returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by an account (`tokenHolder`). */ function balanceOf(address tokenHolder) public view virtual override(IERC20, IERC777) returns (uint256) { return _balances[tokenHolder]; } /** * @dev See {IERC777-send}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function send( address recipient, uint256 amount, bytes memory data ) public virtual override { _send(_msgSender(), recipient, amount, data, "", true); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); address from = _msgSender(); _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev See {IERC777-burn}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function burn(uint256 amount, bytes memory data) public virtual override { _burn(_msgSender(), amount, data, ""); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor(address operator, address tokenHolder) public view virtual override returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) public virtual override { require(_msgSender() != operator, "ERC777: authorizing self as operator"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[_msgSender()][operator]; } else { _operators[_msgSender()][operator] = true; } emit AuthorizedOperator(operator, _msgSender()); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) public virtual override { require(operator != _msgSender(), "ERC777: revoking self as operator"); if (_defaultOperators[operator]) { _revokedDefaultOperators[_msgSender()][operator] = true; } else { delete _operators[_msgSender()][operator]; } emit RevokedOperator(operator, _msgSender()); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view virtual override returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {IERC20-Transfer} events. */ function operatorSend( address sender, address recipient, uint256 amount, bytes memory data, bytes memory operatorData ) public virtual override { require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder"); _send(sender, recipient, amount, data, operatorData, true); } /** * @dev See {IERC777-operatorBurn}. * * Emits {Burned} and {IERC20-Transfer} events. */ function operatorBurn( address account, uint256 amount, bytes memory data, bytes memory operatorData ) public virtual override { require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder"); _burn(account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view virtual override returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) public virtual override returns (bool) { address holder = _msgSender(); _approve(holder, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events. */ function transferFrom( address holder, address recipient, uint256 amount ) public virtual override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); require(holder != address(0), "ERC777: transfer from the zero address"); address spender = _msgSender(); _callTokensToSend(spender, holder, recipient, amount, "", ""); _move(spender, holder, recipient, amount, "", ""); uint256 currentAllowance = _allowances[holder][spender]; require(currentAllowance >= amount, "ERC777: transfer amount exceeds allowance"); _approve(holder, spender, currentAllowance - amount); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * If a send hook is registered for `account`, the corresponding function * will be called with `operator`, `data` and `operatorData`. * * See {IERC777Sender} and {IERC777Recipient}. * * Emits {Minted} and {IERC20-Transfer} events. * * Requirements * * - `account` cannot be the zero address. * - if `account` is a contract, it must implement the {IERC777Recipient} * interface. */ function _mint( address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal virtual { _mint(account, amount, userData, operatorData, true); } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * If `requireReceptionAck` is set to true, and if a send hook is * registered for `account`, the corresponding function will be called with * `operator`, `data` and `operatorData`. * * See {IERC777Sender} and {IERC777Recipient}. * * Emits {Minted} and {IERC20-Transfer} events. * * Requirements * * - `account` cannot be the zero address. * - if `account` is a contract, it must implement the {IERC777Recipient} * interface. */ function _mint( address account, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal virtual { require(account != address(0), "ERC777: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, amount); // Update state variables _totalSupply += amount; _balances[account] += amount; _callTokensReceived(operator, address(0), account, amount, userData, operatorData, requireReceptionAck); emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } /** * @dev Send tokens * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _send( address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal virtual { require(from != address(0), "ERC777: send from the zero address"); require(to != address(0), "ERC777: send to the zero address"); address operator = _msgSender(); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } /** * @dev Burn tokens * @param from address token holder address * @param amount uint256 amount of tokens to burn * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _burn( address from, uint256 amount, bytes memory data, bytes memory operatorData ) internal virtual { require(from != address(0), "ERC777: burn from the zero address"); address operator = _msgSender(); _callTokensToSend(operator, from, address(0), amount, data, operatorData); _beforeTokenTransfer(operator, from, address(0), amount); // Update state variables uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC777: burn amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _totalSupply -= amount; emit Burned(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { _beforeTokenTransfer(operator, from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC777: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } /** * @dev See {ERC20-_approve}. * * Note that accounts cannot have allowance issued by their operators. */ function _approve( address holder, address spender, uint256 value ) internal { require(holder != address(0), "ERC777: approve from the zero address"); require(spender != address(0), "ERC777: approve to the zero address"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) private { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient"); } } /** * @dev Hook that is called before any token transfer. This includes * calls to {send}, {transfer}, {operatorSend}, 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 operator, address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IERC677 { function transferAndCall(address to, uint value, bytes calldata data) external returns (bool success); event TransferWithData(address indexed from, address indexed to, uint value, bytes data); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send( address recipient, uint256 amount, bytes calldata data ) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Revoke an account's operator status for the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of {IERC777} tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC777TokensSender standard as defined in the EIP. * * {IERC777} Token holders can be notified of operations performed on their * tokens by having a contract implement this interface (contract holders can be * their own implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Sender { /** * @dev Called by an {IERC777} token contract whenever a registered holder's * (`from`) tokens are about to be moved or destroyed. The type of operation * is conveyed by `to` being the zero address or not. * * This call occurs _before_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the pre-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensToSend( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as ``account``'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer( address account, bytes32 _interfaceHash, address implementer ) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 _interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/draft-IERC20Permit.sol /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ECDSA.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, 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 ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return recover(hash, r, vs); } else { revert("ECDSA: invalid signature length"); } } /** * @dev Overload of {ECDSA-recover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require( uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value" ); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT 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; } } pragma solidity 0.8.6; import "@openzeppelin/contracts/token/ERC777/ERC777.sol"; import "../ERC677.sol"; contract MockToken is ERC677 { constructor() ERC777("MockToken", "MTOK", new address[](0)) { _mint(msg.sender, 500000000e18, "", ""); } } // 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.6; /* This contract receives XRUNE from the `EmissionsSplitter` contract and allows private investors to claim their share of vested tokens. If they need to update their address the owner can do so for them. */ import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; contract EmissionsPrivateDispenser is Ownable { using SafeERC20 for IERC20; IERC20 public token; uint public totalReceived; mapping(address => uint) public investorsPercentages; // 1e12 = 100% mapping(address => uint) public investorsClaimedAmount; event ConfigureInvestor(address investor, uint percentage); event Claim(address user, uint amount); event Deposit(uint amount); constructor(address _token, address[] memory investors, uint[] memory percentages) { token = IERC20(_token); require(investors.length == percentages.length); for (uint i = 0; i < investors.length; i++) { investorsPercentages[investors[i]] = percentages[i]; emit ConfigureInvestor(investors[i], percentages[i]); } } function updateInvestorAddress(address oldAddress, address newAddress) public onlyOwner { require(investorsPercentages[oldAddress] > 0, "not an investor"); investorsPercentages[newAddress] = investorsPercentages[oldAddress]; investorsPercentages[oldAddress] = 0; investorsClaimedAmount[newAddress] = investorsClaimedAmount[oldAddress]; investorsClaimedAmount[oldAddress] = 0; emit ConfigureInvestor(newAddress, investorsPercentages[newAddress]); } function claimable(address user) public view returns (uint) { return ((totalReceived * investorsPercentages[user]) / 1e12) - investorsClaimedAmount[user]; } function claim() public { uint amount = claimable(msg.sender); require(amount > 0, "nothing to claim"); investorsClaimedAmount[msg.sender] += amount; token.safeTransfer(msg.sender, amount); emit Claim(msg.sender, amount); } function deposit(uint amount) public { token.safeTransferFrom(msg.sender, address(this), amount); totalReceived += amount; emit Deposit(amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import '../Voters.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; contract VotersLockUnlock { using SafeERC20 for IERC20; function run(address voters, uint amount) public { Voters v = Voters(voters); IERC20(v.token()).safeTransferFrom(msg.sender, address(this), amount); IERC20(v.token()).approve(voters, amount); v.lock(amount); v.unlock(amount); } } //SPDX-License-Identifier: MIT pragma solidity 0.8.6; /* This contract allows the sale of an "offering" token in exchange for a "payment" token. It let's investors buy tokens at a fixed price but depending on the amount of interest investors will get a variable allocation size (also called batch auction). The sale is configured with an target amount of payment token to raise and set amount of offering tokens to sell. Investors can participate multiple times. Once the sale ends, investors get to claim their tokens and possibly their payment token refund (for the execess amount that wasn't used to purchase tokens). */ import '@openzeppelin/contracts/security/ReentrancyGuard.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import './interfaces/IVoters.sol'; contract Sale is ReentrancyGuard { using SafeERC20 for IERC20; // Information of each user's participation struct UserInfo { // How many tokens the user has provided uint amount; // Wether this user has already claimed their refund, defaults to false bool claimedRefund; // Wether this user has already claimed their share of tokens, defaults to false bool claimedTokens; } // Owner address, has access to withdrawing funds after the sale address public owner; // Keeper address, has access to tweaking sake parameters address public keeper; // The raising token IERC20 public paymentToken; // The offering token IERC20 public offeringToken; // The block number when sale starts uint public startBlock; // The block number when sale ends uint public endBlock; // The block number when tokens are redeemable uint public tokensBlock; // Total amount of raising tokens that need to be raised uint public raisingAmount; // Total amount of offeringToken that will be offered uint public offeringAmount; // Maximum a user can contribute uint public perUserCap; // Voting token minimum balance to participate uint public votingMinimum; // Voting token address IVoters public votingToken; // Voting token snapshot id to use for balances (optional) uint public votingSnapshotId; // Wether deposits are paused bool public paused; // Total amount of raising tokens that have already been raised uint public totalAmount; // Total amount payment token withdrawn by project uint public totalAmountWithdrawn; // User's participation info mapping(address => UserInfo) public userInfo; // Participants list address[] public addressList; event Deposit(address indexed user, uint amount); event HarvestRefund(address indexed user, uint amount); event HarvestTokens(address indexed user, uint amount); constructor( IERC20 _paymentToken, IERC20 _offeringToken, uint _startBlock, uint _endBlock, uint _tokensBlock, uint _offeringAmount, uint _raisingAmount, uint _perUserCap, address _owner, address _keeper ) { paymentToken = _paymentToken; offeringToken = _offeringToken; startBlock = _startBlock; endBlock = _endBlock; tokensBlock = _tokensBlock; offeringAmount = _offeringAmount; raisingAmount = _raisingAmount; perUserCap = _perUserCap; totalAmount = 0; owner = _owner; keeper = _keeper; _validateBlockParams(); require(_paymentToken != _offeringToken, 'payment != offering'); require(_offeringAmount > 0, 'offering > 0'); require(_raisingAmount > 0, 'raising > 0'); } modifier onlyOwner() { require(msg.sender == owner, "!owner"); _; } modifier onlyOwnerOrKeeper() { require(msg.sender == owner || msg.sender == keeper, "!owner or keeper"); _; } function _validateBlockParams() private view { require(startBlock > block.number, 'start > now'); require(endBlock >= startBlock, 'end > start'); require(endBlock - startBlock <= 172800, 'end < 1 month after start'); require(tokensBlock - endBlock <= 172800, 'tokens < 1 month after end'); } function setOfferingAmount(uint _offerAmount) public onlyOwnerOrKeeper { require (block.number < startBlock, 'sale started'); offeringAmount = _offerAmount; } function setRaisingAmount(uint _raisingAmount) public onlyOwnerOrKeeper { require (block.number < startBlock, 'sale started'); raisingAmount = _raisingAmount; } function setStartBlock(uint _block) public onlyOwnerOrKeeper { startBlock = _block; _validateBlockParams(); } function setEndBlock(uint _block) public onlyOwnerOrKeeper { endBlock = _block; _validateBlockParams(); } function setTokensBlock(uint _block) public onlyOwnerOrKeeper { tokensBlock = _block; _validateBlockParams(); } function configureVotingToken(uint minimum, address token, uint snapshotId) public onlyOwnerOrKeeper { votingMinimum = minimum; votingToken = IVoters(token); votingSnapshotId = snapshotId; } function togglePaused() public onlyOwnerOrKeeper { paused = !paused; } function deposit(uint _amount) public { require(!paused, 'paused'); require(block.number > startBlock && block.number < endBlock, 'sale not active'); require(_amount > 0, 'need amount > 0'); if (votingMinimum > 0) { if (votingSnapshotId == 0) { require(votingToken.balanceOf(msg.sender) >= votingMinimum, "under minimum locked"); } else { require(votingToken.balanceOfAt(msg.sender, votingSnapshotId) >= votingMinimum, "under minimum locked"); } } paymentToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (userInfo[msg.sender].amount == 0) { addressList.push(address(msg.sender)); } userInfo[msg.sender].amount = userInfo[msg.sender].amount + _amount; totalAmount = totalAmount + _amount; require(perUserCap == 0 || userInfo[msg.sender].amount <= perUserCap, 'over per user cap'); emit Deposit(msg.sender, _amount); } function harvestRefund() public nonReentrant { require (block.number > endBlock, 'not harvest time'); require (userInfo[msg.sender].amount > 0, 'have you participated?'); require (!userInfo[msg.sender].claimedRefund, 'nothing to harvest'); uint amount = getRefundingAmount(msg.sender); if (amount > 0) { paymentToken.safeTransfer(address(msg.sender), amount); } userInfo[msg.sender].claimedRefund = true; emit HarvestRefund(msg.sender, amount); } function harvestTokens() public nonReentrant { require (block.number > tokensBlock, 'not harvest time'); require (userInfo[msg.sender].amount > 0, 'have you participated?'); require (!userInfo[msg.sender].claimedTokens, 'nothing to harvest'); uint amount = getOfferingAmount(msg.sender); if (amount > 0) { offeringToken.safeTransfer(address(msg.sender), amount); } userInfo[msg.sender].claimedTokens = true; emit HarvestTokens(msg.sender, amount); } function harvestAll() public { harvestRefund(); harvestTokens(); } function hasHarvestedRefund(address _user) external view returns (bool) { return userInfo[_user].claimedRefund; } function hasHarvestedTokens(address _user) external view returns (bool) { return userInfo[_user].claimedTokens; } // Allocation in percent, 1 means 0.000001(0.0001%), 1000000 means 1(100%) function getUserAllocation(address _user) public view returns (uint) { return (userInfo[_user].amount * 1e12) / totalAmount / 1e6; } // Amount of offering token a user will receive function getOfferingAmount(address _user) public view returns (uint) { if (totalAmount > raisingAmount) { uint allocation = getUserAllocation(_user); return (offeringAmount * allocation) / 1e6; } else { return (userInfo[_user].amount * offeringAmount) / raisingAmount; } } // Amount of the offering token a user will be refunded function getRefundingAmount(address _user) public view returns (uint) { if (totalAmount <= raisingAmount) { return 0; } uint allocation = getUserAllocation(_user); uint payAmount = (raisingAmount * allocation) / 1e6; return userInfo[_user].amount - payAmount; } function getAddressListLength() external view returns (uint) { return addressList.length; } function getParams() external view returns (uint, uint, uint, uint, uint, uint, uint, uint) { return (startBlock, endBlock, tokensBlock, offeringAmount, raisingAmount, perUserCap, totalAmount, addressList.length); } function finalWithdraw(uint _paymentAmount, uint _offeringAmount) public onlyOwner { require (_paymentAmount <= paymentToken.balanceOf(address(this)), 'not enough payment token'); require (_offeringAmount <= offeringToken.balanceOf(address(this)), 'not enough offerring token'); if (_paymentAmount > 0) { paymentToken.safeTransfer(address(msg.sender), _paymentAmount); totalAmountWithdrawn += _paymentAmount; require(totalAmountWithdrawn <= raisingAmount, 'can only widthdraw what is owed'); } if (_offeringAmount > 0) { offeringToken.safeTransfer(address(msg.sender), _offeringAmount); } } } //SPDX-License-Identifier: MIT pragma solidity 0.8.6; /* This contract receives XRUNE token emissions, approximately once a day. It them allows it's `run` method to be called wich will split up it's current balance between the private investors, tema, dao and ecosystem contracts/addresses following their respective vesting curves. */ import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; interface IEmissionsPrivateDispenser { function deposit(uint amount) external; } contract EmissionsSplitter { using SafeERC20 for IERC20; uint public constant ONE_YEAR = 31536000; uint public constant INVESTORS_EMISSIONS_HALF1 = 45000000e18; uint public constant INVESTORS_EMISSIONS_HALF2 = 30000000e18; uint public constant TEAM_EMISSIONS_HALF1 = 66000000e18; uint public constant TEAM_EMISSIONS_HALF2 = 44000000e18; uint public constant ECOSYSTEM_EMISSIONS = 250000000e18; IERC20 public token; uint public emissionsStart; address public dao; // DAO contract address address public ecosystem; // Coucil Gnosis Safe address address public team; // Team Gnosis Safe address address public investors; // EmissionsPrivateDispenser address uint public sentToTeam; uint public sentToInvestors; uint public sentToEcosystem; event Split(uint amount, uint dao, uint team, uint investors, uint ecosystem); constructor(address _token, uint _emissionsStart, address _dao, address _team, address _investors, address _ecosystem) { token = IERC20(_token); emissionsStart = _emissionsStart; dao = _dao; team = _team; investors = _investors; ecosystem = _ecosystem; } function shouldRun() public view returns (bool) { return token.balanceOf(address(this)) > 0; } function run() public { uint initialAmount = token.balanceOf(address(this)); uint amount = initialAmount; require(amount > 0, "no balance to split"); uint sentToInvestorsNow = 0; { // Investors get 45M tokens linearly over the first year uint investorsProgress = _min(((block.timestamp - emissionsStart) * 1e12) / ONE_YEAR, 1e12); uint investorsUnlocked = (investorsProgress * INVESTORS_EMISSIONS_HALF1) / 1e12; uint investorsAmount = _min(investorsUnlocked - sentToInvestors, amount); if (investorsAmount > 0) { sentToInvestorsNow += investorsAmount; sentToInvestors += investorsAmount; amount -= investorsAmount; token.safeApprove(investors, investorsAmount); IEmissionsPrivateDispenser(investors).deposit(investorsAmount); } } { // Investors get their remaining 30M tokens linearly over the second year uint elapsed = block.timestamp - emissionsStart; elapsed -= _min(elapsed, ONE_YEAR); uint investorsProgress = _min((elapsed * 1e12) / ONE_YEAR, 1e12); uint investorsUnlocked = (investorsProgress * INVESTORS_EMISSIONS_HALF2) / 1e12; uint investorsAmount = _min(investorsUnlocked - _min(investorsUnlocked, sentToInvestors), amount); if (investorsAmount > 0) { sentToInvestorsNow += investorsAmount; sentToInvestors += investorsAmount; amount -= investorsAmount; token.safeApprove(investors, investorsAmount); IEmissionsPrivateDispenser(investors).deposit(investorsAmount); } } uint sentToTeamNow = 0; { // Team get 66M tokens linearly over the first 2 years uint teamProgress = _min(((block.timestamp - emissionsStart) * 1e12) / (2 * ONE_YEAR), 1e12); uint teamUnlocked = (teamProgress * TEAM_EMISSIONS_HALF1) / 1e12; uint teamAmount = _min(teamUnlocked - sentToTeam, amount); if (teamAmount > 0) { sentToTeamNow += teamAmount; sentToTeam += teamAmount; amount -= teamAmount; token.safeTransfer(team, teamAmount); } } { // Team get their remaining 44M tokens linearly over the next 2 years uint elapsed = block.timestamp - emissionsStart; elapsed -= _min(elapsed, 2 * ONE_YEAR); uint teamProgress = _min((elapsed * 1e12) / (2 * ONE_YEAR), 1e12); uint teamUnlocked = (teamProgress * TEAM_EMISSIONS_HALF1) / 1e12; uint teamAmount = _min(teamUnlocked - _min(teamUnlocked, sentToTeam), amount); if (teamAmount > 0) { sentToTeamNow += teamAmount; sentToTeam += teamAmount; amount -= teamAmount; token.safeTransfer(team, teamAmount); } } uint ecosystemProgress = _min(((block.timestamp - emissionsStart) * 1e12) / (10 * ONE_YEAR), 1e12); uint ecosystemUnlocked = (ecosystemProgress * ECOSYSTEM_EMISSIONS) / 1e12; uint ecosystemAmount = _min(ecosystemUnlocked - sentToEcosystem, amount); if (ecosystemAmount > 0) { sentToEcosystem += ecosystemAmount; amount -= ecosystemAmount; token.safeTransfer(ecosystem, ecosystemAmount); } if (amount > 0) { token.safeTransfer(dao, amount); } emit Split(initialAmount, amount, sentToTeamNow, sentToInvestorsNow, ecosystemAmount); } function _min(uint a, uint b) private pure returns (uint) { return a < b ? a : b; } }
How many tokens the user has provided What price this user secured Wether this user has already claimed their share of tokens, defaults to false
struct UserInfo { uint amount; uint price; bool claimedTokens; } event Deposit(address indexed user, uint amount, uint price); event HarvestTokens(address indexed user, uint amount); constructor( IERC20 _paymentToken, IERC20 _offeringToken, uint _startBlock, uint _endBlock, uint _tokensBlock, uint _startPrice, uint _priceVelocity, uint _offeringAmount, uint _perUserCap, address _owner, address _keeper
10,089,711
[ 1, 44, 543, 4906, 2430, 326, 729, 711, 2112, 18734, 6205, 333, 729, 1428, 2862, 678, 2437, 333, 729, 711, 1818, 7516, 329, 3675, 7433, 434, 2430, 16, 3467, 358, 629, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 1958, 25003, 288, 203, 1377, 2254, 3844, 31, 203, 1377, 2254, 6205, 31, 203, 1377, 1426, 7516, 329, 5157, 31, 203, 225, 289, 203, 203, 203, 203, 225, 871, 4019, 538, 305, 12, 2867, 8808, 729, 16, 2254, 3844, 16, 2254, 6205, 1769, 203, 225, 871, 670, 297, 26923, 5157, 12, 2867, 8808, 729, 16, 2254, 3844, 1769, 203, 203, 225, 3885, 12, 203, 1377, 467, 654, 39, 3462, 389, 9261, 1345, 16, 203, 1377, 467, 654, 39, 3462, 389, 23322, 310, 1345, 16, 203, 1377, 2254, 389, 1937, 1768, 16, 203, 1377, 2254, 389, 409, 1768, 16, 203, 1377, 2254, 389, 7860, 1768, 16, 203, 1377, 2254, 389, 1937, 5147, 16, 203, 1377, 2254, 389, 8694, 27522, 16, 203, 1377, 2254, 389, 23322, 310, 6275, 16, 203, 1377, 2254, 389, 457, 1299, 4664, 16, 203, 1377, 1758, 389, 8443, 16, 203, 1377, 1758, 389, 79, 9868, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x188cA46Aa2c7ae10C14A931512B62991D5901453/sources/src/Vault.sol
* @notice update the staker contract to a new one @param newStaker the new staker contract @custom:requires owner/ Unstake all wars from old staker
function setStaker(address newStaker) external onlyOwner { if (newStaker == address(0)) revert Errors.ZeroAddress(); address oldStaker = staker; staker = newStaker; emit StakerUpdated(oldStaker, newStaker); uint256 stakerBalance = ERC20(oldStaker).balanceOf(address(this)); if (stakerBalance != 0) { IStaker(oldStaker).unstake(stakerBalance, address(this)); } if (warBalance != 0) { IStaker(newStaker).stake(warBalance, address(this)); } }
16,192,862
[ 1, 2725, 326, 384, 6388, 6835, 358, 279, 394, 1245, 225, 394, 510, 6388, 326, 394, 384, 6388, 6835, 632, 3662, 30, 18942, 3410, 19, 1351, 334, 911, 777, 341, 5913, 628, 1592, 384, 6388, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 510, 6388, 12, 2867, 394, 510, 6388, 13, 3903, 1338, 5541, 288, 203, 3639, 309, 261, 2704, 510, 6388, 422, 1758, 12, 20, 3719, 15226, 9372, 18, 7170, 1887, 5621, 203, 3639, 1758, 1592, 510, 6388, 273, 384, 6388, 31, 203, 203, 3639, 384, 6388, 273, 394, 510, 6388, 31, 203, 3639, 3626, 934, 6388, 7381, 12, 1673, 510, 6388, 16, 394, 510, 6388, 1769, 203, 203, 3639, 2254, 5034, 384, 6388, 13937, 273, 4232, 39, 3462, 12, 1673, 510, 6388, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 334, 6388, 13937, 480, 374, 13, 288, 203, 5411, 467, 510, 6388, 12, 1673, 510, 6388, 2934, 23412, 911, 12, 334, 6388, 13937, 16, 1758, 12, 2211, 10019, 203, 3639, 289, 203, 203, 203, 3639, 309, 261, 905, 13937, 480, 374, 13, 288, 203, 5411, 467, 510, 6388, 12, 2704, 510, 6388, 2934, 334, 911, 12, 905, 13937, 16, 1758, 12, 2211, 10019, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x32234de40715073c70bf83415096e9e9265b6878 //Contract name: StandardCampaignFactory //Balance: 0 Ether //Verification Date: 2/8/2017 //Transacion Count: 4 // CODE STARTS HERE /* This file is part of WeiFund. */ /* The core campaign contract interface. Used across all WeiFund standard campaign contracts. */ pragma solidity ^0.4.4; /// @title Campaign contract interface for WeiFund standard campaigns /// @author Nick Dodson <[email protected]> contract Campaign { /// @notice the creater and operator of the campaign /// @return the Ethereum standard account address of the owner specified function owner() public constant returns(address) {} /// @notice the campaign interface version /// @return the version metadata function version() public constant returns(string) {} /// @notice the campaign name /// @return contractual metadata which specifies the campaign name as a string function name() public constant returns(string) {} /// @notice use to determine the contribution method abi/structure /// @return will return a string that is the exact contributeMethodABI function contributeMethodABI() public constant returns(string) {} /// @notice use to determine the contribution method abi /// @return will return a string that is the exact contributeMethodABI function refundMethodABI() public constant returns(string) {} /// @notice use to determine the contribution method abi /// @return will return a string that is the exact contributeMethodABI function payoutMethodABI() public constant returns(string) {} /// @notice use to determine the beneficiary destination for the campaign /// @return the beneficiary address that will receive the campaign payout function beneficiary() public constant returns(address) {} /// @notice the block number at which the campaign fails or succeeds /// @return the uint block number at which time the campaign expires function expiry() public constant returns(uint256 blockNumber) {} /// @notice the goal the campaign must reach in order for it to succeed /// @return the campaign funding goal specified in wei as a uint256 function fundingGoal() public constant returns(uint256 amount) {} /// @notice the maximum funding amount for this campaign /// @return the campaign funding cap specified in wei as a uint256 function fundingCap() public constant returns(uint256 amount) {} /// @notice the goal the campaign must reach in order for it to succeed /// @return the campaign funding goal specified in wei as a uint256 function amountRaised() public constant returns(uint256 amount) {} /// @notice the block number that the campaign was created /// @return the campaign start block specified as a block number, uint256 function created() public constant returns(uint256 timestamp) {} /// @notice the current stage the campaign is in /// @return the campaign stage the campaign is in with uint256 function stage() public constant returns(uint256); /// @notice if it supports it, return the contribution by ID /// @return returns the contribution tx sender, value and time sent function contributions(uint256 _contributionID) public constant returns(address _sender, uint256 _value, uint256 _time) {} // Campaign events event ContributionMade (address _contributor); event RefundPayoutClaimed(address _payoutDestination, uint256 _payoutAmount); event BeneficiaryPayoutClaimed (address _payoutDestination); } /* This file is part of WeiFund. */ /* The enhancer interface for the CampaignEnhancer contract. */ pragma solidity ^0.4.4; /// @title The campaign enhancer interface contract for build enhancer contracts. /// @author Nick Dodson <[email protected]> contract Enhancer { /// @notice enables the setting of the campaign, if any /// @dev allow the owner to set the campaign function setCampaign(address _campaign) public {} /// @notice notate contribution /// @param _sender The address of the contribution sender /// @param _value The value of the contribution /// @param _blockNumber The block number of the contribution /// @param _amounts The specified contribution product amounts, if any /// @return Whether or not the campaign is an early success after this contribution /// @dev enables the notation of contribution data, and triggering of early success, if need be function notate(address _sender, uint256 _value, uint256 _blockNumber, uint256[] _amounts) public returns (bool earlySuccess) {} } /* This file is part of WeiFund. */ /* A common Owned contract that contains properties for contract ownership. */ pragma solidity ^0.4.4; /// @title A single owned campaign contract for instantiating ownership properties. /// @author Nick Dodson <[email protected]> contract Owned { // only the owner can use this method modifier onlyowner() { if (msg.sender != owner) { throw; } _; } // the owner property address public owner; } /* This file is part of WeiFund. */ /* This is the standard claim contract interface. This used accross all claim contracts. Claim contracts are used for the pickup of digital assets, such as tokens. Note, a campaign enhancer could be a claim as well. This is our general claim interface. */ pragma solidity ^0.4.4; /// @title Claim contract interface. /// @author Nick Dodson <[email protected]> contract Claim { /// @return returns the claim ABI solidity method for this claim function claimMethodABI() constant public returns (string) {} // the claim success event, used for whent he claim has successfully be used event ClaimSuccess(address _sender); } /* This file is part of WeiFund. */ /* The balance claim is used for dispersing balances of refunds for standard camaign contracts. Instead of the contract sending a balance directly to the contributor, it will send the balance to a balancelciam contract. */ pragma solidity ^0.4.4; /// @title The balance claim interface contract, used for defining balance claims. /// @author Nick Dodson <[email protected]> contract BalanceClaimInterface { /// @dev used to claim balance of the balance claim function claimBalance() public {} } /// @title The balance claim, used for sending balances owed to a claim contract. /// @author Nick Dodson <[email protected]> contract BalanceClaim is Owned, Claim, BalanceClaimInterface { /// @notice receive funds function () payable public {} /// @dev the claim balance method, claim the balance then suicide the contract function claimBalance() onlyowner public { // self destruct and send all funds to the balance claim owner selfdestruct(owner); } /// @notice The BalanceClaim constructor method /// @param _owner the address of the balance claim owner function BalanceClaim(address _owner) { // specify the balance claim owner owner = _owner; } // the claim method ABI metadata for user interfaces, written in standard // solidity ABI method format string constant public claimMethodABI = "claimBalance()"; } /* This file is part of WeiFund. */ /* The private service registry is used in WeiFund factory contracts to register generated service contracts, such as our WeiFund standard campaign and enhanced standard campaign contracts. It is usually only inherited by other contracts. */ pragma solidity ^0.4.4; /// @title Private Service Registry - used to register generated service contracts. /// @author Nick Dodson <[email protected]> contract PrivateServiceRegistryInterface { /// @notice register the service '_service' with the private service registry /// @param _service the service contract to be registered /// @return the service ID 'serviceId' function register(address _service) internal returns (uint256 serviceId) {} /// @notice is the service in question '_service' a registered service with this registry /// @param _service the service contract address /// @return either yes (true) the service is registered or no (false) the service is not function isService(address _service) public constant returns (bool) {} /// @notice helps to get service address /// @param _serviceId the service ID /// @return returns the service address of service ID function services(uint256 _serviceId) public constant returns (address _service) {} /// @notice returns the id of a service address, if any /// @param _service the service contract address /// @return the service id of a service function ids(address _service) public constant returns (uint256 serviceId) {} event ServiceRegistered(address _sender, address _service); } contract PrivateServiceRegistry is PrivateServiceRegistryInterface { modifier isRegisteredService(address _service) { // does the service exist in the registry, is the service address not empty if (services.length > 0) { if (services[ids[_service]] == _service && _service != address(0)) { _; } } } modifier isNotRegisteredService(address _service) { // if the service '_service' is not a registered service if (!isService(_service)) { _; } } function register(address _service) internal isNotRegisteredService(_service) returns (uint serviceId) { // create service ID by increasing services length serviceId = services.length++; // set the new service ID to the '_service' address services[serviceId] = _service; // set the ids store to link to the 'serviceId' created ids[_service] = serviceId; // fire the 'ServiceRegistered' event ServiceRegistered(msg.sender, _service); } function isService(address _service) public constant isRegisteredService(_service) returns (bool) { return true; } address[] public services; mapping(address => uint256) public ids; } /* This file is part of WeiFund. */ /* This file is part of WeiFund. */ /* Standard enhanced campaign for WeiFund. A generic crowdsale mechanism for issuing and dispersing digital assets on Ethereum. */ pragma solidity ^0.4.4; /* Interfaces */ /* Specified Contracts */ /// @title Standard Campaign -- enables generic crowdsales that disperse digital assets /// @author Nick Dodson <[email protected]> contract StandardCampaign is Owned, Campaign { // the three possible states enum Stages { CrowdfundOperational, CrowdfundFailure, CrowdfundSuccess } // the campaign state machine enforcement modifier atStage(Stages _expectedStage) { // if the current state does not equal the expected one, throw if (stage() != uint256(_expectedStage)) { throw; } else { // continue with state changing operations _; } } // if the contribution is valid, then carry on with state changing operations // notate the contribution with the enhancer, if the notation method // returns true, then trigger an early success (e.g. token cap reached) modifier validContribution() { // if the msg value is zero or amount raised plus the curent message value // is greater than the funding cap, then throw error if (msg.value == 0 || amountRaised + msg.value > fundingCap || amountRaised + msg.value < amountRaised) { throw; } else { // carry on with state changing operations _; } } // if the contribution is a valid refund claim, then carry on with state // changing operations modifier validRefundClaim(uint256 _contributionID) { // get the contribution data for the refund Contribution refundContribution = contributions[_contributionID]; // if the refund has already been claimed or the refund sender is not the // current message sender, throw error if(refundsClaimed[_contributionID] == true // the refund for this contribution is not claimed || refundContribution.sender != msg.sender){ // the contribution sender is the msg.sender throw; } else { // all is good, carry on with state changing operations _; } } // only the beneficiary can use the method with this modifier modifier onlybeneficiary() { if (msg.sender != beneficiary) { throw; } else { _; } } // allow for fallback function to be used to make contributions function () public payable { contributeMsgValue(defaultAmounts); } // the current campaign stage function stage() public constant returns (uint256) { // if current time is less than the expiry, the crowdfund is operational if (block.number < expiry && earlySuccess == false && amountRaised < fundingCap) { return uint256(Stages.CrowdfundOperational); // if n >= e and aR < fG then the crowdfund is a failure } else if(block.number >= expiry && earlySuccess == false && amountRaised < fundingGoal) { return uint256(Stages.CrowdfundFailure); // if n >= e and aR >= fG or aR >= fC or early success triggered // then the crowdfund is a success (enhancers can trigger early success) // early success is generally used for TokenCap enforcement } else if((block.number >= expiry && amountRaised >= fundingGoal) || earlySuccess == true || amountRaised >= fundingCap) { return uint256(Stages.CrowdfundSuccess); } } // contribute message value if the contribution is valid and the campaign // is in stage operational, allow for complex amounts to be transacted function contributeMsgValue(uint256[] _amounts) public // anyone can attempt to use this method payable // the method is payable and can accept ether atStage(Stages.CrowdfundOperational) // must be at stage operational, done before validContribution validContribution() // contribution must be valid, stage check done first returns (uint256 contributionID) { // increase contributions array length by 1, set as contribution ID contributionID = contributions.length++; // store contribution data in the contributions array contributions[contributionID] = Contribution({ sender: msg.sender, value: msg.value, created: block.number }); // add the contribution ID to that senders address contributionsBySender[msg.sender].push(contributionID); // increase the amount raised by the message value amountRaised += msg.value; // fire the contribution made event ContributionMade(msg.sender); // notate the contribution with the campaign enhancer, if the notation // method returns true, then trigger an early success // the enahncer is treated as malicious here, and is thus wrapped in a // conditional for saftey, note the enhancer may throw as well if (enhancer.notate(msg.sender, msg.value, block.number, _amounts)) { // set early success to true, note, it cannot be reversed once set to true // also validContribution must be after atStage modifier // so that early success is triggered after stage check, not before // early success is used to trigger an early campaign success before the funding // cap is reached. This is generally used for things like hitting the token cap earlySuccess = true; } } // payout the current balance to the beneficiary, if the crowdfund is in // stage success function payoutToBeneficiary() public onlybeneficiary() { // additionally trigger early success, this will force the Success state // forcing the success state keeps the contract state machine rigid // and ensures other third-party contracts that look to this state // that this contract is in state success earlySuccess = true; // send funds to the benerifiary if (!beneficiary.send(this.balance)) { throw; } else { // fire the BeneficiaryPayoutClaimed event BeneficiaryPayoutClaimed(beneficiary); } } // claim refund owed if you are a contributor and the campaign is in stage // failure. Only valid claims will be fulfilled. // will return the balance claim address where funds can be picked up by // contributor. A BalanceClaim is used to further prevent re-entrancy. function claimRefundOwed(uint256 _contributionID) public atStage(Stages.CrowdfundFailure) // in stage failure validRefundClaim(_contributionID) // the claim is a valid refund claim returns (address balanceClaim) { // return the balance claim address // set claimed to true right away refundsClaimed[_contributionID] = true; // get the contribution data for that contribution ID Contribution refundContribution = contributions[_contributionID]; // send funds to the newly created balance claim contract balanceClaim = address(new BalanceClaim(refundContribution.sender)); // set refunds claim address refundClaimAddress[_contributionID] = balanceClaim; // send funds to the newly created balance claim contract if (!balanceClaim.send(refundContribution.value)) { throw; } // fire the refund payed out event RefundPayoutClaimed(balanceClaim, refundContribution.value); } // the total number of valid contributions made to this campaign function totalContributions() public constant returns (uint256 amount) { return uint256(contributions.length); } // get the total number of contributions made a sender function totalContributionsBySender(address _sender) public constant returns (uint256 amount) { return uint256(contributionsBySender[_sender].length); } // the contract constructor function StandardCampaign(string _name, uint256 _expiry, uint256 _fundingGoal, uint256 _fundingCap, address _beneficiary, address _owner, address _enhancer) public { // set the campaign name name = _name; // the campaign expiry in blocks expiry = _expiry; // the fundign goal in wei fundingGoal = _fundingGoal; // the campaign funding cap in wei fundingCap = _fundingCap; // the benerifiary address beneficiary = _beneficiary; // the owner or operator of the campaign owner = _owner; // the time the campaign was created created = block.number; // the campaign enhancer contract enhancer = Enhancer(_enhancer); } // the Contribution data structure struct Contribution { // the contribution sender address sender; // the value of the contribution uint256 value; // the time the contribution was created uint256 created; } // default amounts used uint256[] defaultAmounts; // campaign enhancer, usually for token notation Enhancer public enhancer; // the early success bool, used for triggering early success bool public earlySuccess; // the operator of the campaign address public owner; // the minimum amount of funds needed to be a success after expiry (in wei) uint256 public fundingGoal; // the maximum amount of funds that can be raised (in wei) uint256 public fundingCap; // the total amount raised by this campaign (in wei) uint256 public amountRaised; // the current campaign expiry (future block number) uint256 public expiry; // the time at which the campaign was created (in UNIX timestamp) uint256 public created; // the beneficiary of the funds raised, if the campaign is a success address public beneficiary; // the contributions data store, where all contributions are notated Contribution[] public contributions; // all contribution ID's of a specific sender mapping(address => uint256[]) public contributionsBySender; // the refund BalanceClaim address of a specific refund claim // maps the (contribution ID => refund claim address) mapping(uint256 => address) public refundClaimAddress; // maps the contribution ID to a bool (has the refund been claimed for this // contribution) mapping(uint256 => bool) public refundsClaimed; // the human readable name of the Campaign, for metadata string public name; // the contract version number, if any string constant public version = "0.1.0"; // the contribution method ABI as a string, written in standard solidity // ABI format, this is generally used so that UI's can understand the campaign string constant public contributeMethodABI = "contributeMsgValue(uint256[]):(uint256)"; // the payout to beneficiary ABI, written in standard solidity ABI format string constant public payoutMethodABI = "payoutToBeneficiary()"; // the refund method ABI, written in standard solidity ABI format string constant public refundMethodABI = "claimRefundOwed(uint256):(address)"; } /* This file is part of WeiFund. */ /* An empty campaign enhancer, used to fulfill an enhancer of a WeiFund enhanced standard campaign. */ pragma solidity ^0.4.4; /// @title Empty Enhancer - used to test enhanced standard campaign contracts /// @author Nick Dodson <[email protected]> contract EmptyEnhancer is Enhancer { /// @dev notate contribution data, and trigger early success if need be function notate(address _sender, uint256 _value, uint256 _blockNumber, uint256[] _amounts) public returns (bool earlySuccess) { return false; } } /* A factory contract used for the generation and registration of WeiFund enhanced standard campaign contracts. */ pragma solidity ^0.4.4; /// @title Enhanced Standard Campaign Factory - used to generate and register standard campaigns /// @author Nick Dodson <[email protected]> contract StandardCampaignFactory is PrivateServiceRegistry { function createStandardCampaign(string _name, uint256 _expiry, uint256 _fundingGoal, uint256 _fundingCap, address _beneficiary, address _enhancer) public returns (address campaignAddress) { // create the new enhanced standard campaign campaignAddress = address(new StandardCampaign(_name, _expiry, _fundingGoal, _fundingCap, _beneficiary, msg.sender, _enhancer)); // register the campaign address register(campaignAddress); } }
if the service '_service' is not a registered service
modifier isNotRegisteredService(address _service) { if (!isService(_service)) { _; } }
12,875,197
[ 1, 430, 326, 1156, 2070, 3278, 11, 353, 486, 279, 4104, 1156, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 9606, 8827, 10868, 1179, 12, 2867, 389, 3278, 13, 288, 203, 565, 309, 16051, 291, 1179, 24899, 3278, 3719, 288, 203, 1377, 389, 31, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "./IERC721LibBeforeTokenTransferHook.sol"; /* Functionality used to whitelist OpenSea trading address, if desired */ contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, the Enumerable extension, and Pausable. * * Closely based on and mirrors the excellent https://openzeppelin.com/contracts/. */ library ERC721Lib { using Address for address; using Strings for uint256; /** * @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 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); struct ERC721Storage { // Token name string _name; // Token symbol string _symbol; // Mapping from token ID to owner address mapping (uint256 => address) _owners; // Mapping owner address to token count mapping (address => uint256) _balances; // Mapping from token ID to approved address mapping (uint256 => address) _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) _operatorApprovals; // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) _allTokensIndex; // Base URI string _baseURI; // True if token transfers are paused bool _paused; // Hook function that can be called before token is transferred, along with a pointer to its storage struct IERC721LibBeforeTokenTransferHook _beforeTokenTransferHookInterface; bytes32 _beforeTokenTransferHookStorageSlot; address proxyRegistryAddress; } function init(ERC721Storage storage s, string memory _name, string memory _symbol) external { s._name = _name; s._symbol = _symbol; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) external pure returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId; } // // Start of ERC721 functions // /** * @dev See {IERC721-balanceOf}. */ function _balanceOf(ERC721Storage storage s, address owner) internal view returns (uint256) { require(owner != address(0), "Balance query for address zero"); return s._balances[owner]; } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(ERC721Storage storage s, address owner) external view returns (uint256) { return _balanceOf(s, owner); } /** * @dev See {IERC721-ownerOf}. */ function _ownerOf(ERC721Storage storage s, uint256 tokenId) internal view returns (address) { address owner = s._owners[tokenId]; require(owner != address(0), "Owner query for nonexist. token"); return owner; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(ERC721Storage storage s, uint256 tokenId) external view returns (address) { return _ownerOf(s, tokenId); } /** * @dev See {IERC721Metadata-name}. */ function name(ERC721Storage storage s) external view returns (string memory) { return s._name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol(ERC721Storage storage s) external view returns (string memory) { return s._symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(ERC721Storage storage s, uint256 tokenId) external view returns (string memory) { require(_exists(s, tokenId), "URI query for nonexistent token"); return bytes(s._baseURI).length > 0 ? string(abi.encodePacked(s._baseURI, tokenId.toString())) : ""; } /** * @dev Set base URI */ function setBaseURI(ERC721Storage storage s, string memory baseTokenURI) external { s._baseURI = baseTokenURI; } /** * @dev See {IERC721-approve}. */ function approve(ERC721Storage storage s, address to, uint256 tokenId) external { address owner = _ownerOf(s, tokenId); require(to != owner, "Approval to current owner"); require(msg.sender == owner || _isApprovedForAll(s, owner, msg.sender), "Not owner nor approved for all" ); _approve(s, to, tokenId); } /** * @dev Approve independently of who's the owner * * Obviously expose with care... */ function overrideApprove(ERC721Storage storage s, address to, uint256 tokenId) external { _approve(s, to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function _getApproved(ERC721Storage storage s, uint256 tokenId) internal view returns (address) { require(_exists(s, tokenId), "Approved query nonexist. token"); return s._tokenApprovals[tokenId]; } /** * @dev See {IERC721-getApproved}. */ function getApproved(ERC721Storage storage s, uint256 tokenId) external view returns (address) { return _getApproved(s, tokenId); } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(ERC721Storage storage s, address operator, bool approved) external { require(operator != msg.sender, "Attempted approve to caller"); s._operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function _isApprovedForAll(ERC721Storage storage s, address owner, address operator) internal view returns (bool) { // Whitelist OpenSea proxy contract for easy trading - if we have a valid proxy registry address on file if (s.proxyRegistryAddress != address(0)) { ProxyRegistry proxyRegistry = ProxyRegistry(s.proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } } return s._operatorApprovals[owner][operator]; } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(ERC721Storage storage s, address owner, address operator) external view returns (bool) { return _isApprovedForAll(s, owner, operator); } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(ERC721Storage storage s, address from, address to, uint256 tokenId) external { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(s, msg.sender, tokenId), "TransferFrom not owner/approved"); _transfer(s, from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(ERC721Storage storage s, address from, address to, uint256 tokenId) external { _safeTransferFrom(s, from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function _safeTransferFrom(ERC721Storage storage s, address from, address to, uint256 tokenId, bytes memory _data) internal { require(_isApprovedOrOwner(s, msg.sender, tokenId), "TransferFrom not owner/approved"); _safeTransfer(s, from, to, tokenId, _data); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(ERC721Storage storage s, address from, address to, uint256 tokenId, bytes memory _data) external { _safeTransferFrom(s, 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(ERC721Storage storage s, address from, address to, uint256 tokenId, bytes memory _data) internal { _transfer(s, from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "Transfer to non ERC721Receiver"); } /** * @dev directSafeTransfer * * CAREFUL, this does not verify the previous ownership - only use if ownership/eligibility has been asserted by other means */ function directSafeTransfer(ERC721Storage storage s, address from, address to, uint256 tokenId, bytes memory _data) external { _safeTransfer(s, from, to, tokenId, _data); } /** * @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(ERC721Storage storage s, uint256 tokenId) internal view returns (bool) { return s._owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(ERC721Storage storage s, address spender, uint256 tokenId) internal view returns (bool) { require(_exists(s, tokenId), "Operator query nonexist. token"); address owner = _ownerOf(s, tokenId); return (spender == owner || _getApproved(s, tokenId) == spender || _isApprovedForAll(s, 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(ERC721Storage storage s, address to, uint256 tokenId) internal { _safeMint(s, 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(ERC721Storage storage s, address to, uint256 tokenId, bytes memory _data) internal { _unsafeMint(s, to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "Transfer to non ERC721Receiver"); } /** * @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 _unsafeMint(ERC721Storage storage s, address to, uint256 tokenId) internal { require(to != address(0), "Mint to the zero address"); require(!_exists(s, tokenId), "Token already minted"); _beforeTokenTransfer(s, address(0), to, tokenId); s._balances[to] += 1; s._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(ERC721Storage storage s, uint256 tokenId) internal { address owner = _ownerOf(s, tokenId); _beforeTokenTransfer(s, owner, address(0), tokenId); // Clear approvals _approve(s, address(0), tokenId); s._balances[owner] -= 1; delete s._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(ERC721Storage storage s, address from, address to, uint256 tokenId) internal { require(_ownerOf(s, tokenId) == from, "TransferFrom not owner/approved"); require(to != address(0), "Transfer to the zero address"); _beforeTokenTransfer(s, from, to, tokenId); // Clear approvals from the previous owner _approve(s, address(0), tokenId); s._balances[from] -= 1; s._balances[to] += 1; s._owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(ERC721Storage storage s, address to, uint256 tokenId) internal { s._tokenApprovals[tokenId] = to; emit Approval(_ownerOf(s, 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(msg.sender, from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("Transfer to non ERC721Receiver"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } // // Start of functions from ERC721Enumerable // /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(ERC721Storage storage s, address owner, uint256 index) external view returns (uint256) { require(index < _balanceOf(s, owner), "Owner index out of bounds"); return s._ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function _totalSupply(ERC721Storage storage s) internal view returns (uint256) { return s._allTokens.length; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply(ERC721Storage storage s) external view returns (uint256) { return s._allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(ERC721Storage storage s, uint256 index) external view returns (uint256) { require(index < _totalSupply(s), "Global index out of bounds"); return s._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(ERC721Storage storage s, address from, address to, uint256 tokenId) internal { if(address(s._beforeTokenTransferHookInterface) != address(0)) { // We have a hook that we need to delegate call (bool success, ) = address(s._beforeTokenTransferHookInterface).delegatecall( abi.encodeWithSelector(s._beforeTokenTransferHookInterface._beforeTokenTransferHook.selector, s._beforeTokenTransferHookStorageSlot, from, to, tokenId) ); if(!success) { // Bubble up the revert message assembly { let ptr := mload(0x40) let size := returndatasize() returndatacopy(ptr, 0, size) revert(ptr, size) } } } require(!_paused(s), "No token transfer while paused"); if (from == address(0)) { _addTokenToAllTokensEnumeration(s, tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(s, from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(s, tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(s, 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(ERC721Storage storage s, address to, uint256 tokenId) private { uint256 length = _balanceOf(s, to); s._ownedTokens[to][length] = tokenId; s._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(ERC721Storage storage s, uint256 tokenId) private { s._allTokensIndex[tokenId] = s._allTokens.length; s._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(ERC721Storage storage s, 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 = _balanceOf(s, from) - 1; uint256 tokenIndex = s._ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = s._ownedTokens[from][lastTokenIndex]; s._ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token s._ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete s._ownedTokensIndex[tokenId]; delete s._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(ERC721Storage storage s, 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 = s._allTokens.length - 1; uint256 tokenIndex = s._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 = s._allTokens[lastTokenIndex]; s._allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token s._allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete s._allTokensIndex[tokenId]; s._allTokens.pop(); } // // Start of functions from Pausable // /** * @dev Returns true if the contract is paused, and false otherwise. */ function _paused(ERC721Storage storage s) internal view returns (bool) { return s._paused; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused(ERC721Storage storage s) external view returns (bool) { return s._paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused(ERC721Storage storage s) { require(!_paused(s), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused(ERC721Storage storage s) { require(_paused(s), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause(ERC721Storage storage s) external whenNotPaused(s) { s._paused = true; emit Paused(msg.sender); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause(ERC721Storage storage s) external whenPaused(s) { s._paused = false; emit Unpaused(msg.sender); } } // 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; 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; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC721Lib.sol"; /** * @dev Interface that can be used to hook additional beforeTokenTransfer functions into ERC721Lib */ interface IERC721LibBeforeTokenTransferHook { /** * @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 _beforeTokenTransferHook(bytes32 storagePosition, address from, address to, uint256 tokenId) external; } // 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); }
Update the moved token's index
s._ownedTokensIndex[lastTokenId] = tokenIndex;
6,935,756
[ 1, 1891, 326, 10456, 1147, 1807, 770, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 272, 6315, 995, 329, 5157, 1016, 63, 2722, 1345, 548, 65, 273, 1147, 1016, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x64e5766cC5efFa782D2c43cFCbd5b44388207953/sources/browser/contracts/ytbNFT.sol
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension/
interface IERC721Enumerable is IERC721 { function totalSupply() external view returns (uint256); function tokenOfOwnerByIndex2(address owner, uint256 index) external view returns (uint256 tokenId); function tokenByIndex(uint256 index) external view returns (uint256); } }
12,271,399
[ 1, 654, 39, 17, 27, 5340, 3858, 17, 42, 20651, 1523, 3155, 8263, 16, 3129, 16836, 2710, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 654, 39, 27, 5340, 3572, 25121, 353, 467, 654, 39, 27, 5340, 288, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 1147, 951, 5541, 21268, 22, 12, 2867, 3410, 16, 2254, 5034, 770, 13, 3903, 1476, 1135, 261, 11890, 5034, 1147, 548, 1769, 203, 203, 565, 445, 1147, 21268, 12, 11890, 5034, 770, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 97, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event 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, "You are not the owner of this contract."); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: zeppelin-solidity/contracts/lifecycle/Destructible.sol /** * @title Destructible * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. */ contract Destructible is Ownable { constructor() public payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } // File: zeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused, "this contract is paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { 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; } } // File: contracts/marketplace/Marketplace.sol /** * @title Interface for contracts conforming to ERC-20 */ contract ERC20Interface { function transferFrom(address from, address to, uint tokens) public returns (bool success); } /** * @title Interface for contracts conforming to ERC-721 */ contract ERC721Interface { function ownerOf(uint256 assetId) public view returns (address); function safeTransferFrom(address from, address to, uint256 assetId) public; function isAuthorized(address operator, uint256 assetId) public view returns (bool); function exists(uint256 assetId) public view returns (bool); } contract DCLEscrow is Ownable, Pausable, Destructible { using SafeMath for uint256; ERC20Interface public acceptedToken; ERC721Interface public nonFungibleRegistry; struct Escrow { bytes32 id; address seller; address buyer; uint256 price; uint256 offer; bool acceptsOffers; bool publicE; uint256 escrowByOwnerIdPos; uint256 parcelCount; address highestBidder; uint256 lastOfferPrice; } struct Offer { address highestOffer; uint256 highestOfferPrice; address previousOffer; } mapping (uint256 => Escrow) public escrowByAssetId; mapping (bytes32 => Escrow) public escrowByEscrowId; mapping (bytes32 => Offer) public offersByEscrowId; mapping (address => Escrow[]) public escrowByOwnerId; mapping(address => uint256) public openedEscrowsByOwnerId; mapping(address => uint256) public ownerEscrowsCounter; mapping(address => uint256[]) public allOwnerParcelsOnEscrow; mapping(bytes32 => uint256[]) public assetIdByEscrowId; mapping(address => bool) public whitelistAddresses; uint256 public whitelistCounter; uint256 public publicationFeeInWei; //15000000000000000000 uint256 private publicationFeeTotal; bytes32[] public allEscrowIds; //address[] public whitelistAddressGetter; /* EVENTS */ event EscrowCreated( bytes32 id, address indexed seller, address indexed buyer, uint256 priceInWei, bool acceptsOffers, bool publicE, uint256 parcels ); event EscrowSuccessful( bytes32 id, address indexed seller, uint256 totalPrice, address indexed winner ); event EscrowCancelled( bytes32 id, address indexed seller ); function addAddressWhitelist(address toWhitelist) public onlyOwner { require(toWhitelist != address(0), "Address cannot be empty."); whitelistAddresses[toWhitelist] = true; } /* function getwhitelistCounter() public onlyOwner view returns(uint256) { return whitelistCounter; } function getwhitelistAddress(uint256 index) public onlyOwner view returns(address) { return whitelistAddressGetter[index]; } function deleteWhitelistAddress(address toDelete, uint256 index) public onlyOwner { require(toDelete != address(0), "Address cannot be blank."); require(index > 0, "index needs to be greater than zero."); delete whitelistAddresses[toDelete]; delete whitelistAddressGetter[index]; } */ function updateEscrow(address _acceptedToken, address _nonFungibleRegistry) public onlyOwner { acceptedToken = ERC20Interface(_acceptedToken); nonFungibleRegistry = ERC721Interface(_nonFungibleRegistry); } constructor (address _acceptedToken, address _nonFungibleRegistry) public { acceptedToken = ERC20Interface(_acceptedToken); nonFungibleRegistry = ERC721Interface(_nonFungibleRegistry); } function setPublicationFee(uint256 publicationFee) onlyOwner public { publicationFeeInWei = publicationFee; } function getPublicationFeeTotal() public onlyOwner view returns(uint256) { return publicationFeeTotal; } function getTotalEscrowCount() public view returns(uint256) { return allEscrowIds.length; } function getSingleEscrowAdmin(bytes32 index) public view returns (bytes32, address, address,uint256, uint256, bool, bool, uint256, uint256, address, uint256) { Escrow storage tempEscrow = escrowByEscrowId[index]; return ( tempEscrow.id, tempEscrow.seller, tempEscrow.buyer, tempEscrow.price, tempEscrow.offer, tempEscrow.publicE, tempEscrow.acceptsOffers, tempEscrow.escrowByOwnerIdPos, tempEscrow.parcelCount, tempEscrow.highestBidder, tempEscrow.lastOfferPrice); } function getAssetByEscrowIdLength(bytes32 escrowId) public view returns (uint256) { return assetIdByEscrowId[escrowId].length; } function getSingleAssetByEscrowIdLength(bytes32 escrowId, uint index) public view returns (uint256) { return assetIdByEscrowId[escrowId][index]; } function getEscrowCountByAssetIdArray(address ownerAddress) public view returns (uint256) { return ownerEscrowsCounter[ownerAddress]; } function getAllOwnedParcelsOnEscrow(address ownerAddress) public view returns (uint256) { return allOwnerParcelsOnEscrow[ownerAddress].length; } function getParcelAssetIdOnEscrow(address ownerAddress,uint index) public view returns (uint256) { return allOwnerParcelsOnEscrow[ownerAddress][index]; } function getEscrowCountById(address ownerAddress) public view returns (uint) { return escrowByOwnerId[ownerAddress].length; } function getEscrowInfo(address ownerAddress, uint index) public view returns (bytes32, address, address,uint256, uint256, bool, bool, uint256, uint256, address, uint256) { Escrow storage tempEscrow = escrowByOwnerId[ownerAddress][index]; return ( tempEscrow.id, tempEscrow.seller, tempEscrow.buyer, tempEscrow.price, tempEscrow.offer, tempEscrow.publicE, tempEscrow.acceptsOffers, tempEscrow.escrowByOwnerIdPos, tempEscrow.parcelCount, tempEscrow.highestBidder, tempEscrow.lastOfferPrice); } function placeOffer(bytes32 escrowId, uint256 offerPrice) public whenNotPaused { address seller = escrowByEscrowId[escrowId].seller; require(seller != msg.sender, "You are the owner of this escrow."); require(seller != address(0)); require(offerPrice > 0, "Offer Price needs to be greater than zero"); require(escrowByEscrowId[escrowId].id != '0x0', "That escrow ID is no longer valid."); bool acceptsOffers = escrowByEscrowId[escrowId].acceptsOffers; require(acceptsOffers, "This escrow does not accept offers."); //address buyer = escrowByEscrowId[escrowId].buyer; bool isPublic = escrowByEscrowId[escrowId].publicE; if(!isPublic) { require(msg.sender == escrowByEscrowId[escrowId].buyer, "You are not authorized for this escrow."); } Escrow memory tempEscrow = escrowByEscrowId[escrowId]; tempEscrow.lastOfferPrice = tempEscrow.offer; tempEscrow.offer = offerPrice; tempEscrow.highestBidder = msg.sender; escrowByEscrowId[escrowId] = tempEscrow; } function createNewEscrow(uint256[] memory assedIds, uint256 escrowPrice, bool doesAcceptOffers, bool isPublic, address buyer) public whenNotPaused{ //address tempAssetOwner = msg.sender; uint256 tempParcelCount = assedIds.length; for(uint i = 0; i < tempParcelCount; i++) { address assetOwner = nonFungibleRegistry.ownerOf(assedIds[i]); require(msg.sender == assetOwner, "You are not the owner of this parcel."); require(nonFungibleRegistry.exists(assedIds[i]), "This parcel does not exist."); require(nonFungibleRegistry.isAuthorized(address(this), assedIds[i]), "You have not authorized DCL Escrow to manage your LAND tokens."); allOwnerParcelsOnEscrow[assetOwner].push(assedIds[i]); } require(escrowPrice > 0, "Please pass a price greater than zero."); bytes32 escrowId = keccak256(abi.encodePacked( block.timestamp, msg.sender, assedIds[0], escrowPrice )); assetIdByEscrowId[escrowId] = assedIds; //uint256 memEscrowByOwnerIdPos = openedEscrowsByOwnerId[assetOwner]; Escrow memory memEscrow = Escrow({ id: escrowId, seller: msg.sender, buyer: buyer, price: escrowPrice, offer:0, publicE:isPublic, acceptsOffers: doesAcceptOffers, escrowByOwnerIdPos: 0, parcelCount: tempParcelCount, highestBidder: address(0), lastOfferPrice: 0 }); escrowByEscrowId[escrowId] = memEscrow; escrowByOwnerId[msg.sender].push(memEscrow); //ownerEscrowsCounter[msg.sender] = getEscrowCountByAssetIdArray(msg.sender) + 1; allEscrowIds.push(escrowId); emit EscrowCreated( escrowId, msg.sender, buyer, escrowPrice, doesAcceptOffers, isPublic, tempParcelCount ); } function cancelAllEscrows() public onlyOwner { //need to delete each escrow by escrow id pause(); for(uint e = 0; e < getTotalEscrowCount(); e++) { adminRemoveEscrow(allEscrowIds[e]); } delete allEscrowIds; unpause(); } function adminRemoveEscrow(bytes32 escrowId) public onlyOwner { address seller = escrowByEscrowId[escrowId].seller; //require(seller == msg.sender || msg.sender == owner); //uint256 escrowOwnerPos = escrowByEscrowId[escrowId].escrowByOwnerIdPos; delete escrowByEscrowId[escrowId]; for(uint t = 0; t < escrowByOwnerId[seller].length; t++) { if(escrowByOwnerId[seller][t].id == escrowId) { delete escrowByOwnerId[seller][t]; } } //escrowByOwnerId[seller].splice //ownerEscrowsCounter[seller] = getEscrowCountByAssetIdArray(seller) - 1; uint256[] memory assetIds = assetIdByEscrowId[escrowId]; for(uint i = 0; i < assetIds.length; i++) { for(uint j = 0; j < allOwnerParcelsOnEscrow[seller].length; j++) { if(assetIds[i] == allOwnerParcelsOnEscrow[seller][j]) { delete allOwnerParcelsOnEscrow[seller][j]; } } } emit EscrowCancelled(escrowId, seller); } function removeEscrow(bytes32 escrowId) public whenNotPaused { address seller = escrowByEscrowId[escrowId].seller; require(seller == msg.sender || msg.sender == owner); //uint256 escrowOwnerPos = escrowByEscrowId[escrowId].escrowByOwnerIdPos; delete escrowByEscrowId[escrowId]; for(uint t = 0; t < escrowByOwnerId[seller].length; t++) { if(escrowByOwnerId[seller][t].id == escrowId) { delete escrowByOwnerId[seller][t]; } } //escrowByOwnerId[seller].splice //ownerEscrowsCounter[seller] = getEscrowCountByAssetIdArray(seller) - 1; uint256[] memory assetIds = assetIdByEscrowId[escrowId]; for(uint i = 0; i < assetIds.length; i++) { for(uint j = 0; j < allOwnerParcelsOnEscrow[seller].length; j++) { if(assetIds[i] == allOwnerParcelsOnEscrow[seller][j]) { delete allOwnerParcelsOnEscrow[seller][j]; } } } delete allEscrowIds; emit EscrowCancelled(escrowId, seller); } function acceptEscrow(bytes32 escrowId) public whenNotPaused { address seller = escrowByEscrowId[escrowId].seller; require(seller != msg.sender); require(seller != address(0)); address buyer = escrowByEscrowId[escrowId].buyer; bool isPublic = escrowByEscrowId[escrowId].publicE; if(!isPublic) { require(msg.sender == escrowByEscrowId[escrowId].buyer, "You are not authorized for this escrow."); } //need to add check that offer price is accepted uint256[] memory assetIds = assetIdByEscrowId[escrowId]; for(uint a = 0; a < assetIds.length; a++) { require(seller == nonFungibleRegistry.ownerOf(assetIds[a])); } uint escrowPrice = escrowByEscrowId[escrowId].price; if (publicationFeeInWei > 0) { if(!whitelistAddresses[msg.sender]) { acceptedToken.transferFrom( msg.sender, owner, publicationFeeInWei ); } if(!whitelistAddresses[seller]) { acceptedToken.transferFrom( seller, owner, publicationFeeInWei ); } } // Transfer sale amount to seller acceptedToken.transferFrom( msg.sender, seller, escrowPrice ); for(uint counter = 0; counter < assetIds.length; counter++) { uint256 tempId = assetIds[counter]; nonFungibleRegistry.safeTransferFrom( seller, msg.sender, tempId ); } for(uint t = 0; t < escrowByOwnerId[seller].length; t++) { if(escrowByOwnerId[seller][t].id == escrowId) { delete escrowByOwnerId[seller][t]; } } for(uint i = 0; i < assetIds.length; i++) { for(uint j = 0; j < allOwnerParcelsOnEscrow[seller].length; j++) { if(assetIds[i] == allOwnerParcelsOnEscrow[seller][j]) { delete allOwnerParcelsOnEscrow[seller][j]; } } } delete escrowByEscrowId[escrowId]; delete assetIdByEscrowId[escrowId]; emit EscrowSuccessful( escrowId, seller, escrowPrice, buyer ); } }
* @dev Modifier to make a function callable only when the contract is not paused./
modifier whenNotPaused() { require(!paused, "this contract is paused"); _; }
15,881,858
[ 1, 9829, 358, 1221, 279, 445, 4140, 1338, 1347, 326, 6835, 353, 486, 17781, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 9606, 1347, 1248, 28590, 1435, 288, 203, 565, 2583, 12, 5, 8774, 3668, 16, 315, 2211, 6835, 353, 17781, 8863, 203, 565, 389, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165Storage.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableMap.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../../utils/Utils.sol"; import "../../access/PermitControl.sol"; import "../../proxy/StubProxyRegistry.sol"; import "../../interfaces/ISuper721IMXLock.sol"; /** @title An ERC-721 item creation contract. @author Tim Clancy @author 0xthrpw @author Qazawat Zirak This contract represents the NFTs within a single collection. It allows for a designated collection owner address to manage the creation of NFTs within this collection. The collection owner grants approval to or removes approval from other addresses governing their ability to mint NFTs from this collection. This contract is forked from the inherited OpenZeppelin dependency, and uses ideas inherited from the Super721 reference implementation. August 4th, 2021. */ contract Super721IMX is PermitControl, ERC165Storage, IERC721 { using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; /// The public identifier for the right to set this contract's metadata URI. bytes32 public constant SET_URI = keccak256("SET_URI"); /// The public identifier for the right to set this contract's proxy registry. bytes32 public constant SET_PROXY_REGISTRY = keccak256("SET_PROXY_REGISTRY"); /// The public identifier for the right to configure item groups. bytes32 public constant CONFIGURE_GROUP = keccak256("CONFIGURE_GROUP"); /// The public identifier for the right to mint items. bytes32 public constant MINT = keccak256("MINT"); /// The public identifier for the right to burn items. bytes32 public constant BURN = keccak256("BURN"); /// The public identifier for the right to set item metadata. bytes32 public constant SET_METADATA = keccak256("SET_METADATA"); /// The public identifier for the right to lock the metadata URI. bytes32 public constant LOCK_URI = keccak256("LOCK_URI"); /// The public identifier for the right to lock an item's metadata. bytes32 public constant LOCK_ITEM_URI = keccak256("LOCK_ITEM_URI"); /// The public identifier for the right to disable item creation. bytes32 public constant LOCK_CREATION = keccak256("LOCK_CREATION"); /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /// @dev Supply the magic number for the required ERC-721 interface. /// @dev A mask for isolating an item's group ID. uint256 private constant GROUP_MASK = uint256(type(uint128).max) << 128; /// The public name of this contract. string public name; string public symbol; /** The ERC-721 URI for tracking item metadata, supporting {id} substitution. For example: https://token-cdn-domain/{id}.json. See the ERC-721 spec for more details: https://eips.ethereum.org/EIPS/eip-721#metadata. */ string public metadataUri; /// The URI for the storefront-level metadata of contract string public contractURI; /// A proxy registry address for supporting automatic delegated approval. address public proxyRegistryAddress; /// The address of the IMX core contract for L2 minting. address public imxCoreAddress; /// The address of the global lock for all 721IMX instances. address public super721IMXLock; /// @dev A mapping from each token ID to per-address balances. mapping (uint256 => mapping(address => uint256)) public balances; /// A mapping from each group ID to per-address balances. mapping (uint256 => mapping(address => uint256)) public groupBalances; /// A mapping from each address to a collection-wide balance. mapping(address => uint256) public totalBalances; // 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; /** @dev This is a mapping from each address to per-address operator approvals. Operators are those addresses that have been approved to transfer tokens on behalf of the approver. Transferring tokens includes the right to burn tokens. */ mapping (address => mapping(address => bool)) private operatorApprovals; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; /** This enumeration lists the various supply types that each item group may use. In general, the administrator of this collection or those permissioned to do so may move from a more-permissive supply type to a less-permissive. For example: an uncapped or flexible supply type may be converted to a capped supply type. A capped supply type may not be uncapped later, however. @param Capped There exists a fixed cap on the size of the item group. The cap is set by `supplyData`. @param Uncapped There is no cap on the size of the item group. The value of `supplyData` cannot be set below the current circulating supply but is otherwise ignored. @param Flexible There is a cap which can be raised or lowered (down to circulating supply) freely. The value of `supplyData` cannot be set below the current circulating supply and determines the cap. */ enum SupplyType { Capped, Uncapped, Flexible } /** This enumeration lists the various burn types that each item group may use. These are static once chosen. @param None The items in this group may not be burnt. The value of `burnData` is ignored. @param Burnable The items in this group may be burnt. The value of `burnData` is the maximum that may be burnt. @param Replenishable The items in this group, once burnt, may be reminted by the owner. The value of `burnData` is ignored. */ enum BurnType { None, Burnable, Replenishable } /** This struct is a source of mapping-free input to the `configureGroup` function. It defines the settings for a particular item group. @param name A name for the item group. @param supplyType The supply type for this group of items. @param supplyData An optional integer used by some `supplyType` values. @param burnType The type of burning permitted by this item group. @param burnData An optional integer used by some `burnType` values. */ struct ItemGroupInput { string name; SupplyType supplyType; uint256 supplyData; BurnType burnType; uint256 burnData; } /** This struct defines the settings for a particular item group and is tracked in storage. @param initialized Whether or not this `ItemGroup` has been initialized. @param name A name for the item group. @param supplyType The supply type for this group of items. @param supplyData An optional integer used by some `supplyType` values. @param burnType The type of burning permitted by this item group. @param burnData An optional integer used by some `burnType` values. @param circulatingSupply The number of individual items within this group in circulation. @param mintCount The number of times items in this group have been minted. @param burnCount The number of times items in this group have been burnt. */ struct ItemGroup { bool initialized; string name; SupplyType supplyType; uint256 supplyData; BurnType burnType; uint256 burnData; uint256 circulatingSupply; uint256 mintCount; uint256 burnCount; } /// A mapping of data for each item group. mapping (uint256 => ItemGroup) public itemGroups; /// A mapping of circulating supplies for each individual token. mapping (uint256 => uint256) public circulatingSupply; /// A mapping of the number of times each individual token has been minted. mapping (uint256 => uint256) public mintCount; /// A mapping of the number of times each individual token has been burnt. mapping (uint256 => uint256) public burnCount; /** A mapping of token ID to a boolean representing whether the item's metadata has been explicitly frozen via a call to `lockURI(string calldata _uri, uint256 _id)`. Do note that it is possible for an item's mapping here to be false while still having frozen metadata if the item collection as a whole has had its `uriLocked` value set to true. */ mapping (uint256 => bool) public metadataFrozen; /** A public mapping of optional on-chain metadata for each token ID. A token's on-chain metadata is unable to be changed if the item's metadata URI has been permanently fixed or if the collection's metadata URI as a whole has been frozen. */ mapping (uint256 => string) public blueprints; /// Whether or not the metadata URI has been locked to future changes. bool public uriLocked; /// Whether or not the metadata URI has been locked to future changes. bool public contractUriLocked; /// Whether or not the item collection has been locked to all further minting. bool public locked; /** An event that gets emitted when the metadata collection URI is changed. @param oldURI The old metadata URI. @param newURI The new metadata URI. */ event ChangeURI(string indexed oldURI, string indexed newURI); /** An event that gets emitted when the contract URI is changed. @param oldURI The old metadata URI. @param newURI The new metadata URI. */ event ChangeContractURI(string indexed oldURI, string indexed newURI); /** An event that gets emitted when the proxy registry address is changed. @param oldRegistry The old proxy registry address. @param newRegistry The new proxy registry address. */ event ChangeProxyRegistry(address indexed oldRegistry, address indexed newRegistry); /** An event that gets emitted when an item group is configured. @param manager The caller who configured the item group `_groupId`. @param groupId The groupId being configured. @param newGroup The new group configuration. */ event ItemGroupConfigured(address indexed manager, uint256 groupId, ItemGroupInput indexed newGroup); /** An event that gets emitted when the item collection is locked to further creation. @param locker The caller who locked the collection. */ event CollectionLocked(address indexed locker); /** An event that gets emitted when a token ID has its on-chain metadata changed. @param changer The caller who triggered the metadata change. @param id The ID of the token which had its metadata changed. @param oldMetadata The old metadata of the token. @param newMetadata The new metadata of the token. */ event MetadataChanged(address indexed changer, uint256 indexed id, string oldMetadata, string indexed newMetadata); /** An event that indicates we have set a permanent metadata URI for a token. @param _value The value of the permanent metadata URI. @param _id The token ID associated with the permanent metadata value. */ event PermanentURI(string _value, uint256 indexed _id); /** An event that indicates we have set a permanent contract URI. @param _value The value of the permanent contract URI. @param _id The token ID associated with the permanent contract value. */ event PermanentContractURI(string _value, uint256 indexed _id); /** A modifier which allows only the super-administrative owner or addresses with a specified valid right to perform a call on some specific item. Rights can be applied to the universal circumstance, the item-group-level circumstance, or to the circumstance of the item ID itself. @param _id The item ID on which we check for the validity of the specified `right`. @param _right The right to validate for the calling address. It must be non-expired and exist within the specified `_itemId`. */ modifier hasItemRight(uint256 _id, bytes32 _right) { uint256 groupId = (_id & GROUP_MASK) >> 128; if (_msgSender() == owner()) { _; } else if (hasRight(_msgSender(), UNIVERSAL, _right)) { _; } else if (hasRight(_msgSender(), bytes32(groupId), _right)) { _; } else if (hasRight(_msgSender(), bytes32(_id), _right)) { _; } else { revert("Ix01"); } } /** Construct a new ERC-721 item collection. @param _owner The address of the administrator governing this collection. @param _name The name to assign to this item collection contract. @param _metadataURI The metadata URI to perform later token ID substitution with. @param _contractURI The contract URI. @param _proxyRegistryAddress The address of a proxy registry contract. @param _imxCoreAddress The address of the IMX core contract for L2 minting. */ constructor(address _owner, string memory _name, string memory _symbol, string memory _metadataURI, string memory _contractURI, address _proxyRegistryAddress, address _imxCoreAddress, address _super721IMXLock) { // Do not perform a redundant ownership transfer if the deployer should // remain as the owner of the collection. if (_owner != owner()) { transferOwnership(_owner); } // Register 721 interfaces _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); // Continue initialization. name = _name; symbol = _symbol; metadataUri = _metadataURI; contractURI = _contractURI; proxyRegistryAddress = _proxyRegistryAddress; imxCoreAddress = _imxCoreAddress; super721IMXLock = _super721IMXLock; } /** */ function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get(tokenId, "Ix02"); } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "Ix03"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "Ix04" ); _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** Return a version number for this contract's interface. */ function version() external virtual pure override returns (uint256) { return 1; } /** Return the item collection's metadata URI. This implementation returns the same URI for all tokens within the collection and relies on client-side ID substitution per https://eips.ethereum.org/EIPS/eip-721#metadata. Per said specification, clients calling this function must replace the {id} substring with the actual token ID in hex, not prefixed by 0x, and padded to 64 characters in length. @return The metadata URI string of the item with ID `_itemId`. */ function tokenURI(uint256 id) external view returns (string memory) { if(bytes(metadataUri).length == 0){ return blueprints[id]; } return Utils.interpolate(metadataUri, id); } /** Allow the item collection owner or an approved manager to update the metadata URI of this collection. This implementation relies on a single URI for all items within the collection, and as such does not emit the standard URI event. Instead, we emit our own event to reflect changes in the URI. @param _uri The new URI to update to. */ function setURI(string calldata _uri) external virtual hasValidPermit(UNIVERSAL, SET_URI) { require(!uriLocked, "Ix05"); string memory oldURI = metadataUri; metadataUri = _uri; emit ChangeURI(oldURI, _uri); } /** Allow approved manager to update the contract URI. At the end of update, we emit our own event to reflect changes in the URI. @param _uri The new contract URI to update to. */ function setContractURI(string calldata _uri) external virtual hasValidPermit(UNIVERSAL, SET_URI) { require(!contractUriLocked, "Ix06"); string memory oldContractUri = contractURI; contractURI = _uri; emit ChangeContractURI(oldContractUri, _uri); } /** Allow the item collection owner or an approved manager to update the proxy registry address handling delegated approval. @param _proxyRegistryAddress The address of the new proxy registry to update to. */ function setProxyRegistry(address _proxyRegistryAddress) external virtual hasValidPermit(UNIVERSAL, SET_PROXY_REGISTRY) { address oldRegistry = proxyRegistryAddress; proxyRegistryAddress = _proxyRegistryAddress; emit ChangeProxyRegistry(oldRegistry, _proxyRegistryAddress); } /** Retrieve the balance of a particular token `_id` for a particular address `_owner`. @param _owner The owner to check for this token balance. @param _id The ID of the token to check for a balance. @return The amount of token `_id` owned by `_owner`. */ function balanceOfGroup(address _owner, uint256 _id) public view virtual returns (uint256) { require(_owner != address(0), "Ix07"); return balances[_id][_owner]; } function balanceOf(address _owner) public override view virtual returns (uint256) { require(_owner != address(0), "Ix08"); return totalBalances[_owner]; } /** Retrieve in a single call the balances of some mulitple particular token `_ids` held by corresponding `_owners`. @param _owners The owners to check for token balances. @param _ids The IDs of tokens to check for balances. @return the amount of each token owned by each owner. */ function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view virtual returns (uint256[] memory) { require(_owners.length == _ids.length, ""); // Populate and return an array of balances. uint256[] memory batchBalances = new uint256[](_owners.length); for (uint256 i = 0; i < _owners.length; ++i) { batchBalances[i] = balanceOfGroup(_owners[i], _ids[i]); } return batchBalances; } /** This function returns true if `_operator` is approved to transfer items owned by `_owner`. This approval check features an override to explicitly whitelist any addresses delegated in the proxy registry. @param _owner The owner of items to check for transfer ability. @param _operator The potential transferrer of `_owner`'s items. @return Whether `_operator` may transfer items owned by `_owner`. */ function isApprovedForAll(address _owner, address _operator) public override view virtual returns (bool) { StubProxyRegistry proxyRegistry = StubProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == _operator) { return true; } // We did not find an explicit whitelist in the proxy registry. return operatorApprovals[_owner][_operator]; } /** Enable or disable approval for a third party `_operator` address to manage (transfer or burn) all of the caller's tokens. @param _operator The address to grant management rights over all of the caller's tokens. @param _approved The status of the `_operator`'s approval for the caller. */ function setApprovalForAll(address _operator, bool _approved) external override virtual { require(_msgSender() != _operator, "Ix09"); operatorApprovals[_msgSender()][_operator] = _approved; emit ApprovalForAll(_msgSender(), _operator, _approved); } /** This private helper function converts a number into a single-element array. @param _element The element to convert to an array. @return The array containing the single `_element`. */ function _asSingletonArray(uint256 _element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = _element; return array; } /** An inheritable and configurable pre-transfer hook that can be overridden. It fires before any token transfer, including mints and burns. @param _operator The caller who triggers the token transfer. @param _from The address to transfer tokens from. @param _to The address to transfer tokens to. @param _ids The specific token IDs to transfer. @param _amounts The amounts of the specific `_ids` to transfer. @param _data Additional call data to send with this transfer. */ function _beforeTokenTransfer(address _operator, address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) internal virtual { } /** ERC-721 dictates that any contract which wishes to receive ERC-721 tokens must explicitly designate itself as such. This function checks for such designation to prevent undesirable token transfers. @param _operator The caller who triggers the token transfer. @param _from The address to transfer tokens from. @param _to The address to transfer tokens to. @param _id The specific token ID to transfer. @param _data Additional call data to send with this transfer. */ function _doSafeTransferAcceptanceCheck(address _operator, address _from, address _to, uint256 _id, bytes memory _data) private { if (_to.isContract()) { try IERC721Receiver(_to).onERC721Received(_operator, _from, _id, _data) returns (bytes4 response) { if (response != IERC721Receiver(_to).onERC721Received.selector) { revert("Ix09"); } } catch Error(string memory reason) { revert(reason); } catch { revert("Ix10"); } } } /** Transfer on behalf of a caller or one of their authorized token managers items from one address to another. @param _from The address to transfer tokens from. @param _to The address to transfer tokens to. @param _id The specific token ID to transfer. @param _data Additional call data to send with this transfer. */ /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { _safeTransferFrom(from, to, tokenId, bytes("")); } function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) public virtual override { _safeTransferFrom(from, to, tokenId, data); } function _safeTransferFrom(address _from, address _to, uint256 _id, bytes memory _data) internal virtual { require(_to != address(0), "Ix11"); require(_from == _msgSender() || isApprovedForAll(_from, _msgSender()), "Ix12"); // Validate transfer safety and send tokens away. address operator = _msgSender(); _beforeTokenTransfer(operator, _from, _to, _asSingletonArray(_id), _asSingletonArray(1), _data); // Retrieve the item's group ID. uint256 shiftedGroupId = (_id & GROUP_MASK); uint256 groupId = shiftedGroupId >> 128; // Update all specially-tracked group-specific balances. require(balances[_id][_from] >= 1, "Ix13"); balances[_id][_from] = balances[_id][_from] - 1; balances[_id][_to] = balances[_id][_to] + 1; groupBalances[groupId][_from] = groupBalances[groupId][_from] - 1; groupBalances[groupId][_to] = groupBalances[groupId][_to] + 1; totalBalances[_from] = totalBalances[_from] - 1; totalBalances[_to] = totalBalances[_to] + 1; _holderTokens[_from].remove(_id); _holderTokens[_to].add(_id); _tokenOwners.set(_id, _to); // Emit the transfer event and perform the safety check. emit Transfer(_from, _to, _id); _doSafeTransferAcceptanceCheck(operator, _from, _to, _id, _data); } /** Transfer on behalf of a caller or one of their authorized token managers items from one address to another. @param _from The address to transfer tokens from. @param _to The address to transfer tokens to. @param _ids The specific token IDs to transfer. @param _data Additional call data to send with this transfer. */ function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, bytes memory _data) external virtual { require(_to != address(0), "Ix14"); require(_from == _msgSender() || isApprovedForAll(_from, _msgSender()), "Ix15"); // Validate transfer and perform all batch token sends. _beforeTokenTransfer(_msgSender(), _from, _to, _ids, _asSingletonArray(1), _data); for (uint256 i = 0; i < _ids.length; ++i) { // Retrieve the item's group ID. uint256 groupId = (_ids[i] & GROUP_MASK) >> 128; // Update all specially-tracked group-specific balances. require(balances[_ids[i]][_from] >= 1, "Ix16"); balances[_ids[i]][_from] = balances[_ids[i]][_from] - 1; balances[_ids[i]][_to] = balances[_ids[i]][_to] + 1; groupBalances[groupId][_from] = groupBalances[groupId][_from] - 1; groupBalances[groupId][_to] = groupBalances[groupId][_to] + 1; totalBalances[_from] = totalBalances[_from] - 1; totalBalances[_to] = totalBalances[_to] + 1; // Emit the transfer event and perform the safety check. emit Transfer(_from, _to, _ids[i]); _doSafeTransferAcceptanceCheck(_msgSender(), _from, _to, _ids[i], _data); } } /** Create a new NFT item group or configure an existing one. NFTs within a group share a group ID in the upper 128-bits of their full item ID. Within a group NFTs can be distinguished for the purposes of serializing issue numbers. @param _groupId The ID of the item group to create or configure. @param _data The `ItemGroup` data input. */ function configureGroup(uint256 _groupId, ItemGroupInput memory _data) external virtual hasItemRight(_groupId, CONFIGURE_GROUP) { require(_groupId != 0, "Ix17"); // If the collection is not locked, we may add a new item group. if (!itemGroups[_groupId].initialized) { require(!locked, "Ix18"); itemGroups[_groupId] = ItemGroup({ initialized: true, name: _data.name, supplyType: _data.supplyType, supplyData: _data.supplyData, burnType: _data.burnType, burnData: _data.burnData, circulatingSupply: 0, mintCount: 0, burnCount: 0 }); // Edit an existing item group. The name may always be updated. } else { itemGroups[_groupId].name = _data.name; // A capped supply type may not change. // It may also not have its cap increased. if (itemGroups[_groupId].supplyType == SupplyType.Capped) { require(_data.supplyType == SupplyType.Capped, "Ix19"); require(_data.supplyData <= itemGroups[_groupId].supplyData, "Ix20"); // The flexible and uncapped types may freely change. } else { itemGroups[_groupId].supplyType = _data.supplyType; } // Item supply data may not be reduced below the circulating supply. require(_data.supplyData >= itemGroups[_groupId].circulatingSupply, "Ix21"); itemGroups[_groupId].supplyData = _data.supplyData; // do we want burnType to be updateable? } // Emit the configuration event. emit ItemGroupConfigured(_msgSender(), _groupId, _data); } /** This is a private helper function to replace the `hasItemRight` modifier that we use on some functions in order to inline this check during batch minting and burning. @param _id The ID of the item to check for the given `_right` on. @param _right The right that the caller is trying to exercise on `_id`. @return Whether or not the caller has a valid right on this item. */ function _hasItemRight(uint256 _id, bytes32 _right) private view returns (bool) { uint256 groupId = (_id & GROUP_MASK) >> 128; if (_msgSender() == owner()) { return true; } else if (hasRight(_msgSender(), UNIVERSAL, _right)) { return true; } else if (hasRight(_msgSender(), bytes32(groupId), _right)) { return true; } else if (hasRight(_msgSender(), bytes32(_id), _right)) { return true; } else { return false; } } /** This is a private helper function to verify, according to all of our various minting and burning rules, whether it would be valid to mint a particular item `_id`. @param _id The ID of the item to check for minting validity. @return The ID of the item that should be minted. */ function _mintChecker(uint256 _id) private view returns (uint256) { // Retrieve the item's group ID. uint256 shiftedGroupId = (_id & GROUP_MASK); uint256 groupId = shiftedGroupId >> 128; // console.logUint(groupId); require(itemGroups[groupId].initialized, "Ix22"); // If false, owned by address (or NULL_ADDRESS i.e, was burnable) // If true, never minted, (or was removed i.e, was replenishable) require(!_tokenOwners.contains(_id), "Ix23"); // If we can replenish burnt items, then only our currently-circulating // supply matters. Otherwise, historic mints are what determine the cap. uint256 currentGroupSupply = itemGroups[groupId].mintCount; uint256 currentItemSupply = mintCount[_id]; if (itemGroups[groupId].burnType == BurnType.Replenishable) { currentGroupSupply = itemGroups[groupId].circulatingSupply; currentItemSupply = circulatingSupply[_id]; } // If we are subject to a cap on group size, ensure we don't exceed it. if (itemGroups[groupId].supplyType != SupplyType.Uncapped) { require(currentGroupSupply + 1 <= itemGroups[groupId].supplyData, "Ix24"); } return _id; } /** Mint a batch of tokens into existence and send them to the `_recipient` address. In order to mint an item, its item group must first have been created. Minting an item must obey both the fungibility and size cap of its group. @param _recipient The address to receive all NFTs within the newly-minted group. @param _ids The item IDs for the new items to create. @param _data Any associated data to use on items minted in this transaction. */ function mintBatch(address _recipient, uint256[] memory _ids, bytes memory _data) public virtual { require(_recipient != address(0), "Super721::mintBatch: mint to the zero address"); // Validate and perform the mint. address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), _recipient, _ids, _asSingletonArray(1), _data); // Loop through each of the batched IDs to update storage of special // balances and circulation balances. for (uint256 i = 0; i < _ids.length; i++) { require(_hasItemRight(_ids[i], MINT), "Ix25"); // Retrieve the group ID from the given item `_id` and check mint. uint256 shiftedGroupId = (_ids[i] & GROUP_MASK); uint256 groupId = shiftedGroupId >> 128; uint256 mintedItemId = _mintChecker(_ids[i]); // Update storage of special balances and circulating values. balances[mintedItemId][_recipient] = balances[mintedItemId][_recipient] + 1; groupBalances[groupId][_recipient] = groupBalances[groupId][_recipient] + 1; totalBalances[_recipient] = totalBalances[_recipient] + 1; mintCount[mintedItemId] = mintCount[mintedItemId] + 1; circulatingSupply[mintedItemId] = circulatingSupply[mintedItemId] + 1; itemGroups[groupId].mintCount = itemGroups[groupId].mintCount + 1; itemGroups[groupId].circulatingSupply = itemGroups[groupId].circulatingSupply + 1; //_holderTokens[address(0)].remove(_ids[i]); _holderTokens[_recipient].add(_ids[i]); _tokenOwners.set(_ids[i], _recipient); // Emit event and handle the safety check. emit Transfer(address(0), _recipient, _ids[i]); _doSafeTransferAcceptanceCheck(operator, address(0), _recipient, _ids[i], _data); } } /** The special, IMX-privileged minting function for centralized L2 support. */ function mintFor(address _to, uint256 quantity, bytes calldata _blueprint) external { // check require(_msgSender() == imxCoreAddress, "Ix26"); require(quantity == 1, "Ix27"); require(!ISuper721IMXLock(super721IMXLock).mintForLocked(), "Ix28"); // read data (uint256 id, bytes memory metadata_) = Utils.split(_blueprint); uint256[] memory ids = _asSingletonArray(id); // effects if(metadata_.length > 0){ blueprints[id] = string(metadata_); } mintBatch(_to, ids, _blueprint); } /** This is a private helper function to verify, according to all of our various minting and burning rules, whether it would be valid to burn some `_amount` of a particular item `_id`. @param _id The ID of the item to check for burning validity. @return The ID of the item that should have `_amount` burnt for it. */ function _burnChecker(uint256 _id) private view returns (uint256) { // Retrieve the item's group ID. uint256 shiftedGroupId = (_id & GROUP_MASK); uint256 groupId = shiftedGroupId >> 128; require(itemGroups[groupId].initialized, "Ix29"); // If the item group is non-burnable, then revert. if (itemGroups[groupId].burnType == BurnType.None) { revert("Ix30"); } // If we can burn items, then we must verify that we do not exceed the cap. else if (itemGroups[groupId].burnType == BurnType.Burnable) { require(itemGroups[groupId].burnCount + 1 <= itemGroups[groupId].burnData, "Ix31"); } // If the item is replenishable, then ignore checks uint256 burntItemId = _id; return burntItemId; } /** This function allows an address to destroy some of its items. @param _burner The address whose item is burning. @param _id The item ID to burn. @param _amount The amount of the corresponding item ID to burn. */ // function burn(address _burner, uint256 _id, uint256 _amount) // external virtual hasItemRight(_id, BURN) { // require(_burner != address(0), // "Super721::burn: burn from the zero address"); // // // Retrieve the group ID from the given item `_id` and check burn validity. // uint256 shiftedGroupId = (_id & GROUP_MASK); // uint256 groupId = shiftedGroupId >> 128; // uint256 burntItemId = _burnChecker(_id, _amount); // // // Validate and perform the burn. // address operator = _msgSender(); // _beforeTokenTransfer(operator, _burner, address(0), // _asSingletonArray(burntItemId), _asSingletonArray(_amount), ""); // // // Update storage of special balances and circulating values. // balances[burntItemId][_burner] = balances[burntItemId][_burner] // .sub(_amount, // "Super721::burn: burn amount exceeds balance"); // groupBalances[groupId][_burner] = groupBalances[groupId][_burner] // .sub(_amount); // totalBalances[_burner] = totalBalances[_burner].sub(_amount); // burnCount[burntItemId] = burnCount[burntItemId].add(_amount); // circulatingSupply[burntItemId] = circulatingSupply[burntItemId] // .sub(_amount); // itemGroups[groupId].burnCount = itemGroups[groupId].burnCount.add(_amount); // itemGroups[groupId].circulatingSupply = // itemGroups[groupId].circulatingSupply.sub(_amount); // // // Emit the burn event. // emit Transfer(operator, address(0), _id); // } /** This function allows an address to destroy multiple different items in a single call. @param _burner The address whose items are burning. @param _ids The item IDs to burn. */ function burnBatch(address _burner, uint256[] memory _ids) external virtual { require(_burner != address(0), "Super721::burnBatch: burn from the zero address"); // Validate and perform the burn. address operator = _msgSender(); _beforeTokenTransfer(operator, _burner, address(0), _ids, _asSingletonArray(1), ""); // Loop through each of the batched IDs to update storage of special // balances and circulation balances. for (uint i = 0; i < _ids.length; i++) { require(_hasItemRight(_ids[i], BURN), "Ix32"); // Retrieve the group ID from the given item `_id` and check burn. uint256 shiftedGroupId = (_ids[i] & GROUP_MASK); uint256 groupId = shiftedGroupId >> 128; uint256 burntItemId = _burnChecker(_ids[i]); // Update storage of special balances and circulating values. require(balances[burntItemId][_burner] >= 1, "Ix33"); balances[burntItemId][_burner] = balances[burntItemId][_burner] - 1; groupBalances[groupId][_burner] = groupBalances[groupId][_burner] - 1; totalBalances[_burner] = totalBalances[_burner] - 1; burnCount[burntItemId] = burnCount[burntItemId] + 1; circulatingSupply[burntItemId] = circulatingSupply[burntItemId] - 1; itemGroups[groupId].burnCount = itemGroups[groupId].burnCount + 1; itemGroups[groupId].circulatingSupply = itemGroups[groupId].circulatingSupply - 1; _holderTokens[_burner].remove(_ids[i]); _holderTokens[address(0)].add(_ids[i]); // If burnType is None, burnChecker will revert that if(itemGroups[groupId].burnType == BurnType.Burnable) _tokenOwners.set(_ids[i], address(0)); else _tokenOwners.remove(_ids[i]); // Emit the burn event. emit Transfer(operator, address(0), _ids[i]); } } function metadata(uint256 id) external view returns(string memory) { return blueprints[id]; } /** Set the on-chain metadata attached to a specific token ID so long as the collection as a whole or the token specifically has not had metadata editing frozen. @param _id The ID of the token to set the `_metadata` for. @param _metadata The metadata string to store on-chain. */ function setMetadata(uint256 _id, string memory _metadata) external hasItemRight(_id, SET_METADATA) { uint groupId = _id >> 128; require(!uriLocked && !metadataFrozen[_id] && !metadataFrozen[groupId]); string memory oldMetadata = blueprints[_id]; blueprints[_id] = _metadata; emit MetadataChanged(_msgSender(), _id, oldMetadata, _metadata); } /** Allow the item collection owner or an associated manager to forever lock the metadata URI on the entire collection to future changes. */ function lockURI() external hasValidPermit(UNIVERSAL, LOCK_URI) { uriLocked = true; emit PermanentURI(metadataUri, 2 ** 256 - 1); } /** Allow the associated manager to forever lock the contract URI to future changes */ function lockContractUri() external hasValidPermit(UNIVERSAL, LOCK_URI) { contractUriLocked = true; emit PermanentContractURI(contractURI, 2 ** 256 - 1); } /** Allow the item collection owner or an associated manager to forever lock the metadata URI on an item to future changes. @param _uri The value of the URI to lock for `_id`. @param _id The token ID to lock a metadata URI value into. */ function lockItemURI(string calldata _uri, uint256 _id) external hasItemRight(_id, LOCK_ITEM_URI) { metadataFrozen[_id] = true; emit PermanentURI(_uri, _id); } /** Allow the item collection owner or an associated manager to forever lock the metadata URI on a group of items to future changes. @param _uri The value of the URI to lock for `groupId`. @param groupId The group ID to lock a metadata URI value into. */ function lockGroupURI(string calldata _uri, uint256 groupId) external hasItemRight(groupId, LOCK_ITEM_URI) { metadataFrozen[groupId] = true; emit PermanentURI(_uri, groupId); } /** Allow the item collection owner or an associated manager to forever lock this contract to further item minting. */ function lock() external virtual hasValidPermit(UNIVERSAL, LOCK_CREATION) { locked = true; emit CollectionLocked(_msgSender()); } function getApproved(uint256 tokenId) public view override returns (address) { require(_tokenOwners.contains(tokenId), "Ix34"); return _tokenApprovals[tokenId]; } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_tokenOwners.contains(tokenId), "Ix35"); address owner = ownerOf(tokenId); return (spender == owner || _tokenApprovals[tokenId] == spender || isApprovedForAll(owner, spender)); } /** * @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), "Ix36"); safeTransferFrom(from, to, tokenId); // // require(ownerOf(tokenId) == from, "Super721::transferForm: transfer of token that is not own"); // require(to != address(0), "Super721::transferForm: transfer to the zero address"); // // _beforeTokenTransfer(_msgSender(), from, to, _asSingletonArray(tokenId), _asSingletonArray(1), ""); // // // Clear approvals from the previous owner // //_approve(address(0), tokenId); // _tokenApprovals[tokenId] = address(0); // emit Approval(ownerOf(tokenId), address(0), tokenId); // // _holderTokens[from].remove(tokenId); // _holderTokens[to].add(tokenId); // // _tokenOwners.set(tokenId, to); // // emit Transfer(from, to, tokenId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view 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 returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } } // 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 "../../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; import "./ERC165.sol"; /** * @dev Storage based implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165Storage is ERC165 { /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return super.supportsInterface(interfaceId) || _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 Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./EnumerableSet.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; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { using EnumerableSet for EnumerableSet.Bytes32Set; // 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 Map { // Storage of keys EnumerableSet.Bytes32Set _keys; mapping(bytes32 => bytes32) _values; } /** * @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) { map._values[key] = value; return map._keys.add(key); } /** * @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) { delete map._values[key]; return map._keys.remove(key); } /** * @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._keys.contains(key); } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._keys.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) { bytes32 key = map._keys.at(index); return (key, map._values[key]); } /** * @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) { bytes32 value = map._values[key]; if (value == bytes32(0)) { return (_contains(map, key), bytes32(0)); } else { return (true, value); } } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key"); return value; } /** * @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) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), errorMessage); return value; } // 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 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.8; library Utils { // this is struct for aligning function memory struct Slice { uint length; uint pointer; } function Concat(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; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (uint i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (uint i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (uint i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (uint i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function Concat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory) { return Concat(_a, _b, _c, _d, ""); } function Concat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory) { return Concat(_a, _b, _c, "", ""); } function Concat(string memory _a, string memory _b) internal pure returns (string memory) { return Concat(_a, _b, "", "", ""); } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len; j = _i; while (j != 0) { bstr[--k] = bytes1(uint8(48 + j % 10)); j /= 10; } return string(bstr); } function copyToMemory(uint _destination, uint _source, uint _length) private pure { // Copy word-length chunks while possible for(_length ; _length >= 32; _length -= 32) { assembly { mstore(_destination, mload(_source)) } _destination += 32; _source += 32; } // Copy remaining bytes if(_length >0){ uint mask = 256 ** (32 - _length) - 1; assembly { let source := and(mload(_source), not(mask)) let destination := and(mload(_destination), mask) mstore(_destination, or(destination, source)) } } } // make struct slice out of string function toSlice(string memory input) internal pure returns (Slice memory) { uint ptr; assembly { ptr := add(input, 0x20) } return Slice(bytes(input).length, ptr); } function findPointer(uint inputLength, uint inputPointer, uint toSearchLength, uint toSearchPointer) private pure returns (uint) { uint pointer = inputPointer; if (toSearchLength <= inputLength) { if (toSearchLength <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - toSearchLength)) - 1)); bytes32 toSearchdata; assembly { toSearchdata := and(mload(toSearchPointer), mask) } uint end = inputPointer + inputLength - toSearchLength; bytes32 data; assembly { data := and(mload(pointer), mask) } while (data != toSearchdata) { if (pointer >= end) return inputPointer + inputLength; pointer++; assembly { data := and(mload(pointer), mask) } } return pointer; } else { // For long toSearchs, use hashing bytes32 hash; assembly { hash := keccak256(toSearchPointer, toSearchLength) } for (uint i = 0; i <= inputLength - toSearchLength; i++) { bytes32 testHash; assembly { testHash := keccak256(pointer, toSearchLength) } if (hash == testHash) return pointer; pointer += 1; } } } return inputPointer + inputLength; } function afterMatch(Slice memory input, Slice memory toSearch) internal pure returns (Slice memory) { uint pointer = findPointer(input.length, input.pointer, toSearch.length, toSearch.pointer); input.length -= pointer - input.pointer + 1; // escape void space input.pointer = pointer +1; // escape token return input; } function beforeMatch(Slice memory input, Slice memory toSearch) internal pure returns (Slice memory token) { beforeMatch(input, toSearch, token); } function beforeMatch(Slice memory input, Slice memory toSearch, Slice memory token) internal pure returns (Slice memory) { uint pointer = findPointer(input.length, input.pointer, toSearch.length, toSearch.pointer); token.pointer = input.pointer; token.length = pointer - input.pointer; if (pointer == input.pointer + input.length) { // Not found input.length = 0; } else { input.length -= token.length + toSearch.length; input.pointer = pointer + toSearch.length; } return token; } function toString(Slice memory input) internal pure returns (string memory) { string memory result = new string(input.length); uint resultPointer; assembly { resultPointer := add(result, 32) } copyToMemory(resultPointer, input.pointer, input.length); return result; } function split(bytes calldata blob) internal pure returns (uint256, bytes memory) { int256 index = indexOf(blob, ":", 0); require(index >= 0, "Separator must exist"); // Trim the { and } from the parameters uint256 tokenID = toUint(blob[1:uint256(index) - 1]); uint256 blueprintLength = blob.length - uint256(index) - 3; if (blueprintLength == 0) { return (tokenID, bytes("")); } bytes calldata blueprint = blob[uint256(index) + 2:blob.length - 1]; return (tokenID, blueprint); } /** * Index Of * * Locates and returns the position of a character within a string starting * from a defined offset * * @param _base When being used for a data type this is the extended object * otherwise this is the string acting as the haystack to be * searched * @param _value The needle to search for, at present this is currently * limited to one character * @param _offset The starting point to start searching from which can start * from 0, but must not exceed the length of the string * @return int The position of the needle starting from 0 and returning -1 * in the case of no matches found */ function indexOf( bytes memory _base, string memory _value, uint256 _offset ) internal pure returns (int256) { bytes memory _valueBytes = bytes(_value); assert(_valueBytes.length == 1); for (uint256 i = _offset; i < _base.length; i++) { if (_base[i] == _valueBytes[0]) { return int256(i); } } return -1; } function toUint(bytes memory b) internal pure returns (uint256) { uint256 result = 0; for (uint256 i = 0; i < b.length; i++) { uint256 val = uint256(uint8(b[i])); if (val >= 48 && val <= 57) { result = result * 10 + (val - 48); } } return result; } function interpolate(string memory source, uint value) internal pure returns (string memory result){ Slice memory slice1 = toSlice(source); Slice memory slice2 = toSlice(source); string memory tokenFirst = "{"; string memory tokenLast = "}"; Slice memory firstSlice = toSlice(tokenFirst); Slice memory secondSlice = toSlice(tokenLast); firstSlice = beforeMatch(slice1, firstSlice); secondSlice = afterMatch(slice2, secondSlice); string memory first = toString(firstSlice); string memory second = toString(secondSlice); result = Concat(first, uint2str(value), second); return result; } } /** * @title ArrayUtils * @author Project Wyvern Developers */ library ArrayUtils { /** * Replace bytes in an array with bytes in another array, guarded by a bitmask * Efficiency of this function is a bit unpredictable because of the EVM's word-specific model (arrays under 32 bytes will be slower) * * @dev Mask must be the size of the byte array. A nonzero byte means the byte array can be changed. * @param array The original array * @param desired The target array * @param mask The mask specifying which bits can be changed */ function guardedArrayReplace(bytes memory array, bytes memory desired, bytes memory mask) internal pure { require(array.length == desired.length, "Ux02"); require(array.length == mask.length, "Ux03"); uint words = array.length / 0x20; uint index = words * 0x20; assert(index / 0x20 == words); uint i; for (i = 0; i < words; i++) { /* Conceptually: array[i] = (!mask[i] && array[i]) || (mask[i] && desired[i]), bitwise in word chunks. */ assembly { let commonIndex := mul(0x20, add(1, i)) let maskValue := mload(add(mask, commonIndex)) mstore(add(array, commonIndex), or(and(not(maskValue), mload(add(array, commonIndex))), and(maskValue, mload(add(desired, commonIndex))))) } } /* Deal with the last section of the byte array. */ if (words > 0) { /* This overlaps with bytes already set but is still more efficient than iterating through each of the remaining bytes individually. */ i = words; assembly { let commonIndex := mul(0x20, add(1, i)) let maskValue := mload(add(mask, commonIndex)) mstore(add(array, commonIndex), or(and(not(maskValue), mload(add(array, commonIndex))), and(maskValue, mload(add(desired, commonIndex))))) } } else { /* If the byte array is shorter than a word, we must unfortunately do the whole thing bytewise. (bounds checks could still probably be optimized away in assembly, but this is a rare case) */ for (i = index; i < array.length; i++) { array[i] = ((mask[i] ^ 0xff) & array[i]) | (mask[i] & desired[i]); } } } /** * Test if two arrays are equal * Source: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol * * @dev Arrays must be of equal length, otherwise will return false * @param a First array * @param b Second array * @return Whether or not all bytes in the arrays are equal */ function arrayEq(bytes memory a, bytes memory b) internal pure returns (bool) { bool success = true; assembly { let length := mload(a) // if lengths don't match the arrays are not equal switch eq(length, mload(b)) case 1 { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 let mc := add(a, 0x20) let end := add(mc, length) for { let cc := add(b, 0x20) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { // if any of these checks fails then arrays are not equal if iszero(eq(mload(mc), mload(cc))) { // unsuccess: success := 0 cb := 0 } } } default { // unsuccess: success := 0 } } return success; } /** * Unsafe write byte array into a memory location * * @param index Memory location * @param source Byte array to write * @return End memory index */ function unsafeWriteBytes(uint index, bytes memory source) internal pure returns (uint) { if (source.length > 0) { assembly { let length := mload(source) let end := add(source, add(0x20, length)) let arrIndex := add(source, 0x20) let tempIndex := index for { } eq(lt(arrIndex, end), 1) { arrIndex := add(arrIndex, 0x20) tempIndex := add(tempIndex, 0x20) } { mstore(tempIndex, mload(arrIndex)) } index := add(index, length) } } return index; } /** * Unsafe write address array into a memory location * * @param index Memory location * @param source Address array to write * @return End memory index */ function unsafeWriteUintArray(uint index, uint[] memory source) internal pure returns (uint) { for (uint i = 0; i < source.length; i++){ uint conv = uint(uint160(source[i])) << 0x60; assembly { mstore(index, conv) index := add(index, 0x14) } } return index; } /** * Unsafe write address nested array into a memory location * * @param index Memory location * @param source Address nested array to write * @return End memory index */ function unsafeWriteAddressMap(uint index, address[][] memory source) internal pure returns (uint) { for (uint i = 0; i < source.length; i++){ for (uint j = 0; j < source[i].length; j++){ uint conv = uint(uint160(source[i][j])) << 0x60; assembly { mstore(index, conv) index := add(index, 0x14) } } } return index; } /** * Unsafe write address into a memory location * * @param index Memory location * @param source Address to write * @return End memory index */ function unsafeWriteAddress(uint index, address source) internal pure returns (uint) { uint conv = uint(uint160(source)) << 0x60; assembly { mstore(index, conv) index := add(index, 0x14) } return index; } /** * Unsafe write uint into a memory location * * @param index Memory location * @param source uint to write * @return End memory index */ function unsafeWriteUint(uint index, uint source) internal pure returns (uint) { assembly { mstore(index, source) index := add(index, 0x20) } return index; } /** * Unsafe write uint8 into a memory location * * @param index Memory location * @param source uint8 to write * @return End memory index */ function unsafeWriteUint8(uint index, uint8 source) internal pure returns (uint) { assembly { mstore8(index, source) index := add(index, 0x1) } return index; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** @title An advanced permission-management contract. @author Tim Clancy This contract allows for a contract owner to delegate specific rights to external addresses. Additionally, these rights can be gated behind certain sets of circumstances and granted expiration times. This is useful for some more finely-grained access control in contracts. The owner of this contract is always a fully-permissioned super-administrator. August 23rd, 2021. */ abstract contract PermitControl is Ownable { using Address for address; /// A special reserved constant for representing no rights. bytes32 public constant ZERO_RIGHT = hex"00000000000000000000000000000000"; /// A special constant specifying the unique, universal-rights circumstance. bytes32 public constant UNIVERSAL = hex"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"; /* A special constant specifying the unique manager right. This right allows an address to freely-manipulate the `managedRight` mapping. **/ bytes32 public constant MANAGER = hex"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"; /** A mapping of per-address permissions to the circumstances, represented as an additional layer of generic bytes32 data, under which the addresses have various permits. A permit in this sense is represented by a per-circumstance mapping which couples some right, represented as a generic bytes32, to an expiration time wherein the right may no longer be exercised. An expiration time of 0 indicates that there is in fact no permit for the specified address to exercise the specified right under the specified circumstance. @dev Universal rights MUST be stored under the 0xFFFFFFFFFFFFFFFFFFFFFFFF... max-integer circumstance. Perpetual rights may be given an expiry time of max-integer. */ mapping( address => mapping( bytes32 => mapping( bytes32 => uint256 ))) public permissions; /** An additional mapping of managed rights to manager rights. This mapping represents the administrator relationship that various rights have with one another. An address with a manager right may freely set permits for that manager right's managed rights. Each right may be managed by only one other right. */ mapping( bytes32 => bytes32 ) public managerRight; /** An event emitted when an address has a permit updated. This event captures, through its various parameter combinations, the cases of granting a permit, updating the expiration time of a permit, or revoking a permit. @param updator The address which has updated the permit. @param updatee The address whose permit was updated. @param circumstance The circumstance wherein the permit was updated. @param role The role which was updated. @param expirationTime The time when the permit expires. */ event PermitUpdated( address indexed updator, address indexed updatee, bytes32 circumstance, bytes32 indexed role, uint256 expirationTime ); /** An event emitted when a management relationship in `managerRight` is updated. This event captures adding and revoking management permissions via observing the update history of the `managerRight` value. @param manager The address of the manager performing this update. @param managedRight The right which had its manager updated. @param managerRight The new manager right which was updated to. */ event ManagementUpdated( address indexed manager, bytes32 indexed managedRight, bytes32 indexed managerRight ); /** A modifier which allows only the super-administrative owner or addresses with a specified valid right to perform a call. @param _circumstance The circumstance under which to check for the validity of the specified `right`. @param _right The right to validate for the calling address. It must be non-expired and exist within the specified `_circumstance`. */ modifier hasValidPermit( bytes32 _circumstance, bytes32 _right ) { require(_msgSender() == owner() || hasRight(_msgSender(), _circumstance, _right), "P1"); _; } /** Return a version number for this contract's interface. */ function version() external virtual pure returns (uint256) { return 1; } /** Determine whether or not an address has some rights under the given circumstance, and if they do have the right, until when. @param _address The address to check for the specified `_right`. @param _circumstance The circumstance to check the specified `_right` for. @param _right The right to check for validity. @return The timestamp in seconds when the `_right` expires. If the timestamp is zero, we can assume that the user never had the right. */ function hasRightUntil( address _address, bytes32 _circumstance, bytes32 _right ) public view returns (uint256) { return permissions[_address][_circumstance][_right]; } /** Determine whether or not an address has some rights under the given circumstance, @param _address The address to check for the specified `_right`. @param _circumstance The circumstance to check the specified `_right` for. @param _right The right to check for validity. @return true or false, whether user has rights and time is valid. */ function hasRight( address _address, bytes32 _circumstance, bytes32 _right ) public view returns (bool) { return permissions[_address][_circumstance][_right] > block.timestamp; } /** Set the permit to a specific address under some circumstances. A permit may only be set by the super-administrative contract owner or an address holding some delegated management permit. @param _address The address to assign the specified `_right` to. @param _circumstance The circumstance in which the `_right` is valid. @param _right The specific right to assign. @param _expirationTime The time when the `_right` expires for the provided `_circumstance`. */ function setPermit( address _address, bytes32 _circumstance, bytes32 _right, uint256 _expirationTime ) public virtual hasValidPermit(UNIVERSAL, managerRight[_right]) { require(_right != ZERO_RIGHT, "P2"); permissions[_address][_circumstance][_right] = _expirationTime; emit PermitUpdated(_msgSender(), _address, _circumstance, _right, _expirationTime); } /** Set the `_managerRight` whose `UNIVERSAL` holders may freely manage the specified `_managedRight`. @param _managedRight The right which is to have its manager set to `_managerRight`. @param _managerRight The right whose `UNIVERSAL` holders may manage `_managedRight`. */ function setManagerRight( bytes32 _managedRight, bytes32 _managerRight ) external virtual hasValidPermit(UNIVERSAL, MANAGER) { require(_managedRight != ZERO_RIGHT, "P3"); managerRight[_managedRight] = _managerRight; emit ManagementUpdated(_msgSender(), _managedRight, _managerRight); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; /** @title A proxy registry contract. @author Protinam, Project Wyvern @author Tim Clancy This contract was originally developed by Project Wyvern (https://github.com/ProjectWyvern/) where it currently enjoys great success as a component of the primary exchange contract for OpenSea. It has been modified to support a more modern version of Solidity with associated best practices. The documentation has also been improved to provide more clarity. */ abstract contract StubProxyRegistry { /** This mapping relates an addresses to its own personal `OwnableDelegateProxy` which allow it to proxy functionality to the various callers contained in `authorizedCallers`. */ mapping(address => address) public proxies; } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.8; interface ISuper721IMXLock { function mintForLocked() external view returns(bool); function toggleMintFor() external; } // 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; 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; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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; } }
* Unsafe write uint into a memory location @param index Memory location @param source uint to write @return End memory index/
{ function unsafeWriteUint(uint index, uint source) internal pure returns (uint) assembly { mstore(index, source) index := add(index, 0x20) } return index; }
13,776,088
[ 1, 23912, 1045, 2254, 1368, 279, 3778, 2117, 225, 770, 9251, 2117, 225, 1084, 2254, 358, 1045, 327, 4403, 3778, 770, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 288, 203, 565, 445, 7127, 3067, 5487, 12, 11890, 770, 16, 2254, 1084, 13, 203, 3639, 2713, 16618, 203, 3639, 1135, 261, 11890, 13, 203, 3639, 19931, 288, 203, 5411, 312, 2233, 12, 1615, 16, 1084, 13, 203, 5411, 770, 519, 527, 12, 1615, 16, 374, 92, 3462, 13, 203, 3639, 289, 203, 3639, 327, 770, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0x8C8B5De03d4dAD48fe2bAD13DD304F1E6b63a744/sources/StratFlat.sol
we need to free up profit plus _debtOutstanding.If _debtOutstanding is more than we can free we get as much as possible should be no way for there to be a loss. we hope...no position to harvest or profit to reportwe can only return looseAssetswe need to add outstanding to our profitdont need to do logic if there is nothiing to freewithdraw what we can withdrawif we dont have enough money adjust _debtOutstanding and only change profit if neededwithdraw what we can withdrawif we dont have enough money adjust _debtOutstanding and only change profit if needed
function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { _profit = 0; _debtPayment = _debtOutstanding; uint256 lentAssets = lentTotalAssets(); uint256 looseAssets = want.balanceOf(address(this)); uint256 ironBankDebt = ironBankOutstandingDebtStored(); uint256 total = looseAssets.add(lentAssets); if(ironBankDebt < total){ total = total.sub(ironBankDebt); total = 0; } if (lentAssets == 0) { if (_debtPayment > looseAssets) { _debtPayment = looseAssets; } return (_profit, _loss, _debtPayment); } uint256 debt = vault.strategies(address(this)).totalDebt; if (total > debt) { _profit = total - debt; uint256 amountToFree = _profit.add(_debtPayment); if (amountToFree > 0 && looseAssets < amountToFree) { _withdrawSome(amountToFree.sub(looseAssets)); uint256 newLoose = want.balanceOf(address(this)); if (newLoose < amountToFree) { if (_profit > newLoose) { _profit = newLoose; _debtPayment = 0; _debtPayment = Math.min(newLoose - _profit, _debtPayment); } } } uint256 amountToFree = _loss.add(_debtPayment); if (amountToFree > 0 && looseAssets < amountToFree) { _withdrawSome(amountToFree.sub(looseAssets)); uint256 newLoose = want.balanceOf(address(this)); if (newLoose < amountToFree) { if (_loss > newLoose) { _loss = newLoose; _debtPayment = 0; _debtPayment = Math.min(newLoose - _loss, _debtPayment); } } } } }
5,323,224
[ 1, 1814, 1608, 358, 4843, 731, 450, 7216, 8737, 389, 323, 23602, 1182, 15167, 18, 2047, 389, 323, 23602, 1182, 15167, 353, 1898, 2353, 732, 848, 4843, 732, 336, 487, 9816, 487, 3323, 1410, 506, 1158, 4031, 364, 1915, 358, 506, 279, 8324, 18, 732, 27370, 2777, 2135, 1754, 358, 17895, 26923, 578, 450, 7216, 358, 2605, 1814, 848, 1338, 327, 28393, 10726, 1814, 1608, 358, 527, 20974, 358, 3134, 450, 7216, 72, 1580, 1608, 358, 741, 4058, 309, 1915, 353, 486, 12266, 310, 358, 22010, 359, 483, 9446, 4121, 732, 848, 598, 9446, 430, 732, 14046, 1240, 7304, 15601, 5765, 389, 323, 23602, 1182, 15167, 471, 1338, 2549, 450, 7216, 309, 3577, 1918, 9446, 4121, 732, 848, 598, 9446, 430, 732, 14046, 1240, 7304, 15601, 5765, 389, 323, 23602, 1182, 15167, 471, 1338, 2549, 450, 7216, 309, 3577, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2911, 990, 12, 11890, 5034, 389, 323, 23602, 1182, 15167, 13, 203, 3639, 2713, 203, 3639, 3849, 203, 3639, 1135, 261, 203, 5411, 2254, 5034, 389, 685, 7216, 16, 203, 5411, 2254, 5034, 389, 7873, 16, 203, 5411, 2254, 5034, 389, 323, 23602, 6032, 203, 3639, 262, 203, 565, 288, 203, 3639, 389, 685, 7216, 273, 374, 31, 203, 3639, 389, 323, 23602, 6032, 273, 389, 323, 23602, 1182, 15167, 31, 203, 203, 3639, 2254, 5034, 328, 319, 10726, 273, 328, 319, 5269, 10726, 5621, 203, 203, 3639, 2254, 5034, 28393, 10726, 273, 2545, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2254, 5034, 277, 1949, 16040, 758, 23602, 273, 277, 1949, 16040, 1182, 15167, 758, 23602, 18005, 5621, 203, 3639, 2254, 5034, 2078, 273, 28393, 10726, 18, 1289, 12, 80, 319, 10726, 1769, 203, 3639, 309, 12, 1913, 16040, 758, 23602, 411, 2078, 15329, 203, 5411, 2078, 273, 2078, 18, 1717, 12, 1913, 16040, 758, 23602, 1769, 203, 5411, 2078, 273, 374, 31, 203, 3639, 289, 203, 203, 203, 203, 3639, 309, 261, 80, 319, 10726, 422, 374, 13, 288, 203, 5411, 309, 261, 67, 323, 23602, 6032, 405, 28393, 10726, 13, 288, 203, 7734, 389, 323, 23602, 6032, 273, 28393, 10726, 31, 203, 5411, 289, 203, 203, 5411, 327, 261, 67, 685, 7216, 16, 389, 7873, 16, 389, 323, 23602, 6032, 1769, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 18202, 88, 273, 9229, 18, 701, 15127, 12, 2867, 12, 2211, 13, 2934, 4963, 758, 23602, 31, 203, 2 ]
./full_match/137/0xA54D36B30F8aA90EB1a5d717856fB28dde98e891/sources/contracts/KidTD.sol
use by default 300,000 gas to process auto-claiming dividends exlcude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract KidTD is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public uniswapV2Router; address public immutable uniswapV2Pair; address payable marketingWallet = 0x930ab18E8e65779bcB4b250A764c624DA1F02216; uint256 private totalSupply_ = 10000000000; uint256 private decimal_ = 9; bool private swapping; bool public swapEnabled; KidTDDividendTracker public dividendTracker; address public liquidityWallet; uint256 public swapTokensAtAmount = totalSupply_ * (10**decimal_); uint256 public BNBRewardsBuyFee = 6; uint256 public liquidityBuyFee = 4; uint256 public marketingBuyFee = 4; uint256 public totalBuyFees = BNBRewardsBuyFee.add(liquidityBuyFee).add(marketingBuyFee); uint256 public BNBRewardsSellFee = 6; uint256 public liquiditySellFee = 6; uint256 public marketingSellFee = 6; uint256 public totalSellFees = BNBRewardsSellFee.add(liquiditySellFee).add(marketingSellFee); uint256 public maxTxSell = 1000000 * 10**decimal_; uint256 public maxTxBuy = 500000 * 10**decimal_; uint256 public gasForProcessing = 400000; mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public automatedMarketMakerPairs; event UpdateDividendTracker(address indexed newAddress, address indexed oldAddress); event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event ExcludeMultipleAccountsFromFees(address[] accounts, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event LiquidityWalletUpdated(address indexed newLiquidityWallet, address indexed oldLiquidityWallet); event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SendDividends( uint256 tokensSwapped, uint256 amount ); event ProcessedDividendTracker( uint256 iterations, uint256 claims, uint256 lastProcessedIndex, bool indexed automatic, uint256 gas, address indexed processor ); constructor() public ERC20("KidTD1", "KidTD1") { dividendTracker = new KidTDDividendTracker(); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0xa5E0829CaCEd8fFDD4De3c43696c57F7D7A678ff); address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = _uniswapV2Pair; liquidityWallet = owner(); _setAutomatedMarketMakerPair(_uniswapV2Pair, true); dividendTracker.excludeFromDividends(address(dividendTracker)); dividendTracker.excludeFromDividends(address(this)); dividendTracker.excludeFromDividends(owner()); dividendTracker.excludeFromDividends(address(0)); dividendTracker.excludeFromDividends(address(_uniswapV2Router)); excludeFromFees(owner(), true); excludeFromFees(marketingWallet, true); excludeFromFees(address(this), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(owner(), totalSupply_ * (10**9)); } receive() external payable { } function updateDividendTracker(address newAddress) public onlyOwner { require(newAddress != address(dividendTracker), "KidTD: The dividend tracker already has that address"); KidTDDividendTracker newDividendTracker = KidTDDividendTracker(payable(newAddress)); require(newDividendTracker.owner() == address(this), "KidTD: The new dividend tracker must be owned by the KidTD token contract"); newDividendTracker.excludeFromDividends(address(newDividendTracker)); newDividendTracker.excludeFromDividends(address(this)); newDividendTracker.excludeFromDividends(owner()); newDividendTracker.excludeFromDividends(address(0)); newDividendTracker.excludeFromDividends(address(uniswapV2Router)); emit UpdateDividendTracker(newAddress, address(dividendTracker)); dividendTracker = newDividendTracker; } function updateUniswapV2Router(address newAddress) public onlyOwner { require(newAddress != address(uniswapV2Router), "KidTD: The router already has that address"); emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router)); uniswapV2Router = IUniswapV2Router02(newAddress); } function excludeFromFees(address account, bool excluded) public onlyOwner { require(_isExcludedFromFees[account] != excluded, "KidTD: Account is already the value of 'excluded'"); _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFees[accounts[i]] = excluded; } emit ExcludeMultipleAccountsFromFees(accounts, excluded); } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFees[accounts[i]] = excluded; } emit ExcludeMultipleAccountsFromFees(accounts, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "KidTD: The PancakeSwap pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function setSwapEnabled(bool value) external onlyOwner{ swapEnabled = value; } function _setAutomatedMarketMakerPair(address pair, bool value) private { require(automatedMarketMakerPairs[pair] != value, "KidTD: Automated market maker pair is already set to that value"); automatedMarketMakerPairs[pair] = value; if(value) { dividendTracker.excludeFromDividends(pair); } emit SetAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { require(automatedMarketMakerPairs[pair] != value, "KidTD: Automated market maker pair is already set to that value"); automatedMarketMakerPairs[pair] = value; if(value) { dividendTracker.excludeFromDividends(pair); } emit SetAutomatedMarketMakerPair(pair, value); } function updateGasForProcessing(uint256 newValue) public onlyOwner { require(newValue >= 200000 && newValue <= 500000, "KidTD: gasForProcessing must be between 200,000 and 500,000"); require(newValue != gasForProcessing, "KidTD: Cannot update gasForProcessing to same value"); emit GasForProcessingUpdated(newValue, gasForProcessing); gasForProcessing = newValue; } function updateClaimWait(uint256 claimWait) external onlyOwner { dividendTracker.updateClaimWait(claimWait); } function getClaimWait() external view returns(uint256) { return dividendTracker.claimWait(); } function getTotalDividendsDistributed() external view returns (uint256) { return dividendTracker.totalDividendsDistributed(); } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function withdrawableDividendOf(address account) public view returns(uint256) { return dividendTracker.withdrawableDividendOf(account); } function dividendTokenBalanceOf(address account) public view returns (uint256) { return dividendTracker.balanceOf(account); } function getAccountDividendsInfo(address account) external view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { return dividendTracker.getAccount(account); } function getAccountDividendsInfoAtIndex(uint256 index) external view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { return dividendTracker.getAccountAtIndex(index); } function processDividendTracker(uint256 gas) external { (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) = dividendTracker.process(gas); emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, false, gas, tx.origin); } function claim() external { dividendTracker.processAccount(msg.sender, false); } function getLastProcessedIndex() external view returns(uint256) { return dividendTracker.getLastProcessedIndex(); } function setSwapTokensAtAmt(uint256 amount) external onlyOwner{ swapTokensAtAmount = amount; } function withdraw(uint256 weiAmount) external onlyOwner{ msg.sender.transfer(weiAmount); } function getNumberOfDividendTokenHolders() external view returns(uint256) { return dividendTracker.getNumberOfTokenHolders(); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); bool isSell = from == uniswapV2Pair; require(amount <= (isSell ? maxTxSell : maxTxBuy), "ERC20: transfer failed due to amount more than max tx"); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && swapEnabled ) { swapping = true; uint256 marketingTokens = contractTokenBalance.mul(isSell ? marketingSellFee : marketingBuyFee).div(isSell ? totalSellFees : totalBuyFees); swapAndSendToFee(marketingWallet, marketingTokens); uint256 swapTokens = contractTokenBalance.mul(isSell ? liquiditySellFee : liquidityBuyFee).div(isSell ? totalSellFees : totalBuyFees); swapAndLiquify(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(isSell ? totalSellFees : totalBuyFees).div(100); if(automatedMarketMakerPairs[to]){ fees += amount.mul(6).div(100); } amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); if(!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); bool isSell = from == uniswapV2Pair; require(amount <= (isSell ? maxTxSell : maxTxBuy), "ERC20: transfer failed due to amount more than max tx"); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && swapEnabled ) { swapping = true; uint256 marketingTokens = contractTokenBalance.mul(isSell ? marketingSellFee : marketingBuyFee).div(isSell ? totalSellFees : totalBuyFees); swapAndSendToFee(marketingWallet, marketingTokens); uint256 swapTokens = contractTokenBalance.mul(isSell ? liquiditySellFee : liquidityBuyFee).div(isSell ? totalSellFees : totalBuyFees); swapAndLiquify(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(isSell ? totalSellFees : totalBuyFees).div(100); if(automatedMarketMakerPairs[to]){ fees += amount.mul(6).div(100); } amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); if(!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); bool isSell = from == uniswapV2Pair; require(amount <= (isSell ? maxTxSell : maxTxBuy), "ERC20: transfer failed due to amount more than max tx"); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && swapEnabled ) { swapping = true; uint256 marketingTokens = contractTokenBalance.mul(isSell ? marketingSellFee : marketingBuyFee).div(isSell ? totalSellFees : totalBuyFees); swapAndSendToFee(marketingWallet, marketingTokens); uint256 swapTokens = contractTokenBalance.mul(isSell ? liquiditySellFee : liquidityBuyFee).div(isSell ? totalSellFees : totalBuyFees); swapAndLiquify(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(isSell ? totalSellFees : totalBuyFees).div(100); if(automatedMarketMakerPairs[to]){ fees += amount.mul(6).div(100); } amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); if(!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); bool isSell = from == uniswapV2Pair; require(amount <= (isSell ? maxTxSell : maxTxBuy), "ERC20: transfer failed due to amount more than max tx"); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && swapEnabled ) { swapping = true; uint256 marketingTokens = contractTokenBalance.mul(isSell ? marketingSellFee : marketingBuyFee).div(isSell ? totalSellFees : totalBuyFees); swapAndSendToFee(marketingWallet, marketingTokens); uint256 swapTokens = contractTokenBalance.mul(isSell ? liquiditySellFee : liquidityBuyFee).div(isSell ? totalSellFees : totalBuyFees); swapAndLiquify(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(isSell ? totalSellFees : totalBuyFees).div(100); if(automatedMarketMakerPairs[to]){ fees += amount.mul(6).div(100); } amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); if(!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); bool isSell = from == uniswapV2Pair; require(amount <= (isSell ? maxTxSell : maxTxBuy), "ERC20: transfer failed due to amount more than max tx"); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && swapEnabled ) { swapping = true; uint256 marketingTokens = contractTokenBalance.mul(isSell ? marketingSellFee : marketingBuyFee).div(isSell ? totalSellFees : totalBuyFees); swapAndSendToFee(marketingWallet, marketingTokens); uint256 swapTokens = contractTokenBalance.mul(isSell ? liquiditySellFee : liquidityBuyFee).div(isSell ? totalSellFees : totalBuyFees); swapAndLiquify(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(isSell ? totalSellFees : totalBuyFees).div(100); if(automatedMarketMakerPairs[to]){ fees += amount.mul(6).div(100); } amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); if(!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); bool isSell = from == uniswapV2Pair; require(amount <= (isSell ? maxTxSell : maxTxBuy), "ERC20: transfer failed due to amount more than max tx"); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && swapEnabled ) { swapping = true; uint256 marketingTokens = contractTokenBalance.mul(isSell ? marketingSellFee : marketingBuyFee).div(isSell ? totalSellFees : totalBuyFees); swapAndSendToFee(marketingWallet, marketingTokens); uint256 swapTokens = contractTokenBalance.mul(isSell ? liquiditySellFee : liquidityBuyFee).div(isSell ? totalSellFees : totalBuyFees); swapAndLiquify(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(isSell ? totalSellFees : totalBuyFees).div(100); if(automatedMarketMakerPairs[to]){ fees += amount.mul(6).div(100); } amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); if(!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } try dividendTracker.setBalance(payable(from), balanceOf(from)) {} catch {} try dividendTracker.setBalance(payable(to), balanceOf(to)) {} catch {} function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); bool isSell = from == uniswapV2Pair; require(amount <= (isSell ? maxTxSell : maxTxBuy), "ERC20: transfer failed due to amount more than max tx"); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && swapEnabled ) { swapping = true; uint256 marketingTokens = contractTokenBalance.mul(isSell ? marketingSellFee : marketingBuyFee).div(isSell ? totalSellFees : totalBuyFees); swapAndSendToFee(marketingWallet, marketingTokens); uint256 swapTokens = contractTokenBalance.mul(isSell ? liquiditySellFee : liquidityBuyFee).div(isSell ? totalSellFees : totalBuyFees); swapAndLiquify(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(isSell ? totalSellFees : totalBuyFees).div(100); if(automatedMarketMakerPairs[to]){ fees += amount.mul(6).div(100); } amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); if(!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); bool isSell = from == uniswapV2Pair; require(amount <= (isSell ? maxTxSell : maxTxBuy), "ERC20: transfer failed due to amount more than max tx"); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && swapEnabled ) { swapping = true; uint256 marketingTokens = contractTokenBalance.mul(isSell ? marketingSellFee : marketingBuyFee).div(isSell ? totalSellFees : totalBuyFees); swapAndSendToFee(marketingWallet, marketingTokens); uint256 swapTokens = contractTokenBalance.mul(isSell ? liquiditySellFee : liquidityBuyFee).div(isSell ? totalSellFees : totalBuyFees); swapAndLiquify(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(isSell ? totalSellFees : totalBuyFees).div(100); if(automatedMarketMakerPairs[to]){ fees += amount.mul(6).div(100); } amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); if(!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); bool isSell = from == uniswapV2Pair; require(amount <= (isSell ? maxTxSell : maxTxBuy), "ERC20: transfer failed due to amount more than max tx"); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && swapEnabled ) { swapping = true; uint256 marketingTokens = contractTokenBalance.mul(isSell ? marketingSellFee : marketingBuyFee).div(isSell ? totalSellFees : totalBuyFees); swapAndSendToFee(marketingWallet, marketingTokens); uint256 swapTokens = contractTokenBalance.mul(isSell ? liquiditySellFee : liquidityBuyFee).div(isSell ? totalSellFees : totalBuyFees); swapAndLiquify(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(isSell ? totalSellFees : totalBuyFees).div(100); if(automatedMarketMakerPairs[to]){ fees += amount.mul(6).div(100); } amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); if(!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function setMaxTxBuy(uint256 amount) external onlyOwner{ maxTxBuy = amount; } function setMaxTxSell(uint256 amount) external onlyOwner{ maxTxSell = amount; } function setBuyFee(uint256 _rewardFee, uint256 _liquidityFee, uint256 _marketingFee) external onlyOwner{ BNBRewardsBuyFee = _rewardFee; liquidityBuyFee = _liquidityFee; marketingBuyFee = _marketingFee; totalBuyFees = BNBRewardsBuyFee.add(liquidityBuyFee).add(marketingBuyFee); } function setSellFee(uint256 _rewardFee, uint256 _liquidityFee, uint256 _marketingFee) external onlyOwner{ BNBRewardsSellFee = _rewardFee; liquiditySellFee = _liquidityFee; marketingSellFee = _marketingFee; totalSellFees = BNBRewardsSellFee.add(liquiditySellFee).add(marketingSellFee); } function swapAndSendToFee(address payable wallet, uint256 tokens) private { uint256 initialBalance = address(this).balance; swapTokensForEth(tokens); uint256 newBalance = address(this).balance.sub(initialBalance); wallet.transfer(newBalance); } function excludeFromDividends(address wallet) external onlyOwner{ dividendTracker.excludeFromDividends(wallet); } function setMarketingWallet(address payable newwallet) external onlyOwner{ marketingWallet = newwallet; } function swapAndLiquify(uint256 tokens) private { uint256 half = tokens.div(2); uint256 otherHalf = tokens.sub(half); uint256 initialBalance = address(this).balance; uint256 newBalance = address(this).balance.sub(initialBalance); addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, liquidityWallet, block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function swapAndSendDividends(uint256 tokens) private { swapTokensForEth(tokens); uint256 dividends = address(this).balance; if(success) { emit SendDividends(tokens, dividends); } } (bool success,) = address(dividendTracker).call{value: dividends}(""); function swapAndSendDividends(uint256 tokens) private { swapTokensForEth(tokens); uint256 dividends = address(this).balance; if(success) { emit SendDividends(tokens, dividends); } } }
4,699,927
[ 1, 1202, 635, 805, 11631, 16, 3784, 16189, 358, 1207, 3656, 17, 14784, 310, 3739, 350, 5839, 431, 17704, 1317, 628, 1656, 281, 471, 943, 2492, 3844, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 1475, 350, 23409, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 11732, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 203, 565, 1758, 8843, 429, 13667, 310, 16936, 273, 374, 92, 29, 5082, 378, 2643, 41, 28, 73, 9222, 4700, 29, 13459, 38, 24, 70, 26520, 37, 27, 1105, 71, 26, 3247, 9793, 21, 42, 3103, 22, 2313, 31, 203, 565, 2254, 5034, 3238, 2078, 3088, 1283, 67, 273, 2130, 12648, 31, 203, 565, 2254, 5034, 3238, 6970, 67, 273, 2468, 31, 203, 565, 1426, 3238, 7720, 1382, 31, 203, 565, 1426, 1071, 7720, 1526, 31, 203, 203, 565, 1475, 350, 56, 5698, 427, 26746, 8135, 1071, 31945, 8135, 31, 203, 203, 565, 1758, 1071, 4501, 372, 24237, 16936, 31, 203, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 273, 2078, 3088, 1283, 67, 380, 261, 2163, 636, 12586, 67, 1769, 203, 203, 565, 2254, 5034, 1071, 225, 605, 50, 7192, 359, 14727, 38, 9835, 14667, 273, 1666, 31, 203, 565, 2254, 5034, 1071, 225, 4501, 372, 24237, 38, 9835, 14667, 273, 1059, 31, 203, 565, 2254, 5034, 1071, 225, 13667, 310, 38, 9835, 14667, 273, 1059, 31, 203, 565, 2254, 5034, 1071, 225, 2078, 38, 9835, 2954, 281, 273, 605, 50, 7192, 359, 14727, 38, 9835, 14667, 18, 1289, 12, 549, 372, 24237, 38, 9835, 14667, 2 ]
//Address: 0x2821fb31998e60d220ff52af6299872f25a3e149 //Contract name: EmaCrowdSale //Balance: 0 Ether //Verification Date: 5/20/2018 //Transacion Count: 16 // CODE STARTS HERE pragma solidity ^ 0.4 .23; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns(uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns(uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns(uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns(uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract Controlled is Pausable { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } modifier onlyControllerorOwner { require((msg.sender == controller) || (msg.sender == owner)); _; } address public controller; constructor() public { controller = msg.sender; } /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) public onlyControllerorOwner { controller = _newController; } } contract TokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) public payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) public returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) public returns(bool); } /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { using SafeMath for uint256; string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = 'V 1.0'; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping(address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping(address => mapping(address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred constructor( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = MiniMeTokenFactory(_tokenFactory); name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = MiniMeToken(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns(bool success) { require(transfersEnabled); 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 controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); } doTransfer(_from, _to, _amount); return true; } /// @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 { if (_amount == 0) { emit Transfer(_from, _to, _amount); // Follow the spec to louch the event when transfer 0 return; } // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer throws uint256 previousBalanceFrom = balanceOfAt(_from, block.number); require(previousBalanceFrom >= _amount); // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens uint256 previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo.add(_amount) >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo.add(_amount)); // An event to make the transfer easy to find on the blockchain emit Transfer(_from, _to, _amount); } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public constant returns(uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns(bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); } allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) public constant returns(uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(address _spender, uint256 _amount, bytes _extraData) public returns(bool success) { require(approve(_spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns(uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public constant returns(uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public constant returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount) public onlyControllerorOwner whenNotPaused returns(bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply.add(_amount) >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo.add(_amount) >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply.add(_amount)); updateValueAtNow(balances[_owner], previousBalanceTo.add(_amount)); emit Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount) onlyControllerorOwner public returns(bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply.sub(_amount)); updateValueAtNow(balances[_owner], previousBalanceFrom.sub(_amount)); emit Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) public onlyControllerorOwner { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block) constant internal returns(uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length.sub(1)].fromBlock) return checkpoints[checkpoints.length.sub(1)].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length.sub(1); while (max > min) { uint mid = (max.add(min).add(1)).div(2); if (checkpoints[mid].fromBlock <= _block) { min = mid; } else { max = mid.sub(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.sub(1)].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length.sub(1)]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size: = extcodesize(_addr) } return size > 0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns(uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function() public payable { /*require(isContract(controller)); require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender));*/ revert(); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) public onlyControllerorOwner { if (_token == 0x0) { controller.transfer(address(this).balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); emit ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns(uint256); function balanceOf(address who) public view returns(uint256); function transfer(address to, uint256 value) public returns(bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public; } contract EmaToken is MiniMeToken { constructor(address tokenfactory, address parenttoken, uint parentsnapshot, string tokenname, uint8 dec, string tokensymbol, bool transfersenabled) MiniMeToken(tokenfactory, parenttoken, parentsnapshot, tokenname, dec, tokensymbol, transfersenabled) public {} } /** * @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 Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns(MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } contract Crowdsale is Pausable { using SafeMath for uint256; // The token being sold MiniMeToken public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei uint256 public rate = 6120; // Amount of tokens sold uint256 public tokensSold; uint256 public allCrowdSaleTokens = 255000000000000000000000000; //255M tokens available for crowdsale /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event buyx(address buyer, address contractAddr, uint256 amount); constructor(address _wallet, MiniMeToken _token) public { require(_wallet != address(0)); require(_token != address(0)); wallet = _wallet; token = _token; } function setCrowdsale(address _wallet, MiniMeToken _token) internal { require(_wallet != address(0)); require(_token != address(0)); wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * fallback function ***DO NOT OVERRIDE*** */ function() external whenNotPaused payable { emit buyx(msg.sender, this, _getTokenAmount(msg.value)); buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public whenNotPaused payable { if ((msg.value >= 500000000000000000000) && (msg.value < 1000000000000000000000)) { rate = 7140; } else if (msg.value >= 1000000000000000000000) { rate = 7650; } else if (tokensSold <= 21420000000000000000000000) { rate = 6120; } else if ((tokensSold > 21420000000000000000000000) && (tokensSold <= 42304500000000000000000000)) { rate = 5967; } else if ((tokensSold > 42304500000000000000000000) && (tokensSold <= 73095750000000000000000000)) { rate = 5865; } else if ((tokensSold > 73095750000000000000000000) && (tokensSold <= 112365750000000000000000000)) { rate = 5610; } else if ((tokensSold > 112365750000000000000000000) && (tokensSold <= 159222000000000000000000000)) { rate = 5355; } else if (tokensSold > 159222000000000000000000000) { rate = 5100; } uint256 weiAmount = msg.value; uint256 tokens = _getTokenAmount(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); tokensSold = allCrowdSaleTokens.sub(token.balanceOf(this)); } // ----------------------------------------- // 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.transfer(_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 returns(uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } contract EmaCrowdSale is Crowdsale { using SafeMath for uint256; constructor(address wallet, MiniMeToken token) Crowdsale(wallet, token) public { setCrowdsale(wallet, token); } function tranferPresaleTokens(address investor, uint256 ammount) public onlyOwner { tokensSold = tokensSold.add(ammount); token.transferFrom(this, investor, ammount); } function setTokenTransferState(bool state) public onlyOwner { token.changeController(this); token.enableTransfers(state); } function claim(address claimToken) public onlyOwner { token.changeController(this); token.claimTokens(claimToken); } function() external payable whenNotPaused { emit buyx(msg.sender, this, _getTokenAmount(msg.value)); buyTokens(msg.sender); } }
* @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/ optional override
function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { }
1,044,949
[ 1, 4354, 434, 392, 7120, 23701, 18, 21008, 919, 471, 999, 15226, 6317, 358, 15436, 8006, 1347, 923, 4636, 854, 486, 5100, 18, 225, 389, 70, 4009, 74, 14463, 814, 5267, 14928, 326, 1147, 23701, 225, 389, 1814, 77, 6275, 1445, 316, 732, 77, 24589, 316, 326, 23701, 19, 3129, 3849, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2767, 4270, 23164, 12, 2867, 389, 70, 4009, 74, 14463, 814, 16, 2254, 5034, 389, 1814, 77, 6275, 13, 2713, 288, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; /// @title Strong Holder Offering (SHO) contract used to collect funds from SHO lottery winners. /// @author DAO Maker /// @notice The flow is the following: /// 1. SHO Organizer runs the lottery off-chain. /// 2. Once the winners are selected, for every winner, the SHO Organzier signs a message cointaining the SHO information. /// The signing, as well as the signature storage, is done off-chain. /// 3. Winners call this contract passing in the signature and the relevant SHO data. By doing this they confirm their /// particiaption in the SHO (i.e. claim their winning spot) and transfer the funds required to participate. /// 4. The SHO contract verifies the signature, to make sure it comes from the SHO Organizer, and verifies the signed SHO data. /// If all is correct, the funds are transferred from the winner to the fund receiver. /// @dev The contract is owned by an admin (intended to be a multisig wallet) who can change critical state variables. /// SHO Organizer is a off-chain role. contract SHO is Ownable, Pausable { using ECDSA for bytes32; using SafeERC20 for IERC20; address public shoOrganizer; address public depositReceiver; mapping(string => mapping(address => bool)) public depositsForSho; mapping(string => uint) public depositedAmount; event ShoOrganizerChanged( address oldShoOrganizer, address newShoOrganizer ); event DepositReceiverChanged( address oldDepositReceiver, address newDepositReceiver ); event Deposited( address indexed winner, string indexed indexedShoId, string shoId, IERC20 depositToken, uint amount, uint deadline, address indexed depositReceiver, address shoOrganizer, uint maxTotalAmount ); event RecoveredERC20( uint amount, IERC20 token ); constructor(address _shoOrganizer, address _depositReceiver) { shoOrganizer = _shoOrganizer; depositReceiver = _depositReceiver; emit ShoOrganizerChanged(address(0), _shoOrganizer); emit DepositReceiverChanged(address(0), _depositReceiver); } function setShoOrganizer(address _shoOrganizer) external onlyOwner { emit ShoOrganizerChanged(shoOrganizer, _shoOrganizer); shoOrganizer = _shoOrganizer; } function setDepositReceiver(address _depositReceiver) external onlyOwner { emit DepositReceiverChanged(depositReceiver, _depositReceiver); depositReceiver = _depositReceiver; } function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } /// @notice Verifies that the passed SHO data is signed correctly and that the signature comes from the SHO Organizer. /// If all checks out, the caller is marked in contract storage and funds are transferred from the caller to the predefined /// fund receiver. /// @dev Callable by any account. Security is based on the passed signature. Pausable by the owner. /// @param signature Signature from the SHO Organizer. The message signed contains the winner address and the other parameters /// passed in the call. /// @param shoId An opaque SHO identifier. /// @param depositToken Address of an ERC20-compatible token used for deposits in this SHO. The winner must first set the token /// allowance of this contract for the `amount` or more. /// @param amount Amount of tokens the winner is allowed to send. The unit is the base unit of the `depositToken` /// (i.e. the smallest subdenomination of the token). /// @param deadline Time until the winners have to call this function (in Unix time). /// @param maxTotalAmount The maximum amount that can be deposited for a given shoId. function deposit( bytes calldata signature, string calldata shoId, IERC20 depositToken, uint amount, uint deadline, uint maxTotalAmount ) external whenNotPaused { address winner = msg.sender; require(!depositsForSho[shoId][winner], "SHO: this wallet already made a deposit for this SHO"); require(block.timestamp <= deadline, "SHO: the deadline for this SHO has passed"); depositedAmount[shoId] += amount; require(depositedAmount[shoId] <= maxTotalAmount, "SHO: the maximum amount of deposits have been reached"); bytes32 dataHash = keccak256(abi.encodePacked(winner, shoId, depositToken, amount, deadline, depositReceiver, maxTotalAmount)); require(dataHash.toEthSignedMessageHash().recover(signature) == shoOrganizer, "SHO: signature verification failed"); depositsForSho[shoId][winner] = true; depositToken.safeTransferFrom(winner, depositReceiver, amount); emit Deposited(winner, shoId, shoId, depositToken, amount, deadline, depositReceiver, shoOrganizer, maxTotalAmount); } /// @notice Recovers any tokens unintentionally sent to this contract. This contract is not meant to hold any funds. /// @dev The admin can call this to recover any tokens sent mistakenly to this contract by users. /// @param token ERC20 token address to be recovered. function recoverERC20(IERC20 token) external onlyOwner { uint balance = token.balanceOf(address(this)); token.safeTransfer(msg.sender, balance); emit RecoveredERC20(balance, token); } }
@notice Verifies that the passed SHO data is signed correctly and that the signature comes from the SHO Organizer. If all checks out, the caller is marked in contract storage and funds are transferred from the caller to the predefined fund receiver. @dev Callable by any account. Security is based on the passed signature. Pausable by the owner. @param signature Signature from the SHO Organizer. The message signed contains the winner address and the other parameters passed in the call. @param shoId An opaque SHO identifier. @param depositToken Address of an ERC20-compatible token used for deposits in this SHO. The winner must first set the token allowance of this contract for the `amount` or more. @param amount Amount of tokens the winner is allowed to send. The unit is the base unit of the `depositToken` (i.e. the smallest subdenomination of the token). @param deadline Time until the winners have to call this function (in Unix time). @param maxTotalAmount The maximum amount that can be deposited for a given shoId.
function deposit( bytes calldata signature, string calldata shoId, IERC20 depositToken, uint amount, uint deadline, uint maxTotalAmount ) external whenNotPaused { address winner = msg.sender; require(!depositsForSho[shoId][winner], "SHO: this wallet already made a deposit for this SHO"); require(block.timestamp <= deadline, "SHO: the deadline for this SHO has passed"); depositedAmount[shoId] += amount; require(depositedAmount[shoId] <= maxTotalAmount, "SHO: the maximum amount of deposits have been reached"); bytes32 dataHash = keccak256(abi.encodePacked(winner, shoId, depositToken, amount, deadline, depositReceiver, maxTotalAmount)); require(dataHash.toEthSignedMessageHash().recover(signature) == shoOrganizer, "SHO: signature verification failed"); depositsForSho[shoId][winner] = true; depositToken.safeTransferFrom(winner, depositReceiver, amount); emit Deposited(winner, shoId, shoId, depositToken, amount, deadline, depositReceiver, shoOrganizer, maxTotalAmount); }
1,034,368
[ 1, 19802, 716, 326, 2275, 6122, 51, 501, 353, 6726, 8783, 471, 716, 326, 3372, 14535, 628, 326, 6122, 51, 8533, 304, 1824, 18, 971, 777, 4271, 596, 16, 326, 4894, 353, 9350, 316, 6835, 2502, 471, 284, 19156, 854, 906, 4193, 628, 326, 4894, 358, 326, 19555, 284, 1074, 5971, 18, 225, 10464, 635, 1281, 2236, 18, 6036, 353, 2511, 603, 326, 2275, 3372, 18, 21800, 16665, 635, 326, 3410, 18, 225, 3372, 9249, 628, 326, 6122, 51, 8533, 304, 1824, 18, 1021, 883, 6726, 1914, 326, 5657, 1224, 1758, 471, 326, 1308, 1472, 3639, 2275, 316, 326, 745, 18, 225, 699, 83, 548, 1922, 22519, 6122, 51, 2756, 18, 225, 443, 1724, 1345, 5267, 434, 392, 4232, 39, 3462, 17, 10943, 1147, 1399, 364, 443, 917, 1282, 316, 333, 6122, 51, 18, 1021, 5657, 1224, 1297, 1122, 444, 326, 1147, 3639, 1699, 1359, 434, 333, 6835, 364, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 443, 1724, 12, 203, 3639, 1731, 745, 892, 3372, 16, 203, 3639, 533, 745, 892, 699, 83, 548, 16, 203, 3639, 467, 654, 39, 3462, 443, 1724, 1345, 16, 203, 3639, 2254, 3844, 16, 203, 3639, 2254, 14096, 16, 203, 3639, 2254, 943, 5269, 6275, 203, 565, 262, 3903, 1347, 1248, 28590, 288, 203, 3639, 1758, 5657, 1224, 273, 1234, 18, 15330, 31, 203, 203, 3639, 2583, 12, 5, 323, 917, 1282, 1290, 1555, 83, 63, 674, 83, 548, 6362, 91, 7872, 6487, 315, 2664, 51, 30, 333, 9230, 1818, 7165, 279, 443, 1724, 364, 333, 6122, 51, 8863, 203, 3639, 2583, 12, 2629, 18, 5508, 1648, 14096, 16, 315, 2664, 51, 30, 326, 14096, 364, 333, 6122, 51, 711, 2275, 8863, 203, 203, 3639, 443, 1724, 329, 6275, 63, 674, 83, 548, 65, 1011, 3844, 31, 203, 3639, 2583, 12, 323, 1724, 329, 6275, 63, 674, 83, 548, 65, 1648, 943, 5269, 6275, 16, 315, 2664, 51, 30, 326, 4207, 3844, 434, 443, 917, 1282, 1240, 2118, 8675, 8863, 203, 203, 3639, 1731, 1578, 501, 2310, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 91, 7872, 16, 699, 83, 548, 16, 443, 1724, 1345, 16, 3844, 16, 14096, 16, 443, 1724, 12952, 16, 943, 5269, 6275, 10019, 203, 3639, 2583, 12, 892, 2310, 18, 869, 41, 451, 12294, 1079, 2310, 7675, 266, 3165, 12, 8195, 13, 422, 699, 83, 6001, 304, 1824, 16, 315, 2664, 51, 30, 3372, 11805, 2535, 8863, 203, 203, 3639, 443, 917, 1282, 2 ]
pragma solidity ^0.4.18; import "./PayrollInterface.sol"; import "./math/SafeMath.sol"; import "./token/StandardToken.sol"; contract Payroll is PayrollInterface { using SafeMath for uint256; struct Employee { uint lastPayday; uint lastAllocated; uint256 yearlySalaryUSD; address[] tokenAllocation; uint256[] tokenDistribution; } address private owner; address private oracle; Employee[] employees; mapping (address => uint256) employmentHistory; uint256 private totalFundsUSD; mapping (address => uint256) private tokenFunds; mapping (address => uint256) private exchangeRates; event EmployeeAdded(address _employee, address[] _allowedTokens, uint256 _initialYearlySalary); event EmployeeSalaryChanged(uint256 employeeId, uint256 _yearlyUSDSalary); event EmployeeRemoved(uint256 employeeId); event FundsAdded(address token, uint256 amount, uint256 currentFunds); event TokensAllocated(address employee, address[] tokens, uint256[] distribution); event TransferedEther(address employee, uint256 amount); event TransferedToken(address employee, address token, uint256 amount); event EmployeePaid(address employee, uint256 amount); event ExchangeRateSet(address token, uint256 exchangeRate); modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyEmployed() { require(employees[employmentHistory[msg.sender]].yearlySalaryUSD > 0); _; } modifier onlyOracle() { require(msg.sender == oracle); _; } /** * @dev Payroll creates a new payroll with the sender being the owner of the payroll * @param _oracle */ function Payroll(address _oracle) public { owner = msg.sender; oracle = _oracle; } /** * @dev addEmployee allows the payroll owner to add a employee to the payroll * @param accountAddress is the address of the employee being added to the payroll * @param allowedTokens is an array of the tokens that the employee is allowed to be paid in * @param distribution is an array of percentages that add to 100 specifying what percent of the employee salary will be paid out in each token * @param initialYearlyUSDSalary is the yearly USD salary of the employee */ function addEmployee(address accountAddress, address[] allowedTokens, uint256[] distribution, uint256 initialYearlyUSDSalary) public onlyOwner { require(accountAddress != 0x0); require(allowedTokens.length == distribution.length); require(initialYearlyUSDSalary >= 0); employmentHistory[accountAddress] = employees.length; employees.push(Employee({ lastPayday: 0, lastAllocated: 0, yearlySalaryUSD: initialYearlyUSDSalary, tokenAllocation: allowedTokens, tokenDistribution: distribution })); EmployeeAdded(accountAddress, allowedTokens, initialYearlyUSDSalary); } /** * @dev setEmployeeSalary allows the payroll owner to increase or decrease an employee salary * @param _employeeId numerical id of the employee must be greater than -1 * @param _yearlyUSDSalary new salary of the employee must be greater than 0 */ function setEmployeeSalary(uint256 _employeeId, uint256 _yearlyUSDSalary) public onlyOwner { require(employees[_employeeId].yearlySalaryUSD > 0 && _yearlyUSDSalary > 0); employees[_employeeId].yearlySalaryUSD = _yearlyUSDSalary; EmployeeSalaryChanged(_employeeId, _yearlyUSDSalary); } /** * @dev removeEmployee allows for the payroll owner to remove an employee from payroll * @param _employeeId numerical id of the employee must be greater than -1 */ function removeEmployee(uint256 _employeeId) public onlyOwner { require(employees[_employeeId].yearlySalaryUSD > 0); // use delete so that employee id order is preserved delete employees[_employeeId]; employees.length--; EmployeeRemoved(_employeeId); } /** * @dev addFunds allows the payroll owner to add ether funds to the payroll */ function addFunds() public onlyOwner payable { require(msg.value > 0); uint256 fundsUSD = msg.value.mul(exchangeRates[0x0]); totalFundsUSD = totalFundsUSD.add(fundsUSD); FundsAdded(0x0, fundsUSD, totalFundsUSD); } /** * @dev scapeHatch allows the owner to take funds so that they are not lost in the contract forever */ function scapeHatch() public onlyOwner { selfdestruct(owner); } /** * @dev getPayrollFunds returns the ether funds in USD * @notice only the payroll owner can call this function */ function getPayrollFunds() public view onlyOwner returns (uint256) { return this.balance.mul(exchangeRates[0x0]); } /** * @dev getEmployeeCount returns the current number of employee on payroll */ function getEmployeeCount() public view returns (uint256) { return employees.length; } /** * @dev getEmployee returns information about the employee using their employeeID * @param _employeeId numerical id of employee on payroll, must be greater than -1 */ function getEmployee(uint256 _employeeId) public view returns (uint, uint, uint256, address[], uint256[]) { require(_employeeId >= 0); Employee storage employee = employees[_employeeId]; return ( employee.lastPayday, employee.lastAllocated, employee.yearlySalaryUSD, employee.tokenAllocation, employee.tokenDistribution); } /** * @dev _calculateYearlyBurnrate determines the how much funds are spent per year */ function _calculateYearlyBurnrate() internal view returns (uint256) { uint256 yearlyBurnrate; for (uint256 i = 0; i < employees.length; i++) { yearlyBurnrate = yearlyBurnrate.add(employees[i].yearlySalaryUSD); } return yearlyBurnrate; } /** * @dev calculatePayrollBurnrate determines how much funds are spent per month */ function calculatePayrollBurnrate() public view returns (uint256) { return _calculateYearlyBurnrate().div(uint256(12)); } /** * @dev calculatePayrollRunway calculates how manys days are left until the payroll is out of funds */ function calculatePayrollRunway() public view returns (uint256) { uint256 dailyBurnRate = _calculateYearlyBurnrate().div(uint256(365)); return totalFundsUSD.div(dailyBurnRate); } /** * @dev determineAllocation lets a employee determine which tokens they would like to be paid in and in what distribution * @notice only employees can call this function and can only do so every six months * @notice distribution array values must add up to 100 * @param tokens array of tokens that the employee wishes to be paid out in * @param distribution array of percentages of how the employee will be paid out in each token */ function determineAllocation(address[] tokens, uint256[] distribution) onlyEmployed public { require(tokens.length > 0 && tokens.length == distribution.length); require(block.timestamp > employees[employmentHistory[msg.sender]].lastAllocated + 180 * 1 days); uint256 totalDistribution; for (uint256 i = 0; i < distribution.length; i++) { totalDistribution = totalDistribution.add(distribution[i]); } require(totalDistribution == 100); employees[employmentHistory[msg.sender]].tokenAllocation = tokens; employees[employmentHistory[msg.sender]].tokenDistribution = distribution; employees[employmentHistory[msg.sender]].lastAllocated = block.timestamp; TokensAllocated(msg.sender, tokens, distribution); } /** * @dev payday allows for employees to collect their monthly paycheck * @notice Only employees can call this function and can only call this once every 30 days */ function payday() onlyEmployed public { require(employees[employmentHistory[msg.sender]].yearlySalaryUSD > 0); Employee storage employee = employees[employmentHistory[msg.sender]]; require(block.timestamp > employee.lastPayday + 30 * 1 days); uint256 monthPaycheckUSD = employee.yearlySalaryUSD.div(uint256(12)); for (uint256 i = 0; i < employee.tokenAllocation.length; i++) { // determine the amount in the token we should be paying to the employee address token = employee.tokenAllocation[i]; uint256 distribution = employee.tokenDistribution[i]; if (distribution == 0) { continue; } uint256 tokenPaycheckUSD = (monthPaycheckUSD.mul(distribution)).div(uint(100)); uint256 tokenPaycheck = tokenPaycheckUSD.div(exchangeRates[token]); if (token == 0x0) { // just do an ether transfer msg.sender.transfer(tokenPaycheck); TransferedEther(msg.sender, tokenPaycheck); } else { // will need to use ERC20 transfer protocols StandardToken stdToken = StandardToken(token); stdToken.transferFrom(owner, msg.sender, tokenPaycheck); TransferedToken(msg.sender, token, tokenPaycheck); } } totalFundsUSD = totalFundsUSD.sub(monthPaycheckUSD); employee.lastPayday = block.timestamp; EmployeePaid(msg.sender, monthPaycheckUSD); } /** * @dev setExchangeRate allows for a token oracle to set the exchange rate of tokens handed out in payroll * @param _token address of the token * @param _usdExchangeRate exchange rate of the token in USD/token */ function setExchangeRate(address _token, uint256 _usdExchangeRate) public onlyOracle { require(msg.sender == oracle && _usdExchangeRate > 0); exchangeRates[_token] = _usdExchangeRate; ExchangeRateSet(_token, _usdExchangeRate); } }
* @dev scapeHatch allows the owner to take funds so that they are not lost in the contract forever/
function scapeHatch() public onlyOwner { selfdestruct(owner); }
12,792,015
[ 1, 12476, 44, 505, 5360, 326, 3410, 358, 4862, 284, 19156, 1427, 716, 2898, 854, 486, 13557, 316, 326, 6835, 21238, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 888, 1273, 44, 505, 1435, 1071, 1338, 5541, 288, 203, 3639, 365, 5489, 8813, 12, 8443, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: UNLICENSED pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./users.sol"; import "./submits.sol"; import "./papers.sol"; contract ResearchShare is Users, Submits, Papers { /** * Emitted event when a review is require (= paper si submitted) * * @param _ipfsHash paper ipfs hash * @param reviewers reviewer list */ event ReviewRequest( string _ipfsHash, address[] reviewers ); /** * Emitted event when a review is validated * * @param _ipfsHash paper ipfs hash */ event Validation( string _ipfsHash ); mapping(string => bool) ipfsHashToValidationStatus; /** * Deprecated * Generate random number from date using keccak * This is only for tests. Use RANDAO in production instead * @param _x Lower Bound * @param _y Upper Bound * @param _seed seed fo number generation */ function _generateRandomNum(uint _x, uint _y, string memory _seed) private pure returns (uint) { require(_x < _y); uint randVal = uint(keccak256(abi.encodePacked(_seed))) % (_y - _x) + _x; return (randVal); } /** * Find reviewers random reviewers based on their competence fields * * @param _field Corresponding research field * @param _ipfsHash Paper ipfs hash * @param _n Number of reviewers to find **/ function findReviewers(string memory _field, string memory _ipfsHash, uint256 _n) private view returns (address[] memory) { require(fieldToUser[_field].length >= _n, "Not enough reviewer available for this field"); address[] memory reviewers = new address[](_n); address[] storage potentialReviewers = fieldToUser[_field]; uint rand_val = _generateRandomNum(0, potentialReviewers.length, _ipfsHash); for (uint i = 0; i < _n; i++) { reviewers[_n] = (potentialReviewers[rand_val + i]); } return (reviewers); } /** * Answer true if the paper where _ipfsHash is pointing has been validated into this contract * * @param _ipfsHash ipfs hash pointing to the document to certify */ function certPaper(string memory _ipfsHash) public view returns(bool){ return (ipfsHashToValidationStatus[_ipfsHash]); } /** * Creates a Submit and start the Review process. * * @param _ipfsHash Hash of the submitter Paper. * @param _field Research field **/ function submitPaper(string memory _ipfsHash, string memory _field) public { uint submitId = newSubmit(_ipfsHash); address[] memory reviewers = findReviewers(_field, _ipfsHash, 1); addReviewers(submitId, reviewers); emit ReviewRequest(_ipfsHash, reviewers); } /** * Publish the paper on ipfs * * @param _ipfsHash ipfsHash to publish */ function publishPaper(string memory _ipfsHash) private { ipfsHashToValidationStatus[_ipfsHash] = true; } /** * CallBack function called when a review is added * * @param _ipfsHash submit ipfs hash */ function onReview(string memory _ipfsHash) private { uint256 submit_id = submitToId[_ipfsHash]; address[] memory reviewers = submitIdToReviewers[submit_id]; Review[] memory reviews = submitIdToReviews[submit_id]; uint16 validations = 0; for (uint i = 0; i < reviewers.length; ++i) { for (uint j = 0; j < reviews.length; ++j) { if (reviews[j].status == ReviewStatus.Accepted && reviews[j].reviewer == reviewers[i]) { validations += 1; break; } } } if (validations == reviewers.length) { publishPaper(_ipfsHash); emit Validation(_ipfsHash); } } /** * Add a new review to a submit and returns the review's id; * * @param _ipfsHash Hash of the submitted file. * @param _status What the reviewers think should happen next to the submit. * @param _requests Change requests (could be empty) **/ function submitReview(string memory _ipfsHash, ReviewStatus _status, ChangeRequest[] memory _requests) public onlyReviewer(_ipfsHash) returns (uint) { uint id = submitToId[_ipfsHash]; require(id != notSubmitted); Review memory review = createReview(_status, _requests); submitIdToReviews[id].push(review); emit ReviewSubmit(_ipfsHash, msg.sender, _status, _requests); onReview(_ipfsHash); return review.id; } }
* Find reviewers random reviewers based on their competence fields @param _field Corresponding research field @param _ipfsHash Paper ipfs hash @param _n Number of reviewers to find/
function findReviewers(string memory _field, string memory _ipfsHash, uint256 _n) private view returns (address[] memory) { require(fieldToUser[_field].length >= _n, "Not enough reviewer available for this field"); address[] memory reviewers = new address[](_n); address[] storage potentialReviewers = fieldToUser[_field]; uint rand_val = _generateRandomNum(0, potentialReviewers.length, _ipfsHash); return (reviewers); }
14,111,213
[ 1, 3125, 10725, 414, 2744, 10725, 414, 2511, 603, 3675, 25163, 802, 1466, 225, 389, 1518, 9557, 17863, 310, 283, 3072, 652, 225, 389, 625, 2556, 2310, 20971, 2359, 2556, 1651, 225, 389, 82, 3588, 434, 10725, 414, 358, 1104, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1104, 9159, 414, 12, 1080, 3778, 389, 1518, 16, 533, 3778, 389, 625, 2556, 2310, 16, 2254, 5034, 389, 82, 13, 3238, 1476, 1135, 261, 2867, 8526, 3778, 13, 288, 203, 3639, 2583, 12, 1518, 774, 1299, 63, 67, 1518, 8009, 2469, 1545, 389, 82, 16, 315, 1248, 7304, 10725, 264, 2319, 364, 333, 652, 8863, 203, 3639, 1758, 8526, 3778, 10725, 414, 273, 394, 1758, 8526, 24899, 82, 1769, 203, 3639, 1758, 8526, 2502, 8555, 9159, 414, 273, 652, 774, 1299, 63, 67, 1518, 15533, 203, 3639, 2254, 5605, 67, 1125, 273, 389, 7163, 8529, 2578, 12, 20, 16, 8555, 9159, 414, 18, 2469, 16, 389, 625, 2556, 2310, 1769, 203, 3639, 327, 261, 16041, 414, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xa3E2D77D02095d04dE8CFbf34b1C03fC9b24307A/sources/contracts/Marketplacev4.sol
This function is used to update or set the CloudaxNFT Listing price
function setServiceFee(uint256 __serviceFee) public onlyOwner { uint256 oldFee = _serviceFee; _serviceFee = __serviceFee; emit ServiceFeeUpgraded(oldFee, _serviceFee, block.timestamp); }
1,880,430
[ 1, 2503, 445, 353, 1399, 358, 1089, 578, 444, 326, 4396, 651, 50, 4464, 987, 310, 6205, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 30000, 14667, 12, 11890, 5034, 1001, 3278, 14667, 13, 1071, 1338, 5541, 288, 203, 3639, 2254, 5034, 1592, 14667, 273, 389, 3278, 14667, 31, 203, 3639, 389, 3278, 14667, 273, 1001, 3278, 14667, 31, 203, 3639, 3626, 1956, 14667, 1211, 19305, 12, 1673, 14667, 16, 389, 3278, 14667, 16, 1203, 18, 5508, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.1; interface IPoTypes { //------------------------------------------------------------------------ // Purchase Order //------------------------------------------------------------------------ enum PoItemStatus { Initial, // 0 expect never to see this Created, // 1 PO item has been created in the contract | 0->1 managed by buyer waller contract fn call from buyer UI Accepted, // 2 PO item has been accepted by the seller and a corresponding SO item created | 1->2 managed by seller wallet contract fn call from seller UI Rejected, // 3 PO item has been rejected by the seller | 1->3 managed by seller wallet contract fn call from seller UI ReadyForGoodsIssue, // 4 PO item is ready for goods issue | 2->4 managed by seller wallet contract fn call from seller UI GoodsIssued, // 5 PO item has been posted or issued by the seller | 4->5 managed by seller wallet contract fn call from seller UI GoodsReceived, // 6 PO item has been received by the buyer or escrow time exceeded | 5->6 managed by buyer wallet contract fn call from buyer OR po main contract 30 days or Seller UI Completed, // 7 PO item is complete and escrow funds released to the buyer wallet | 6->7 managed by seller wallet contract fn call from seller UI Cancelled // 8 PO item has been successfully cancelled and funds refunded to buyer wallet | 1->8 or 2->8 managed by seller wallet contract fn call from seller UI, at discretion of seller (poss break out into own field of po item payment status) } enum PoItemCancelStatus { Initial, // 0 default to empty, no request made RequestMade, // 1 PO item has had cancellation requested | 0->1 managed by buyer wallet contract fn call from buyer UI RequestRejected, // 2 PO item has had cancellation rejected | 1->2 managed by seller wallet contract fn call from seller UI RequestAccepted // 3 PO item has had cancellation accepted | 1->3 managed by seller wallet contract fn call from seller UI } enum PoType { Initial, // 0 expect never to see this Cash, // 1 PO is paid up front by the buyer Invoice // 2 PO is paid later after buyer receives an invoice } struct PoItem { uint poNumber; // contract managed, PO header key uint8 poItemNumber; // contract managed, PO item key bytes32 soNumber; // seller system (eg eShop) managed (any numbering allowed, could be same as PO number and PO item) bytes32 soItemNumber; // seller system (eg eShop) managed (any numbering allowed, could be same as PO number and PO item) bytes32 productId; // buyer UI managed, product id from product registry uint quantity; // buyer UI managed, regular quantity, eg 4 bytes32 unit; // buyer UI managed, regular quantity units, eg PC pieces (TODO are there ISO codes for this?) bytes32 quantitySymbol; // buyer UI managed, symbol of the ERC20 that represents this productId (assume token quantity same as quantity above) address quantityAddress; // buyer UI managed, contract address of the ERC20 that represents this productId uint currencyValue; // buyer UI managed, value in the units of the ERC20 that is making the payment eg DAI has token precision 18, so 1120000000000000000 DAI is 1.12 USD PoItemStatus status; // contract managed for create, then seller system managed uint goodsIssuedDate; // contract managed at point of goods issue, unix timestamp uint goodsReceivedDate; // contract managed at point of goods received (or time out), unix timestamp uint plannedEscrowReleaseDate; // contract managed at point of goods issue, it is the planned escrow release date = goods issue + escrow days eg 30 days uint actualEscrowReleaseDate; // contract managed at point of successful escrow release bool isEscrowReleased; // contract managed, defaults to false, true when escrow funds released to seller PoItemCancelStatus cancelStatus; // contract managed from buyer UI and seller UI fn calls } struct Po { uint poNumber; // contract managed, PO header key, leave blank at PO creation time address buyerAddress; // buyer UI managed, buyer EoA address handling currency and "owner" of the PO ("finance address") address receiverAddress; // buyer UI managed, buyer EoA address will receive product ownership tokens at end ("logistics address") address buyerWalletAddress; // buyer UI managed, buyer contract address, needed to locate contract whose functions are called by buyer UI bytes32 currencySymbol; // buyer UI managed, symbol of the ERC20 that is making payment, eg DAI address currencyAddress; // buyer UI managed, contract address of the ERC20 that is making payment uint quoteId; // buyer UI managed, a quote signed by seller system, sellerId+quoteId uniquely identifies a single poNumber uint quoteExpiryDate; // buyer UI managed, a quote signed by seller system, sellerId+quoteId uniquely identifies a single poNumber address approverAddress; // contract managed, signer of quote, looked up from seller master data during PO creation PoType poType; // buyer UI managed, specifies what workflow PO will use bytes32 sellerId; // buyer UI managed, allocated by seller admin to uniquely identify their shop uint poCreateDate; // buyer UI managed, po creation unix timestamp uint8 poItemCount; // contract managed, count of line items written to storage PoItem[] poItems; // dynamic array of po items, TODO impose configurable max of eg 16, low enough that contract can iterate all } //------------------------------------------------------------------------ // Seller //------------------------------------------------------------------------ struct Seller { bytes32 sellerId; // uniquely identifies a seller/shop bytes32 sellerDescription; // free text short description address contractAddress; // Contract address of seller wallet, where money sent after a sale address approverAddress; // EoA or contract address, the signer who can a sign a quotation tx to prove shop approves it bool isActive; // flag true if seller is active } }
buyer UI managed, buyer EoA address will receive product ownership tokens at end ("logistics address")
address receiverAddress;
12,612,365
[ 1, 70, 16213, 6484, 7016, 16, 27037, 512, 83, 37, 1758, 903, 6798, 3017, 23178, 2430, 622, 679, 7566, 1330, 4287, 1758, 7923, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1758, 5971, 1887, 31, 5411, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x808d0A6Db89270E5025f3270f937F5c0E654E46a/sources/contracts/ScrapStaking.sol
Interface for Genesis Dysto Apez Contract
interface IDystoGen { function ownerOf(uint256 id) external view returns (address); function transferFrom( address from, address to, uint256 tokenId ) external; }
16,452,179
[ 1, 1358, 364, 31637, 463, 1094, 83, 432, 347, 94, 13456, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 1599, 1094, 83, 7642, 288, 203, 565, 445, 3410, 951, 12, 11890, 5034, 612, 13, 3903, 1476, 1135, 261, 2867, 1769, 203, 203, 565, 445, 7412, 1265, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 565, 262, 3903, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract Z_ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract Z_ERC20 is Z_ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token implementation * @dev Basic version of StandardToken, with no allowances. */ contract Z_BasicToken is Z_ERC20Basic { mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token, implementing transfer by agents * * @dev Implementation of the basic standard token with allowances. * @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 Z_StandardToken is Z_ERC20, Z_BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another by agents within allowance limit * @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 * @return true */ 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] -= _value; balances[_to] += _value; allowed[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; } /** * @dev Transfer tokens from one address to by admin , without any allowance limit * @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 * @return true */ function transferFromByAdmin(address _from, address _to, uint256 _value) internal returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); //require(_value <= 100000); balances[_from] -= _value; balances[_to] += _value; emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. * @return true */ 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 Approve the passed address to spend the specified *additional* 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 _addedValue The additional amount of tokens to be spent. * @return true * 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) */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender] + (_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the allownance quota by the specified amount of tokens * * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to be decreased * @return true */ 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 - (_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and multiple admin addresses, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Z_Ownable { address public owner; mapping (address => bool) internal admin_accounts; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { // set msg.sender as owner owner = msg.sender; // set msg.sender as first administrator admin_accounts[msg.sender]= true; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner ); _; } /** * @dev check if msg.sender is owner * @return true if msg.sender is owner */ function isOwner() internal view returns (bool) { return (msg.sender == owner ); } /** * @dev Throws if called by any account other than admins. */ modifier onlyAdmin() { require (admin_accounts[msg.sender]==true); _; } /** * @dev check if msg.sender is admin * @return true if msg.sender is admin */ function isAdmin() internal view returns (bool) { return (admin_accounts[msg.sender]==true); } } /** @title main contract for NOW token. we should deploy this contract. needs about 5,500,000 gas */ contract NOWToken is Z_StandardToken, Z_Ownable { string public constant name = "NOW Token"; string public constant symbol = "NOW"; uint8 public constant decimals = 18; // token traded in integer amounts, no period // total token supply: 3 billion NOW uint256 internal constant _totalTokenAmount = 3 * (10 ** 9) * (10 ** 18); uint256 internal constant WEI_PER_ETHER= 1000000000000000000; // 10^18 wei = 1 ether uint256 internal constant NUM_OF_SALE_STAGES= 5; // support upto five sale stages // enum type definition for sale status (0 ~ 13) enum Sale_Status { Initialized_STATUS, // 0 Stage0_Sale_Started_STATUS, // 1, stage0 Stage0_Sale_Stopped_STATUS, // 2, stage0 Stage1_Sale_Started_STATUS, // 3, stage1 Stage1_Sale_Stopped_STATUS, // 4, stage1 Stage2_Sale_Started_STATUS, // 5, stage2 Stage2_Sale_Stopped_STATUS, // 6, stage2 Stage3_Sale_Started_STATUS, // 7, stage3 Stage3_Sale_Stopped_STATUS, // 8, stage3 Stage4_Sale_Started_STATUS, // 9, stage4 Stage4_Sale_Stopped_STATUS, // 10, stage4 Public_Allowed_To_Trade_STATUS, // 11 Stage0_Allowed_To_Trade_STATUS, // 12 Closed_STATUS // 13 } // sale status variable: 0 ~ 13 (enum Sale_Status ) Sale_Status public sale_status= Sale_Status.Initialized_STATUS; // sale stage index : 0 ~ 4 ( 0:1~2, 1:3~4, 2:5~6, 3:7~8, 4:9~10) uint256 public sale_stage_index= 0; // 0 ~ 4 for stage0 ~ 4 // initiazlied time uint256 public when_initialized= 0; // timestamp when public trade begins except stage0 uint256 public when_public_allowed_to_trade_started= 0; // timestamp when *all* tokens trade begins including stage0 uint256 public when_stage0_allowed_to_trade_started= 0; // array of sale starting time's timestamp uint256 [NUM_OF_SALE_STAGES] public when_stageN_sale_started; // array of sale stopping time's timestamp uint256 [NUM_OF_SALE_STAGES] public when_stageN_sale_stopped; // sum of all sold tokens uint256 public sold_tokens_total= 0; // sum of ethers received during all token sale stages uint256 public raised_ethers_total= 0; // array of sold tokens per sale stage uint256[NUM_OF_SALE_STAGES] public sold_tokens_per_stage; // array of received ethers per sale stage uint256[NUM_OF_SALE_STAGES] public raised_ethers_per_stage; // target ether amount to gather in each sale stage, when fullfilled, the sale stage automatically forced to stop uint256[NUM_OF_SALE_STAGES] public target_ethers_per_stage= [ 1000 * WEI_PER_ETHER, // stage0 for staff 9882 * WEI_PER_ETHER, // stage1 for black sale 11454 * WEI_PER_ETHER, // stage2 for private sale 11200 * WEI_PER_ETHER, // stage3 for public sale 11667 * WEI_PER_ETHER // stage4 for crowd sale ]; // array of token sale price for each stage (wei per now) uint256[NUM_OF_SALE_STAGES] internal sale_price_per_stage_wei_per_now = [ uint256(1000000000000000000/ uint256(100000)),// stage0 for staff uint256(1000000000000000000/ uint256(38000)), // stage1 for black sale uint256(1000000000000000000/ uint256(23000)), // stage2 for private sale uint256(1000000000000000000/ uint256(17000)), // stage3 for public sale uint256(1000000000000000000/ uint256(10000)) // stage4 for crowd sale ]; // struct definition for token sale history struct history_token_sale_obj { address _buyer; uint256 _ether_value; // in wei uint256 _token_value; // in now token uint256 _when; } // struct definition for token transfer history struct history_token_transfer_obj { address _from; address _to; uint256 _token_value; // in now token uint256 _when; } // struct definition for token burning history struct history_token_burning_obj { address _from; uint256 _token_value_burned; // in now token uint256 _when; } // token sale history for stage 0 ~ 4 history_token_sale_obj[] internal history_token_sale_stage0; history_token_sale_obj[] internal history_token_sale_stage1; history_token_sale_obj[] internal history_token_sale_stage2; history_token_sale_obj[] internal history_token_sale_stage3; history_token_sale_obj[] internal history_token_sale_stage4; // token transfer history history_token_transfer_obj[] internal history_token_transfer; // token burning history history_token_burning_obj[] internal history_token_burning; // token sale amount for each account per stage 0 ~ 4 mapping (address => uint256) internal sale_amount_stage0_account; mapping (address => uint256) internal sale_amount_stage1_account; mapping (address => uint256) internal sale_amount_stage2_account; mapping (address => uint256) internal sale_amount_stage3_account; mapping (address => uint256) internal sale_amount_stage4_account; // array for list of holders and their receiving amounts mapping (address => uint256) internal holders_received_accumul; // array for list of holders accounts (including even inactive holders) address[] public holders; // array for list of sale holders accounts for each sale stage address[] public holders_stage0_sale; address[] public holders_stage1_sale; address[] public holders_stage2_sale; address[] public holders_stage3_sale; address[] public holders_stage4_sale; // array for list of trading holders which are not sale holders address[] public holders_trading; // array for list of burning holders accounts address[] public holders_burned; // array for list of frozen holders accounts address[] public holders_frozen; // burned tokens for each holders account mapping (address => uint256) public burned_amount; // sum of all burned tokens uint256 public totalBurned= 0; // total ether value withdrawed from this contract by contract owner uint256 public totalEtherWithdrawed= 0; // addess to timestamp mapping to mark the account freezing time ( 0 means later unfreezed ) mapping (address => uint256) internal account_frozen_time; // unused mapping (address => mapping (string => uint256)) internal traded_monthly; // cryptocurrency exchange office ether address, for monitorig purpose address[] public cryptocurrency_exchange_company_accounts; ///////////////////////////////////////////////////////////////////////// event AddNewAdministrator(address indexed _admin, uint256 indexed _when); event RemoveAdministrator(address indexed _admin, uint256 indexed _when); /** * @dev add new admin accounts * (run by admin, public function) * @param _newAdmin new admin address */ function z_admin_add_admin(address _newAdmin) public onlyOwner { require(_newAdmin != address(0)); admin_accounts[_newAdmin]=true; emit AddNewAdministrator(_newAdmin, block.timestamp); } /** * @dev remove old admin accounts * (run by admin, public function) * @param _oldAdmin old admin address */ function z_admin_remove_admin(address _oldAdmin) public onlyOwner { require(_oldAdmin != address(0)); require(admin_accounts[_oldAdmin]==true); admin_accounts[_oldAdmin]=false; emit RemoveAdministrator(_oldAdmin, block.timestamp); } event AddNewExchangeAccount(address indexed _exchange_account, uint256 indexed _when); /** * @dev add new exchange office accounts * (run by admin, public function) * @param _exchange_account new exchange address */ function z_admin_add_exchange(address _exchange_account) public onlyAdmin { require(_exchange_account != address(0)); cryptocurrency_exchange_company_accounts.push(_exchange_account); emit AddNewExchangeAccount(_exchange_account, block.timestamp); } event SaleTokenPriceSet(uint256 _stage_index, uint256 _wei_per_now_value, uint256 indexed _when); /** * @dev set new token sale price for current sale stage * (run buy admin, public function) * return _how_many_wei_per_now new token sale price (wei per now) */ function z_admin_set_sale_price(uint256 _how_many_wei_per_now) public onlyAdmin { if(_how_many_wei_per_now == 0) revert(); if(sale_stage_index >= 5) revert(); sale_price_per_stage_wei_per_now[sale_stage_index] = _how_many_wei_per_now; emit SaleTokenPriceSet(sale_stage_index, _how_many_wei_per_now, block.timestamp); } /** * @dev return current or last token sale price * (public view function) * return _sale_price get current token sale price (wei per now) * return _current_sale_stage_index get current sale stage index ( 0 ~ 4) */ function CurrentSalePrice() public view returns (uint256 _sale_price, uint256 _current_sale_stage_index) { if(sale_stage_index >= 5) revert(); _current_sale_stage_index= sale_stage_index; _sale_price= sale_price_per_stage_wei_per_now[sale_stage_index]; } event InitializedStage(uint256 indexed _when); event StartStage0TokenSale(uint256 indexed _when); event StartStage1TokenSale(uint256 indexed _when); event StartStage2TokenSale(uint256 indexed _when); event StartStage3TokenSale(uint256 indexed _when); event StartStage4TokenSale(uint256 indexed _when); /** * @dev start _new_sale_stage_index sale stage * (run by admin ) */ function start_StageN_Sale(uint256 _new_sale_stage_index) internal { if(sale_status==Sale_Status.Initialized_STATUS || sale_stage_index+1<= _new_sale_stage_index) sale_stage_index= _new_sale_stage_index; else revert(); sale_status= Sale_Status(1 + sale_stage_index * 2); // 0=>1, 1=>3, 2=>5, 3=>7, 4=>9 when_stageN_sale_started[sale_stage_index]= block.timestamp; if(sale_stage_index==0) emit StartStage0TokenSale(block.timestamp); if(sale_stage_index==1) emit StartStage1TokenSale(block.timestamp); if(sale_stage_index==2) emit StartStage2TokenSale(block.timestamp); if(sale_stage_index==3) emit StartStage3TokenSale(block.timestamp); if(sale_stage_index==4) emit StartStage4TokenSale(block.timestamp); } event StopStage0TokenSale(uint256 indexed _when); event StopStage1TokenSale(uint256 indexed _when); event StopStage2TokenSale(uint256 indexed _when); event StopStage3TokenSale(uint256 indexed _when); event StopStage4TokenSale(uint256 indexed _when); /** * @dev stop this [_old_sale_stage_index] sale stage * (run by admin ) */ function stop_StageN_Sale(uint256 _old_sale_stage_index) internal { if(sale_stage_index != _old_sale_stage_index) revert(); sale_status= Sale_Status(2 + sale_stage_index * 2); // 0=>2, 1=>4, 2=>6, 3=>8, 4=>10 when_stageN_sale_stopped[sale_stage_index]= block.timestamp; if(sale_stage_index==0) emit StopStage0TokenSale(block.timestamp); if(sale_stage_index==1) emit StopStage1TokenSale(block.timestamp); if(sale_stage_index==2) emit StopStage2TokenSale(block.timestamp); if(sale_stage_index==3) emit StopStage3TokenSale(block.timestamp); if(sale_stage_index==4) emit StopStage4TokenSale(block.timestamp); } event StartTradePublicSaleTokens(uint256 indexed _when); /** * @dev allow stage1~4 token trading * (run by admin ) */ function start_Public_Trade() internal onlyAdmin { // if current sale stage had not been stopped, first stop current active sale stage Sale_Status new_sale_status= Sale_Status(2 + sale_stage_index * 2); if(new_sale_status > sale_status) stop_StageN_Sale(sale_stage_index); sale_status= Sale_Status.Public_Allowed_To_Trade_STATUS; when_public_allowed_to_trade_started= block.timestamp; emit StartTradePublicSaleTokens(block.timestamp); } event StartTradeStage0SaleTokens(uint256 indexed _when); /** * @dev allow stage0 token trading * (run by admin ) */ function start_Stage0_Trade() internal onlyAdmin { if(sale_status!= Sale_Status.Public_Allowed_To_Trade_STATUS) revert(); // allowed 1 year later after stage1 tokens trading is enabled uint32 stage0_locked_year= 1; bool is_debug= false; // change to false if this contract source is release version if(is_debug==false && block.timestamp < stage0_locked_year*365*24*60*60 + when_public_allowed_to_trade_started ) revert(); if(is_debug==true && block.timestamp < stage0_locked_year*10*60 + when_public_allowed_to_trade_started ) revert(); sale_status= Sale_Status.Stage0_Allowed_To_Trade_STATUS; when_stage0_allowed_to_trade_started= block.timestamp; emit StartTradeStage0SaleTokens(block.timestamp); } event CreateTokenContract(uint256 indexed _when); /** * @dev token contract constructor(), initialized tokens supply and sale status variables * (run by owner when contract deploy) */ constructor() public { totalSupply = _totalTokenAmount; balances[msg.sender] = _totalTokenAmount; sale_status= Sale_Status.Initialized_STATUS; sale_stage_index= 0; when_initialized= block.timestamp; holders.push(msg.sender); holders_received_accumul[msg.sender] += _totalTokenAmount; emit Transfer(address(0x0), msg.sender, _totalTokenAmount); emit InitializedStage(block.timestamp); emit CreateTokenContract(block.timestamp); } /** * @dev check if specified token transfer request is valid * ( internal modifier function). * revert if transfer should be NOT allowed, otherwise do nothing * @param _from source account from whom tokens should be transferred * @param _to destination account to whom tokens should be transferred * @param _value number of tokens to be transferred */ modifier validTransaction( address _from, address _to, uint256 _value) { require(_to != address(0x0)); require(_to != _from); require(_value > 0); if(isAdmin()==false) { // if _from is frozen account, disallow this request if(account_frozen_time[_from] > 0) revert(); if(_value == 0 ) revert(); // if token trading is not enabled yet, disallow this request if(sale_status < Sale_Status.Public_Allowed_To_Trade_STATUS) revert(); // if stage0 token trading is not enabled yet, disallow this request if( sale_amount_stage0_account[_from] > 0 ) { if(sale_status < Sale_Status.Stage0_Allowed_To_Trade_STATUS) revert(); } else { } } _; } event TransferToken(address indexed _from_whom,address indexed _to_whom, uint _token_value, uint256 indexed _when); event TransferTokenFrom(address indexed _from_whom,address indexed _to_whom, address _agent, uint _token_value, uint256 indexed _when); event TransferTokenFromByAdmin(address indexed _from_whom,address indexed _to_whom, address _admin, uint _token_value, uint256 indexed _when); /** * @dev transfer specified amount of tokens from my account to _to account * (run by self, public function) * @param _to destination account to whom tokens should be transferred * @param _value number of tokens to be transferred * @return _success report if transfer was successful, on failure revert() */ function transfer(address _to, uint _value) public validTransaction(msg.sender, _to, _value) returns (bool _success) { _success= super.transfer(_to, _value); if(_success==false) revert(); emit TransferToken(msg.sender,_to,_value,block.timestamp); // check if new trading holder if(holders_received_accumul[_to]==0x0) { // new holder comes holders.push(_to); holders_trading.push(_to); emit NewHolderTrading(_to, block.timestamp); } holders_received_accumul[_to] += _value; // leave a transfer history entry history_token_transfer.push( history_token_transfer_obj( { _from: msg.sender, _to: _to, _token_value: _value, _when: block.timestamp } ) ); } /** * @dev transfer specified amount of tokens from _from account to _to account * (run by agent, public function) * @param _from client account who approved transaction performed by this sender as agent * @param _to destination account to whom tokens should be transferred * @param _value number of tokens to be transferred * @return _success report if transfer was successful, on failure revert() */ function transferFrom(address _from, address _to, uint _value) public validTransaction(_from, _to, _value) returns (bool _success) { if(isAdmin()==true) { // admins can transfer tokens of **ANY** accounts emit TransferTokenFromByAdmin(_from,_to,msg.sender,_value,block.timestamp); _success= super.transferFromByAdmin(_from,_to, _value); } else { // approved agents can transfer tokens of their clients (clients shoukd 'approve()' agents first) emit TransferTokenFrom(_from,_to,msg.sender,_value,block.timestamp); _success= super.transferFrom(_from, _to, _value); } if(_success==false) revert(); // check if new trading holder if(holders_received_accumul[_to]==0x0) { // new holder comes holders.push(_to); holders_trading.push(_to); emit NewHolderTrading(_to, block.timestamp); } holders_received_accumul[_to] += _value; // leave a transfer history entry history_token_transfer.push( history_token_transfer_obj( { _from: _from, _to: _to, _token_value: _value, _when: block.timestamp } ) ); } event IssueTokenSale(address indexed _buyer, uint _ether_value, uint _token_value, uint _exchange_rate_now_per_wei, uint256 indexed _when); /** * @dev fallback function for incoming ether, receive ethers and give tokens back */ function () public payable { buy(); } event NewHolderTrading(address indexed _new_comer, uint256 indexed _when); event NewHolderSale(address indexed _new_comer, uint256 indexed _when); /** * @dev buy now tokens by sending some ethers to this contract address * (payable public function ) */ function buy() public payable { if(sale_status < Sale_Status.Stage0_Sale_Started_STATUS) revert(); if(sale_status > Sale_Status.Stage4_Sale_Stopped_STATUS) revert(); if((uint256(sale_status)%2)!=1) revert(); // not in started sale status if(isAdmin()==true) revert(); // admins are not allowed to buy tokens uint256 tokens; uint256 wei_per_now= sale_price_per_stage_wei_per_now[sale_stage_index]; // if sent ether value is less than exch_rate, revert if (msg.value < wei_per_now) revert(); // calculate num of bought tokens based on sent ether value (in wei) tokens = uint256( msg.value / wei_per_now ); if (tokens + sold_tokens_total > totalSupply) revert(); // update token sale statistics per stage if(sale_stage_index==0) sale_amount_stage0_account[msg.sender] += tokens; else if(sale_stage_index==1) sale_amount_stage1_account[msg.sender] += tokens; else if(sale_stage_index==2) sale_amount_stage2_account[msg.sender] += tokens; else if(sale_stage_index==3) sale_amount_stage3_account[msg.sender] += tokens; else if(sale_stage_index==4) sale_amount_stage4_account[msg.sender] += tokens; sold_tokens_per_stage[sale_stage_index] += tokens; sold_tokens_total += tokens; // update ether statistics raised_ethers_per_stage[sale_stage_index] += msg.value; raised_ethers_total += msg.value; super.transferFromByAdmin(owner, msg.sender, tokens); // check if this holder is new if(holders_received_accumul[msg.sender]==0x0) { // new holder comes holders.push(msg.sender); if(sale_stage_index==0) holders_stage0_sale.push(msg.sender); else if(sale_stage_index==1) holders_stage1_sale.push(msg.sender); else if(sale_stage_index==2) holders_stage2_sale.push(msg.sender); else if(sale_stage_index==3) holders_stage3_sale.push(msg.sender); else if(sale_stage_index==4) holders_stage4_sale.push(msg.sender); emit NewHolderSale(msg.sender, block.timestamp); } holders_received_accumul[msg.sender] += tokens; // leave a token sale history entry history_token_sale_obj memory history = history_token_sale_obj( { _buyer: msg.sender, _ether_value: msg.value, _token_value: tokens, _when: block.timestamp } ); if(sale_stage_index==0) history_token_sale_stage0.push( history ); else if(sale_stage_index==1) history_token_sale_stage1.push( history ); else if(sale_stage_index==2) history_token_sale_stage2.push( history ); else if(sale_stage_index==3) history_token_sale_stage3.push( history ); else if(sale_stage_index==4) history_token_sale_stage4.push( history ); emit IssueTokenSale(msg.sender, msg.value, tokens, wei_per_now, block.timestamp); // if target ether is reached, stop this sale stage if( target_ethers_per_stage[sale_stage_index] <= raised_ethers_per_stage[sale_stage_index]) stop_StageN_Sale(sale_stage_index); } event FreezeAccount(address indexed _account_to_freeze, uint256 indexed _when); event UnfreezeAccount(address indexed _account_to_unfreeze, uint256 indexed _when); /** * @dev freeze a holder account, prohibit further token transfer * (run by ADMIN, public function) * @param _account_to_freeze account to freeze */ function z_admin_freeze(address _account_to_freeze) public onlyAdmin { account_frozen_time[_account_to_freeze]= block.timestamp; holders_frozen.push(_account_to_freeze); emit FreezeAccount(_account_to_freeze,block.timestamp); } /** * @dev unfreeze a holder account * (run by ADMIN, public function) * @param _account_to_unfreeze account to unfreeze (previously frozen) */ function z_admin_unfreeze(address _account_to_unfreeze) public onlyAdmin { account_frozen_time[_account_to_unfreeze]= 0; // reset time to zero emit UnfreezeAccount(_account_to_unfreeze,block.timestamp); } event CloseTokenContract(uint256 indexed _when); /** * @dev close this contract after burning all tokens * (run by ADMIN, public function ) */ function closeContract() onlyAdmin internal { if(sale_status < Sale_Status.Stage0_Allowed_To_Trade_STATUS) revert(); if(totalSupply > 0) revert(); address ScAddress = this; emit CloseTokenContract(block.timestamp); emit WithdrawEther(owner,ScAddress.balance,block.timestamp); selfdestruct(owner); } /** * @dev retrieve contract's ether balance info * (public view function) * @return _current_ether_balane current contract ethereum balance ( in wei unit) * @return _ethers_withdrawn withdrawen ethers in wei * @return _ethers_raised_total total ethers gathered from token sale */ function ContractEtherBalance() public view returns ( uint256 _current_ether_balance, uint256 _ethers_withdrawn, uint256 _ethers_raised_total ) { _current_ether_balance= address(this).balance; _ethers_withdrawn= totalEtherWithdrawed; _ethers_raised_total= raised_ethers_total; } event WithdrawEther(address indexed _addr, uint256 _value, uint256 indexed _when); /** * @dev transfer this contract ether balance to owner's account * ( public function ) * @param _withdraw_wei_value amount to widthdraw ( in wei unit) */ function z_admin_withdraw_ether(uint256 _withdraw_wei_value) onlyAdmin public { address ScAddress = this; if(_withdraw_wei_value > ScAddress.balance) revert(); //if(owner.call.value(_withdraw_wei_value).gas(5000)()==false) revert(); if(owner.send(_withdraw_wei_value)==false) revert(); totalEtherWithdrawed += _withdraw_wei_value; emit WithdrawEther(owner,_withdraw_wei_value,block.timestamp); } /** * @dev return list of active holders accounts and their balances * ( public view function ) * @param _max_num_of_items_to_display Max Number of latest accounts items to display ( 0 means 1 ) * @return _num_of_active_holders number of latest holders accounts * @return _active_holders array of active( balance > 0) holders * @return _token_balances array of token balances */ function list_active_holders_and_balances(uint _max_num_of_items_to_display) public view returns (uint _num_of_active_holders,address[] _active_holders,uint[] _token_balances){ uint len = holders.length; _num_of_active_holders = 0; if(_max_num_of_items_to_display==0) _max_num_of_items_to_display=1; for (uint i = len-1 ; i >= 0 ; i--) { if( balances[ holders[i] ] != 0x0) _num_of_active_holders++; if(_max_num_of_items_to_display == _num_of_active_holders) break; } _active_holders = new address[](_num_of_active_holders); _token_balances = new uint[](_num_of_active_holders); uint num=0; for (uint j = len-1 ; j >= 0 && _num_of_active_holders > num ; j--) { address addr = holders[j]; if( balances[ addr ] == 0x0) continue; // assure balance > 0 _active_holders[num] = addr; _token_balances[num] = balances[addr]; num++; } } /** * @dev return list of recent stage0 token sale history * ( public view function ) * @param _max_num_of_items_to_display Max Number of latest history items to display ( 0 means 1 ) * @return _num number of latest token sale history items * @return _sale_holders array of holders * @return _ethers array of ethers paid * @return _tokens array of tokens bought * @return _whens array of sale times */ function list_history_of_stage0_sale(uint _max_num_of_items_to_display) public view returns (uint _num,address[] _sale_holders,uint[] _ethers,uint[] _tokens,uint[] _whens){ uint len = history_token_sale_stage0.length; uint n= len; if(_max_num_of_items_to_display == 0) _max_num_of_items_to_display= 1; if(_max_num_of_items_to_display < n) n= _max_num_of_items_to_display; _sale_holders = new address[](n); _ethers = new uint[](n); _tokens = new uint[](n); _whens = new uint[](n); _num=0; for (uint j = len-1 ; j >= 0 && n > _num ; j--) { history_token_sale_obj storage obj= history_token_sale_stage0[j]; _sale_holders[_num]= obj._buyer; _ethers[_num]= obj._ether_value; _tokens[_num]= obj._token_value; _whens[_num]= obj._when; _num++; } } /** * @dev return list of recent stage1 token sale history * ( public view function ) * @param _max_num_of_items_to_display Max Number of latest history items to display ( 0 means 1 ) * @return _num number of latest token sale history items * @return _sale_holders array of holders * @return _ethers array of ethers paid * @return _tokens array of tokens bought * @return _whens array of sale times */ function list_history_of_stage1_sale(uint _max_num_of_items_to_display) public view returns (uint _num,address[] _sale_holders,uint[] _ethers,uint[] _tokens,uint[] _whens){ uint len = history_token_sale_stage1.length; uint n= len; if(_max_num_of_items_to_display == 0) _max_num_of_items_to_display= 1; if(_max_num_of_items_to_display < n) n= _max_num_of_items_to_display; _sale_holders = new address[](n); _ethers = new uint[](n); _tokens = new uint[](n); _whens = new uint[](n); _num=0; for (uint j = len-1 ; j >= 0 && n > _num ; j--) { history_token_sale_obj storage obj= history_token_sale_stage1[j]; _sale_holders[_num]= obj._buyer; _ethers[_num]= obj._ether_value; _tokens[_num]= obj._token_value; _whens[_num]= obj._when; _num++; } } /** * @dev return list of recent stage2 token sale history * ( public view function ) * @param _max_num_of_items_to_display Max Number of latest history items to display ( 0 means 1 ) * @return _num number of latest token sale history items * @return _sale_holders array of holders * @return _ethers array of ethers paid * @return _tokens array of tokens bought * @return _whens array of sale times */ function list_history_of_stage2_sale(uint _max_num_of_items_to_display) public view returns (uint _num,address[] _sale_holders,uint[] _ethers,uint[] _tokens,uint[] _whens){ uint len = history_token_sale_stage2.length; uint n= len; if(_max_num_of_items_to_display == 0) _max_num_of_items_to_display= 1; if(_max_num_of_items_to_display < n) n= _max_num_of_items_to_display; _sale_holders = new address[](n); _ethers = new uint[](n); _tokens = new uint[](n); _whens = new uint[](n); _num=0; for (uint j = len-1 ; j >= 0 && n > _num ; j--) { history_token_sale_obj storage obj= history_token_sale_stage2[j]; _sale_holders[_num]= obj._buyer; _ethers[_num]= obj._ether_value; _tokens[_num]= obj._token_value; _whens[_num]= obj._when; _num++; } } /** * @dev return list of recent stage3 token sale history * ( public view function ) * @param _max_num_of_items_to_display Max Number of latest history items to display ( 0 means 1 ) * @return _num number of latest token sale history items * @return _sale_holders array of holders * @return _ethers array of ethers paid * @return _tokens array of tokens bought * @return _whens array of sale times */ function list_history_of_stage3_sale(uint _max_num_of_items_to_display) public view returns (uint _num,address[] _sale_holders,uint[] _ethers,uint[] _tokens,uint[] _whens){ uint len = history_token_sale_stage3.length; uint n= len; if(_max_num_of_items_to_display == 0) _max_num_of_items_to_display= 1; if(_max_num_of_items_to_display < n) n= _max_num_of_items_to_display; _sale_holders = new address[](n); _ethers = new uint[](n); _tokens = new uint[](n); _whens = new uint[](n); _num=0; for (uint j = len-1 ; j >= 0 && n > _num ; j--) { history_token_sale_obj storage obj= history_token_sale_stage3[j]; _sale_holders[_num]= obj._buyer; _ethers[_num]= obj._ether_value; _tokens[_num]= obj._token_value; _whens[_num]= obj._when; _num++; } } /** * @dev return list of recent stage4 token sale history * ( public view function ) * @param _max_num_of_items_to_display Max Number of latest history items to display ( 0 means 1 ) * @return _num number of latest token sale history items * @return _sale_holders array of holders * @return _ethers array of ethers paid * @return _tokens array of tokens bought * @return _whens array of sale times */ function list_history_of_stage4_sale(uint _max_num_of_items_to_display) public view returns (uint _num,address[] _sale_holders,uint[] _ethers,uint[] _tokens,uint[] _whens){ uint len = history_token_sale_stage4.length; uint n= len; if(_max_num_of_items_to_display == 0) _max_num_of_items_to_display= 1; if(_max_num_of_items_to_display < n) n= _max_num_of_items_to_display; _sale_holders = new address[](n); _ethers = new uint[](n); _tokens = new uint[](n); _whens = new uint[](n); _num=0; for (uint j = len-1 ; j >= 0 && n > _num ; j--) { history_token_sale_obj storage obj= history_token_sale_stage4[j]; _sale_holders[_num]= obj._buyer; _ethers[_num]= obj._ether_value; _tokens[_num]= obj._token_value; _whens[_num]= obj._when; _num++; } } /** * @dev return list of latest #N transfer history * ( public view function ) * @param _max_num_of_items_to_display Max Number of latest history items to display ( 0 means 1 ) * @return _num number of latest transfer history items * @return _senders array of senders * @return _receivers array of receivers * @return _tokens array of tokens transferred * @return _whens array of transfer times */ function list_history_of_token_transfer(uint _max_num_of_items_to_display) public view returns (uint _num,address[] _senders,address[] _receivers,uint[] _tokens,uint[] _whens){ uint len = history_token_transfer.length; uint n= len; if(_max_num_of_items_to_display == 0) _max_num_of_items_to_display= 1; if(_max_num_of_items_to_display < n) n= _max_num_of_items_to_display; _senders = new address[](n); _receivers = new address[](n); _tokens = new uint[](n); _whens = new uint[](n); _num=0; for (uint j = len-1 ; j >= 0 && n > _num ; j--) { history_token_transfer_obj storage obj= history_token_transfer[j]; _senders[_num]= obj._from; _receivers[_num]= obj._to; _tokens[_num]= obj._token_value; _whens[_num]= obj._when; _num++; } } /** * @dev return list of latest address-filtered #N transfer history * ( public view function ) * @param _addr address as filter for transfer history (default 0x0) * @return _num number of latest transfer history items * @return _senders array of senders * @return _receivers array of receivers * @return _tokens array of tokens transferred * @return _whens array of transfer times */ function list_history_of_token_transfer_filtered_by_addr(address _addr) public view returns (uint _num,address[] _senders,address[] _receivers,uint[] _tokens,uint[] _whens){ uint len = history_token_transfer.length; uint _max_num_of_items_to_display= 0; history_token_transfer_obj storage obj= history_token_transfer[0]; uint j; for (j = len-1 ; j >= 0 ; j--) { obj= history_token_transfer[j]; if(obj._from== _addr || obj._to== _addr) _max_num_of_items_to_display++; } if(_max_num_of_items_to_display == 0) _max_num_of_items_to_display= 1; _senders = new address[](_max_num_of_items_to_display); _receivers = new address[](_max_num_of_items_to_display); _tokens = new uint[](_max_num_of_items_to_display); _whens = new uint[](_max_num_of_items_to_display); _num=0; for (j = len-1 ; j >= 0 && _max_num_of_items_to_display > _num ; j--) { obj= history_token_transfer[j]; if(obj._from!= _addr && obj._to!= _addr) continue; _senders[_num]= obj._from; _receivers[_num]= obj._to; _tokens[_num]= obj._token_value; _whens[_num]= obj._when; _num++; } } /** * @dev return frozen accounts and their balances * ( public view function ) * @param _max_num_of_items_to_display Max Number of items to display ( 0 means 1 ) * @return _num number of currently frozen accounts * @return _frozen_holders array of frozen accounts * @return _whens array of frozen times */ function list_frozen_accounts(uint _max_num_of_items_to_display) public view returns (uint _num,address[] _frozen_holders,uint[] _whens){ uint len = holders_frozen.length; uint num_of_frozen_holders = 0; if(_max_num_of_items_to_display==0) _max_num_of_items_to_display=1; for (uint i = len-1 ; i >= 0 ; i--) { // assure currently in frozen state if( account_frozen_time[ holders_frozen[i] ] > 0x0) num_of_frozen_holders++; if(_max_num_of_items_to_display == num_of_frozen_holders) break; } _frozen_holders = new address[](num_of_frozen_holders); _whens = new uint[](num_of_frozen_holders); _num=0; for (uint j = len-1 ; j >= 0 && num_of_frozen_holders > _num ; j--) { address addr= holders_frozen[j]; uint256 when= account_frozen_time[ addr ]; if( when == 0x0) continue; // assure if frozen true _frozen_holders[_num]= addr; _whens[_num]= when; _num++; } } /** * @dev Token sale sumilation for current sale stage * ( public view function ) * @param _ether_or_wei_value input ethereum value (in wei or ether unit) * @return _num_of_tokens number of tokens that can be bought with the input value * @return _exch_rate current sale stage exchange rate (wei per now) * @return _current_sale_stage_index current sale stage index */ function simulate_token_sale(uint _ether_or_wei_value) public view returns (uint256 _num_of_tokens, uint256 _exch_rate, uint256 _current_sale_stage_index) { if(sale_stage_index >=5 ) return (0,0,0); _exch_rate= sale_price_per_stage_wei_per_now[sale_stage_index]; _current_sale_stage_index= sale_stage_index; // determine whether the input value is in ether unit or in wei unit if(_ether_or_wei_value>=1000000) _num_of_tokens= uint256( _ether_or_wei_value / _exch_rate ); // guess it is in wei else _num_of_tokens= uint256( _ether_or_wei_value * WEI_PER_ETHER / _exch_rate ); // guess it is in ether } /** * @dev Admin menu: Token Sale Status management * (run by admin, public function) * @param _next_status next status index (1 ~ 13). refer to enum Sale_Status */ function z_admin_next_status(Sale_Status _next_status) onlyAdmin public { if(_next_status== Sale_Status.Stage0_Sale_Started_STATUS) { start_StageN_Sale(0); return;} // 1 if(_next_status== Sale_Status.Stage0_Sale_Stopped_STATUS) { stop_StageN_Sale(0); return;} // 2 if(_next_status== Sale_Status.Stage1_Sale_Started_STATUS) { start_StageN_Sale(1); return;} // 3 if(_next_status== Sale_Status.Stage1_Sale_Stopped_STATUS) { stop_StageN_Sale(1); return;} // 4 if(_next_status== Sale_Status.Stage2_Sale_Started_STATUS) { start_StageN_Sale(2); return;} // 5 if(_next_status== Sale_Status.Stage2_Sale_Stopped_STATUS) { stop_StageN_Sale(2); return;} // 6 if(_next_status== Sale_Status.Stage3_Sale_Started_STATUS) { start_StageN_Sale(3); return;} // 7 if(_next_status== Sale_Status.Stage3_Sale_Stopped_STATUS) { stop_StageN_Sale(3); return;} // 8 if(_next_status== Sale_Status.Stage4_Sale_Started_STATUS) { start_StageN_Sale(4); return;} // 9 if(_next_status== Sale_Status.Stage4_Sale_Stopped_STATUS) { stop_StageN_Sale(4); return;} // 10 if(_next_status== Sale_Status.Public_Allowed_To_Trade_STATUS) { start_Public_Trade(); return;} //11 if(_next_status== Sale_Status.Stage0_Allowed_To_Trade_STATUS) { start_Stage0_Trade(); return;} //12 if(_next_status== Sale_Status.Closed_STATUS) { closeContract(); return;} //13 revert(); } }
* @dev return list of recent stage3 token sale history ( public view function ) @param _max_num_of_items_to_display Max Number of latest history items to display ( 0 means 1 ) @return _num number of latest token sale history items @return _sale_holders array of holders @return _ethers array of ethers paid @return _tokens array of tokens bought @return _whens array of sale times/
function list_history_of_stage3_sale(uint _max_num_of_items_to_display) public view returns (uint _num,address[] _sale_holders,uint[] _ethers,uint[] _tokens,uint[] _whens){ uint len = history_token_sale_stage3.length; uint n= len; if(_max_num_of_items_to_display == 0) _max_num_of_items_to_display= 1; if(_max_num_of_items_to_display < n) n= _max_num_of_items_to_display; _sale_holders = new address[](n); _ethers = new uint[](n); _tokens = new uint[](n); _whens = new uint[](n); _num=0; for (uint j = len-1 ; j >= 0 && n > _num ; j--) { history_token_sale_obj storage obj= history_token_sale_stage3[j]; _sale_holders[_num]= obj._buyer; _ethers[_num]= obj._ether_value; _tokens[_num]= obj._token_value; _whens[_num]= obj._when; _num++; } }
13,028,587
[ 1, 2463, 225, 666, 434, 8399, 6009, 23, 1147, 272, 5349, 4927, 377, 261, 1071, 1476, 445, 262, 225, 389, 1896, 67, 2107, 67, 792, 67, 3319, 67, 869, 67, 5417, 282, 4238, 3588, 434, 4891, 4927, 1516, 358, 2562, 261, 374, 4696, 404, 262, 327, 225, 389, 2107, 282, 1300, 434, 4891, 1147, 272, 5349, 4927, 1516, 327, 225, 389, 87, 5349, 67, 9000, 282, 526, 434, 366, 4665, 327, 225, 389, 546, 414, 282, 526, 434, 13750, 414, 30591, 327, 225, 389, 7860, 282, 526, 434, 2430, 800, 9540, 327, 225, 389, 3350, 773, 282, 526, 434, 272, 5349, 4124, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 666, 67, 8189, 67, 792, 67, 12869, 23, 67, 87, 5349, 12, 11890, 389, 1896, 67, 2107, 67, 792, 67, 3319, 67, 869, 67, 5417, 13, 1071, 1476, 7010, 1377, 1135, 261, 11890, 389, 2107, 16, 2867, 8526, 389, 87, 5349, 67, 9000, 16, 11890, 8526, 389, 546, 414, 16, 11890, 8526, 389, 7860, 16, 11890, 8526, 389, 3350, 773, 15329, 203, 1377, 2254, 562, 273, 4927, 67, 2316, 67, 87, 5349, 67, 12869, 23, 18, 2469, 31, 203, 1377, 2254, 290, 33, 562, 31, 7010, 1377, 309, 24899, 1896, 67, 2107, 67, 792, 67, 3319, 67, 869, 67, 5417, 422, 374, 13, 389, 1896, 67, 2107, 67, 792, 67, 3319, 67, 869, 67, 5417, 33, 404, 31, 203, 1377, 309, 24899, 1896, 67, 2107, 67, 792, 67, 3319, 67, 869, 67, 5417, 411, 225, 290, 13, 290, 33, 389, 1896, 67, 2107, 67, 792, 67, 3319, 67, 869, 67, 5417, 31, 203, 1377, 389, 87, 5349, 67, 9000, 273, 394, 1758, 8526, 12, 82, 1769, 203, 1377, 389, 546, 414, 273, 394, 2254, 8526, 12, 82, 1769, 203, 1377, 389, 7860, 273, 394, 2254, 8526, 12, 82, 1769, 203, 1377, 389, 3350, 773, 273, 394, 2254, 8526, 12, 82, 1769, 203, 1377, 389, 2107, 33, 20, 31, 203, 1377, 364, 261, 11890, 525, 273, 562, 17, 21, 274, 525, 1545, 374, 597, 290, 405, 389, 2107, 274, 525, 413, 13, 288, 203, 540, 4927, 67, 2316, 67, 87, 5349, 67, 2603, 2502, 1081, 33, 4927, 67, 2316, 67, 87, 5349, 67, 2 ]
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlEnumerableUpgradeable.sol"; import "./AccessControlUpgradeable.sol"; import "../utils/structs/EnumerableSetUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable { function __AccessControlEnumerable_init() internal onlyInitializing { } function __AccessControlEnumerable_init_unchained() internal onlyInitializing { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {_grantRole} to track enumerable memberships */ function _grantRole(bytes32 role, address account) internal virtual override { super._grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {_revokeRole} to track enumerable memberships */ function _revokeRole(bytes32 role, address account) internal virtual override { super._revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal onlyInitializing { } function __AccessControl_init_unchained() internal onlyInitializing { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable { /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) external view returns (address); /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @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 * ==== * * [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 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; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) 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 EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol) pragma solidity ^0.8.0; import "./draft-IERC20Permit.sol"; import "../ERC20.sol"; import "../../../utils/cryptography/draft-EIP712.sol"; import "../../../utils/cryptography/ECDSA.sol"; import "../../../utils/Counters.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") {} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (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/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol) pragma solidity ^0.8.0; import "./ECDSA.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; address private immutable _CACHED_THIS; 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) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _CACHED_THIS = address(this); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, 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 ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { ERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol"; import { Token } from "../token/Token.sol"; import { ERC20Burnable } from "../token/ERC20Burnable.sol"; import { IVersioned } from "../utility/interfaces/IVersioned.sol"; import { Owned } from "../utility/Owned.sol"; import { Utils } from "../utility/Utils.sol"; import { IPoolToken } from "./interfaces/IPoolToken.sol"; /** * @dev Pool Token contract */ contract PoolToken is IPoolToken, ERC20Permit, ERC20Burnable, Owned, Utils { Token private immutable _reserveToken; uint8 private _decimals; /** * @dev initializes a new PoolToken contract */ constructor( string memory name, string memory symbol, uint8 initDecimals, Token initReserveToken ) ERC20(name, symbol) ERC20Permit(name) validAddress(address(initReserveToken)) { _decimals = initDecimals; _reserveToken = initReserveToken; } /** * @inheritdoc IVersioned */ function version() external pure returns (uint16) { return 1; } /** * @dev returns the number of decimals used to get its user representation */ function decimals() public view virtual override returns (uint8) { return _decimals; } /** * @inheritdoc IPoolToken */ function reserveToken() external view returns (Token) { return _reserveToken; } /** * @inheritdoc IPoolToken */ function mint(address recipient, uint256 amount) external onlyOwner validExternalAddress(recipient) { _mint(recipient, amount); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { Token } from "../token/Token.sol"; import { TokenLibrary } from "../token/TokenLibrary.sol"; import { IVersioned } from "../utility/interfaces/IVersioned.sol"; import { Upgradeable } from "../utility/Upgradeable.sol"; import { Utils } from "../utility/Utils.sol"; import { IPoolTokenFactory } from "./interfaces/IPoolTokenFactory.sol"; import { IPoolToken } from "./interfaces/IPoolToken.sol"; import { PoolToken } from "./PoolToken.sol"; /** * @dev Pool Token Factory contract */ contract PoolTokenFactory is IPoolTokenFactory, Upgradeable, Utils { using TokenLibrary for Token; string private constant POOL_TOKEN_SYMBOL_PREFIX = "bn"; string private constant POOL_TOKEN_NAME_PREFIX = "Bancor"; string private constant POOL_TOKEN_NAME_SUFFIX = "Pool Token"; // a mapping between tokens and custom symbol overrides (only needed for tokens with malformed symbol property) mapping(Token => string) private _tokenSymbolOverrides; // a mapping between tokens and custom token overrides (only needed for tokens with malformed decimals property) mapping(Token => uint8) private _tokenDecimalsOverrides; // upgrade forward-compatibility storage gap uint256[MAX_GAP - 2] private __gap; /** * @dev triggered when a pool token is created */ event PoolTokenCreated(IPoolToken indexed poolToken, Token indexed token); /** * @dev fully initializes the contract and its parents */ function initialize() external initializer { __PoolTokenFactory_init(); } // solhint-disable func-name-mixedcase /** * @dev initializes the contract and its parents */ function __PoolTokenFactory_init() internal onlyInitializing { __Upgradeable_init(); __PoolTokenFactory_init_unchained(); } /** * @dev performs contract-specific initialization */ function __PoolTokenFactory_init_unchained() internal onlyInitializing {} // solhint-enable func-name-mixedcase /** * @inheritdoc Upgradeable */ function version() public pure override(IVersioned, Upgradeable) returns (uint16) { return 1; } /** * @inheritdoc IPoolTokenFactory */ function tokenSymbolOverride(Token token) external view returns (string memory) { return _tokenSymbolOverrides[token]; } /** * @dev sets the custom symbol override for a given reserve token * * requirements: * * - the caller must be the admin of the contract */ function setTokenSymbolOverride(Token token, string calldata symbol) external onlyAdmin { _tokenSymbolOverrides[token] = symbol; } /** * @inheritdoc IPoolTokenFactory */ function tokenDecimalsOverride(Token token) external view returns (uint8) { return _tokenDecimalsOverrides[token]; } /** * @dev sets the decimals override for a given reserve token * * requirements: * * - the caller must be the admin of the contract */ function setTokenDecimalsOverride(Token token, uint8 decimals) external onlyAdmin { _tokenDecimalsOverrides[token] = decimals; } /** * @inheritdoc IPoolTokenFactory */ function createPoolToken(Token token) external validAddress(address(token)) returns (IPoolToken) { string memory customSymbol = _tokenSymbolOverrides[token]; string memory tokenSymbol = bytes(customSymbol).length != 0 ? customSymbol : token.symbol(); uint8 customDecimals = _tokenDecimalsOverrides[token]; uint8 tokenDecimals = customDecimals != 0 ? customDecimals : token.decimals(); string memory symbol = string.concat(POOL_TOKEN_SYMBOL_PREFIX, tokenSymbol); string memory name = string.concat(POOL_TOKEN_NAME_PREFIX, " ", tokenSymbol, " ", POOL_TOKEN_NAME_SUFFIX); PoolToken newPoolToken = new PoolToken(name, symbol, tokenDecimals, token); // make sure to transfer the ownership to the caller newPoolToken.transferOwnership(msg.sender); emit PoolTokenCreated({ poolToken: newPoolToken, token: token }); return newPoolToken; } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol"; import { IERC20Burnable } from "../../token/interfaces/IERC20Burnable.sol"; import { Token } from "../../token/Token.sol"; import { IVersioned } from "../../utility/interfaces/IVersioned.sol"; import { IOwned } from "../../utility/interfaces/IOwned.sol"; /** * @dev Pool Token interface */ interface IPoolToken is IVersioned, IOwned, IERC20, IERC20Permit, IERC20Burnable { /** * @dev returns the address of the reserve token */ function reserveToken() external view returns (Token); /** * @dev increases the token supply and sends the new tokens to the given account * * requirements: * * - the caller must be the owner of the contract */ function mint(address recipient, uint256 amount) external; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { Token } from "../../token/Token.sol"; import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol"; import { IPoolToken } from "./IPoolToken.sol"; /** * @dev Pool Token Factory interface */ interface IPoolTokenFactory is IUpgradeable { /** * @dev returns the custom symbol override for a given reserve token */ function tokenSymbolOverride(Token token) external view returns (string memory); /** * @dev returns the custom decimals override for a given reserve token */ function tokenDecimalsOverride(Token token) external view returns (uint8); /** * @dev creates a pool token for the specified token */ function createPoolToken(Token token) external returns (IPoolToken); } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { IERC20Burnable } from "./interfaces/IERC20Burnable.sol"; /** * @dev this is an adapted clone of the OZ's ERC20Burnable extension which is unfortunately required so that it can be * explicitly specified in interfaces via our new IERC20Burnable interface. * * We have also removed the explicit use of Context and updated the code to our style. */ abstract contract ERC20Burnable is ERC20, IERC20Burnable { /** * @inheritdoc IERC20Burnable */ function burn(uint256 amount) external virtual { _burn(msg.sender, amount); } /** * @inheritdoc IERC20Burnable */ function burnFrom(address recipient, uint256 amount) external virtual { _approve(recipient, msg.sender, allowance(recipient, msg.sender) - amount); _burn(recipient, amount); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /** * @dev extends the SafeERC20 library with additional operations */ library SafeERC20Ex { using SafeERC20 for IERC20; /** * @dev ensures that the spender has sufficient allowance */ function ensureApprove( IERC20 token, address spender, uint256 amount ) internal { if (amount == 0) { return; } uint256 allowance = token.allowance(address(this), spender); if (allowance >= amount) { return; } if (allowance > 0) { token.safeApprove(spender, 0); } token.safeApprove(spender, amount); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; /** * @dev the main purpose of the Token interfaces is to ensure artificially that we won't use ERC20's standard functions, * but only their safe versions, which are provided by SafeERC20 and SafeERC20Ex via the TokenLibrary contract */ interface Token { } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { IERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol"; import { SafeERC20Ex } from "./SafeERC20Ex.sol"; import { Token } from "./Token.sol"; struct Signature { uint8 v; bytes32 r; bytes32 s; } /** * @dev This library implements ERC20 and SafeERC20 utilities for both the native token and for ERC20 tokens */ library TokenLibrary { using SafeERC20 for IERC20; using SafeERC20Ex for IERC20; error PermitUnsupported(); // the address that represents the native token reserve address public constant NATIVE_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // the symbol that represents the native token string private constant NATIVE_TOKEN_SYMBOL = "ETH"; // the decimals for the native token uint8 private constant NATIVE_TOKEN_DECIMALS = 18; /** * @dev returns whether the provided token represents an ERC20 or the native token reserve */ function isNative(Token token) internal pure returns (bool) { return address(token) == NATIVE_TOKEN_ADDRESS; } /** * @dev returns the symbol of the native token/ERC20 token */ function symbol(Token token) internal view returns (string memory) { if (isNative(token)) { return NATIVE_TOKEN_SYMBOL; } return toERC20(token).symbol(); } /** * @dev returns the decimals of the native token/ERC20 token */ function decimals(Token token) internal view returns (uint8) { if (isNative(token)) { return NATIVE_TOKEN_DECIMALS; } return toERC20(token).decimals(); } /** * @dev returns the balance of the native token/ERC20 token */ function balanceOf(Token token, address account) internal view returns (uint256) { if (isNative(token)) { return account.balance; } return toIERC20(token).balanceOf(account); } /** * @dev transfers a specific amount of the native token/ERC20 token */ function safeTransfer( Token token, address to, uint256 amount ) internal { if (amount == 0) { return; } if (isNative(token)) { payable(to).transfer(amount); } else { toIERC20(token).safeTransfer(to, amount); } } /** * @dev transfers a specific amount of the native token/ERC20 token from a specific holder using the allowance mechanism * * note that the function does not perform any action if the native token is provided */ function safeTransferFrom( Token token, address from, address to, uint256 amount ) internal { if (amount == 0 || isNative(token)) { return; } toIERC20(token).safeTransferFrom(from, to, amount); } /** * @dev approves a specific amount of the native token/ERC20 token from a specific holder * * note that the function does not perform any action if the native token is provided */ function safeApprove( Token token, address spender, uint256 amount ) internal { if (isNative(token)) { return; } toIERC20(token).safeApprove(spender, amount); } /** * @dev ensures that the spender has sufficient allowance * * note that the function does not perform any action if the native token is provided */ function ensureApprove( Token token, address spender, uint256 amount ) internal { if (isNative(token)) { return; } toIERC20(token).ensureApprove(spender, amount); } /** * @dev performs an EIP2612 permit */ function permit( Token token, address owner, address spender, uint256 tokenAmount, uint256 deadline, Signature memory signature ) internal { if (isNative(token)) { revert PermitUnsupported(); } // permit the amount the owner is trying to deposit. Please note, that if the base token doesn't support // EIP2612 permit - either this call or the inner safeTransferFrom will revert IERC20Permit(address(token)).permit( owner, spender, tokenAmount, deadline, signature.v, signature.r, signature.s ); } /** * @dev compares between a token and another raw ERC20 token */ function isEqual(Token token, IERC20 erc20Token) internal pure returns (bool) { return toIERC20(token) == erc20Token; } /** * @dev utility function that converts an token to an IERC20 */ function toIERC20(Token token) internal pure returns (IERC20) { return IERC20(address(token)); } /** * @dev utility function that converts an token to an ERC20 */ function toERC20(Token token) internal pure returns (ERC20) { return ERC20(address(token)); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; /** * @dev burnable ERC20 interface */ interface IERC20Burnable { /** * @dev Destroys tokens from the caller. */ function burn(uint256 amount) external; /** * @dev Destroys tokens from a recipient, deducting from the caller's allowance * * requirements: * * - the caller must have allowance for recipient's tokens of at least the specified amount */ function burnFrom(address recipient, uint256 amount) external; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; uint32 constant PPM_RESOLUTION = 1000000; // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IOwned } from "./interfaces/IOwned.sol"; import { AccessDenied } from "./Utils.sol"; /** * @dev this contract provides support and utilities for contract ownership */ abstract contract Owned is IOwned { error SameOwner(); address private _owner; address private _newOwner; /** * @dev triggered when the owner is updated */ event OwnerUpdate(address indexed prevOwner, address indexed newOwner); // solhint-disable func-name-mixedcase /** * @dev initializes the contract */ constructor() { _transferOwnership(msg.sender); } // solhint-enable func-name-mixedcase // allows execution by the owner only modifier onlyOwner() { _onlyOwner(); _; } // error message binary size optimization function _onlyOwner() private view { if (msg.sender != _owner) { revert AccessDenied(); } } /** * @inheritdoc IOwned */ function owner() public view virtual returns (address) { return _owner; } /** * @inheritdoc IOwned */ function transferOwnership(address ownerCandidate) public virtual onlyOwner { if (ownerCandidate == _owner) { revert SameOwner(); } _newOwner = ownerCandidate; } /** * @inheritdoc IOwned */ function acceptOwnership() public virtual { if (msg.sender != _newOwner) { revert AccessDenied(); } _transferOwnership(_newOwner); } /** * @dev returns the address of the new owner candidate */ function newOwner() external view returns (address) { return _newOwner; } /** * @dev sets the new owner internally */ function _transferOwnership(address ownerCandidate) private { address prevOwner = _owner; _owner = ownerCandidate; _newOwner = address(0); emit OwnerUpdate({ prevOwner: prevOwner, newOwner: ownerCandidate }); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { AccessControlEnumerableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import { IUpgradeable } from "./interfaces/IUpgradeable.sol"; import { AccessDenied } from "./Utils.sol"; /** * @dev this contract provides common utilities for upgradeable contracts */ abstract contract Upgradeable is IUpgradeable, AccessControlEnumerableUpgradeable { error AlreadyInitialized(); // the admin role is used to allow a non-proxy admin to perform additional initialization/setup during contract // upgrades bytes32 internal constant ROLE_ADMIN = keccak256("ROLE_ADMIN"); uint32 internal constant MAX_GAP = 50; uint16 internal _initializations; // upgrade forward-compatibility storage gap uint256[MAX_GAP - 1] private __gap; // solhint-disable func-name-mixedcase /** * @dev initializes the contract and its parents */ function __Upgradeable_init() internal onlyInitializing { __AccessControl_init(); __Upgradeable_init_unchained(); } /** * @dev performs contract-specific initialization */ function __Upgradeable_init_unchained() internal onlyInitializing { _initializations = 1; // set up administrative roles _setRoleAdmin(ROLE_ADMIN, ROLE_ADMIN); // allow the deployer to initially be the admin of the contract _setupRole(ROLE_ADMIN, msg.sender); } // solhint-enable func-name-mixedcase modifier onlyAdmin() { _hasRole(ROLE_ADMIN, msg.sender); _; } modifier onlyRoleMember(bytes32 role) { _hasRole(role, msg.sender); _; } function version() public view virtual override returns (uint16); /** * @dev returns the admin role */ function roleAdmin() external pure returns (bytes32) { return ROLE_ADMIN; } /** * @dev performs post-upgrade initialization * * requirements: * * - this must can be called only once per-upgrade */ function postUpgrade(bytes calldata data) external { uint16 initializations = _initializations + 1; if (initializations != version()) { revert AlreadyInitialized(); } _initializations = initializations; _postUpgrade(data); } /** * @dev an optional post-upgrade callback that can be implemented by child contracts */ function _postUpgrade( bytes calldata /* data */ ) internal virtual {} function _hasRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert AccessDenied(); } } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { PPM_RESOLUTION } from "./Constants.sol"; error AccessDenied(); error AlreadyExists(); error DoesNotExist(); error InvalidAddress(); error InvalidExternalAddress(); error InvalidFee(); error InvalidPool(); error InvalidPoolCollection(); error InvalidStakedBalance(); error InvalidToken(); error InvalidType(); error InvalidParam(); error NotEmpty(); error NotPayable(); error ZeroValue(); /** * @dev common utilities */ contract Utils { // allows execution by the caller only modifier only(address caller) { _only(caller); _; } function _only(address caller) internal view { if (msg.sender != caller) { revert AccessDenied(); } } // verifies that a value is greater than zero modifier greaterThanZero(uint256 value) { _greaterThanZero(value); _; } // error message binary size optimization function _greaterThanZero(uint256 value) internal pure { if (value == 0) { revert ZeroValue(); } } // validates an address - currently only checks that it isn't null modifier validAddress(address addr) { _validAddress(addr); _; } // error message binary size optimization function _validAddress(address addr) internal pure { if (addr == address(0)) { revert InvalidAddress(); } } // validates an external address - currently only checks that it isn't null or this modifier validExternalAddress(address addr) { _validExternalAddress(addr); _; } // error message binary size optimization function _validExternalAddress(address addr) internal view { if (addr == address(0) || addr == address(this)) { revert InvalidExternalAddress(); } } // ensures that the fee is valid modifier validFee(uint32 fee) { _validFee(fee); _; } // error message binary size optimization function _validFee(uint32 fee) internal pure { if (fee > PPM_RESOLUTION) { revert InvalidFee(); } } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; /** * @dev Owned interface */ interface IOwned { /** * @dev returns the address of the current owner */ function owner() external view returns (address); /** * @dev allows transferring the contract ownership * * requirements: * * - the caller must be the owner of the contract * - the new owner still needs to accept the transfer */ function transferOwnership(address ownerCandidate) external; /** * @dev used by a new owner to accept an ownership transfer */ function acceptOwnership() external; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; import { IVersioned } from "./IVersioned.sol"; import { IAccessControlEnumerableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/IAccessControlEnumerableUpgradeable.sol"; /** * @dev this is the common interface for upgradeable contracts */ interface IUpgradeable is IAccessControlEnumerableUpgradeable, IVersioned { } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.8.13; /** * @dev an interface for a versioned contract */ interface IVersioned { function version() external view returns (uint16); }
* @inheritdoc IPoolTokenFactory/ make sure to transfer the ownership to the caller
function createPoolToken(Token token) external validAddress(address(token)) returns (IPoolToken) { string memory customSymbol = _tokenSymbolOverrides[token]; string memory tokenSymbol = bytes(customSymbol).length != 0 ? customSymbol : token.symbol(); uint8 customDecimals = _tokenDecimalsOverrides[token]; uint8 tokenDecimals = customDecimals != 0 ? customDecimals : token.decimals(); string memory symbol = string.concat(POOL_TOKEN_SYMBOL_PREFIX, tokenSymbol); string memory name = string.concat(POOL_TOKEN_NAME_PREFIX, " ", tokenSymbol, " ", POOL_TOKEN_NAME_SUFFIX); PoolToken newPoolToken = new PoolToken(name, symbol, tokenDecimals, token); newPoolToken.transferOwnership(msg.sender); return newPoolToken; }
87,007
[ 1, 36, 10093, 467, 2864, 1345, 1733, 19, 1221, 3071, 358, 7412, 326, 23178, 358, 326, 4894, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 752, 2864, 1345, 12, 1345, 1147, 13, 3903, 923, 1887, 12, 2867, 12, 2316, 3719, 1135, 261, 2579, 1371, 1345, 13, 288, 203, 3639, 533, 3778, 1679, 5335, 273, 389, 2316, 5335, 13084, 63, 2316, 15533, 203, 3639, 533, 3778, 1147, 5335, 273, 1731, 12, 3662, 5335, 2934, 2469, 480, 374, 692, 1679, 5335, 294, 1147, 18, 7175, 5621, 203, 203, 3639, 2254, 28, 1679, 31809, 273, 389, 2316, 31809, 13084, 63, 2316, 15533, 203, 3639, 2254, 28, 1147, 31809, 273, 1679, 31809, 480, 374, 692, 1679, 31809, 294, 1147, 18, 31734, 5621, 203, 203, 3639, 533, 3778, 3273, 273, 533, 18, 16426, 12, 20339, 67, 8412, 67, 22093, 67, 6307, 16, 1147, 5335, 1769, 203, 3639, 533, 3778, 508, 273, 533, 18, 16426, 12, 20339, 67, 8412, 67, 1985, 67, 6307, 16, 315, 3104, 1147, 5335, 16, 315, 3104, 13803, 1741, 67, 8412, 67, 1985, 67, 14964, 1769, 203, 203, 3639, 8828, 1345, 394, 2864, 1345, 273, 394, 8828, 1345, 12, 529, 16, 3273, 16, 1147, 31809, 16, 1147, 1769, 203, 203, 3639, 394, 2864, 1345, 18, 13866, 5460, 12565, 12, 3576, 18, 15330, 1769, 203, 203, 203, 3639, 327, 394, 2864, 1345, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xFE7195686fCcCfA136613fAf7CB73E23318894Df/sources/contracts/DevsMap.sol
address WRAPPER - hardcoded for Mumbai address wrapperAddress = 0x99aFAf084eBA697E584501b8Ed2c0B37Dd136693;
address wrapperAddress;
5,687,299
[ 1, 2867, 12984, 2203, 3194, 300, 7877, 24808, 364, 490, 3592, 10658, 1758, 4053, 1887, 273, 374, 92, 2733, 69, 2046, 74, 20, 5193, 73, 12536, 8148, 27, 41, 25, 5193, 9172, 70, 28, 2671, 22, 71, 20, 38, 6418, 40, 72, 3437, 6028, 11180, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1758, 4053, 1887, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; import "./SafeMath.sol"; contract LoyalPoints { using SafeMath for uint256; // predefined exchange methods bytes1 private constant NO_EXCHANGE = 0x00; bytes1 private constant MULTIPLICATION = 0x01; bytes1 private constant DIVISION = 0x02; // defaults bytes1 private constant DEFAULT_EXCHANGE_METHOD = DIVISION; uint256 private constant DEFAULT_EXCHANGE_RATIO = 1; uint256 private nonce = 0; struct ExchangeRatio { bytes1 method; uint256 ratio; } struct Company { address account; bytes1 publicKeyPrefix; bytes32 publicKeyCurvePoint; bytes32 name; uint256 rewardRatio; bytes32 fabAddress; uint256 creationNumber; } struct Transaction { bytes32 companyName; uint256 nonce; uint256 rewardPoints; bool isRedeemed; address beneficiary; bytes signature; } mapping(address => mapping(bytes32 => uint256)) private userPoints; // stores user points mapping(bytes32 => mapping(bytes32 => ExchangeRatio)) private pointsExchangeRate; // stores the points exchange rate among company mapping(bytes32 => Company) private companyInfo; // stores the company registration info mapping(uint256 => Transaction) private transactionLookUp; // saves the transaction info for rewards redeem bytes32[] private companyNameList; function registerCompany(bytes1 _publicKeyPrefix, bytes32 _publicKeyCurvePoint, bytes32 _companyName, uint256 _rewardRatio, bytes32 _fabAddress) external returns(bool success) { if (companyInfo[_companyName].creationNumber > 0) { return false; } companyInfo[_companyName] = Company({ account: msg.sender, publicKeyPrefix: _publicKeyPrefix, publicKeyCurvePoint: _publicKeyCurvePoint, name: _companyName, rewardRatio: _rewardRatio, fabAddress: _fabAddress, creationNumber: companyNameList.length + 1 }); companyNameList.push(_companyName); return true; } function getNonce() public view returns (uint256 nonceCurrent) { return nonce; } function getExchangeRate(bytes32 _from, bytes32 _to) public view returns(bytes1 method, uint256 ratio) { return (pointsExchangeRate[_from][_to].method, pointsExchangeRate[_from][_to].ratio); } function getAllCompanies() public view returns(bytes1[] publicKeyPrefixes, bytes32[] publicKeyCurvePoints, bytes32[] companyNames, uint256[] companyCreationNumbers, bytes32[] fabAddresses) { uint256 numCompanies = companyNameList.length; publicKeyPrefixes = new bytes1[](numCompanies); publicKeyCurvePoints = new bytes32[](numCompanies); companyNames = new bytes32[](numCompanies); fabAddresses = new bytes32[](numCompanies); companyCreationNumbers = new uint256[](numCompanies); for (uint256 i = 0; i < numCompanies; i++) { Company storage company = companyInfo[companyNameList[i]]; publicKeyPrefixes[i] = company.publicKeyPrefix; publicKeyCurvePoints[i] = company.publicKeyCurvePoint; companyNames[i] = company.name; fabAddresses[i] = company.fabAddress; companyCreationNumbers[i] = company.creationNumber; } } function issuePoints(bytes32 _company, uint256 _moneySpent, address _beneficiary, uint256 _nonce, bytes32 _fabAddress, bytes _signature) external returns(bytes32 hash) { //require(_fabAddress == companyInfo[_company].fabAddress, "You are not allowed to issue points for this company"); //require(_nonce == nonce, "Nonce does not match"); uint256 rewardPoints = _moneySpent.div(companyInfo[_company].rewardRatio); hash = keccak256(abi.encodePacked(_signature, _company, nonce, rewardPoints, _beneficiary)); transactionLookUp[nonce] = Transaction({ signature: _signature, companyName: _company, nonce: _nonce, rewardPoints: rewardPoints, isRedeemed: false, beneficiary: _beneficiary }); nonce = nonce.add(1); } function redeemPoints(uint256 _nonce, address _beneficiary) external returns(bool success) { Transaction storage transaction = transactionLookUp[_nonce]; require(!transaction.isRedeemed, "this reward has already been redeemed"); if (transaction.beneficiary != address(0)) { require(transaction.beneficiary == msg.sender, "you are not the points owner"); } else { transaction.beneficiary = _beneficiary; } transaction.isRedeemed = true; userPoints[transaction.beneficiary][transaction.companyName] = userPoints[transaction.beneficiary][transaction.companyName].add(transaction.rewardPoints); return true; } function getBalances() public view returns(uint256[] balances) { balances = new uint256[](companyNameList.length); for (uint256 i = 0; i < companyNameList.length; i++) { balances[i] = userPoints[msg.sender][companyNameList[i]]; } } function spendPoints(bytes32 _company, uint256 _amount) external returns(bool success) { userPoints[msg.sender][_company] = userPoints[msg.sender][_company].sub(_amount); return true; } function convertPoints(bytes32 _from, bytes32 _to, uint256 _amount) private view returns(uint256 convertAmount) { ExchangeRatio storage rewardRatio = pointsExchangeRate[_from][_to]; require(rewardRatio.method == NO_EXCHANGE || rewardRatio.method == MULTIPLICATION || rewardRatio.method == DIVISION, "unknown exchange method"); if (rewardRatio.method == NO_EXCHANGE) { return _amount.mul(DEFAULT_EXCHANGE_RATIO); } else if (rewardRatio.method == MULTIPLICATION) { return _amount.mul(rewardRatio.ratio); } else if (rewardRatio.method == DIVISION) { return _amount.div(rewardRatio.ratio); } return 0; } function transferPointsSelf(bytes32 _from, bytes32 _to, uint256 _amount) external returns(bool success) { userPoints[msg.sender][_from] = userPoints[msg.sender][_from].sub(_amount); uint256 rewardAmount = convertPoints(_from, _to, _amount); userPoints[msg.sender][_to] = userPoints[msg.sender][_to].add(rewardAmount); return true; } function transferPointsOthers(bytes32 _fromPoints, address _toUser, bytes32 _toPoints, uint256 _amount) external returns(bool success) { userPoints[msg.sender][_fromPoints] = userPoints[msg.sender][_fromPoints].sub(_amount); uint256 transferAmount = convertPoints(_fromPoints, _toPoints, _amount); userPoints[_toUser][_toPoints] = userPoints[_toUser][_toPoints].add(transferAmount); return true; } }
stores the company registration info
mapping(bytes32 => Company) private companyInfo;
7,320,701
[ 1, 19632, 326, 9395, 7914, 1123, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 3890, 1578, 516, 26782, 13, 3238, 9395, 966, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.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. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * IMPORTANT: It is unsafe to assume that an address for which this * function returns false is an externally-owned account (EOA) and not a * contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract RoomLPProgram { using SafeMath for uint256; using SafeERC20 for IERC20; // TODO: Please do not forget to call the approve for this contract from the wallet. address public roomTokenRewardsReservoirAddress = 0x86181Ff88BDEC75d5f007cEfEE31087C8327dF77; address public owner; // This is ROOM/ETH LP ERC20 address. IERC20 public constant roomLPToken = IERC20(0xBE55c87dFf2a9f5c95cB5C07572C51fd91fe0732); // This is the correct CRC address of the ROOM token IERC20 public constant roomToken = IERC20(0xAd4f86a25bbc20FfB751f2FAC312A0B4d8F88c64); // total Room LP staked uint256 private _totalStaked; // last updated block number uint256 public lastUpdateBlock; uint256 private _accRewardPerToken; // accumulative reward per token uint256 private _rewardPerBlock; // reward per block uint256 public finishBlock; // finish rewarding block number uint256 public endTime; mapping(address => uint256) private _rewards; // rewards balances mapping(address => uint256) private _prevAccRewardPerToken; // previous accumulative reward per token (for a user) mapping(address => uint256) private _balances; // balances per user event Staked(address indexed user, uint256 amount); event Unstaked(address indexed user, uint256 amount); event ClaimReward(address indexed user, uint256 reward); event FarmingParametersChanged(uint256 rewardPerBlock, uint256 rewardBlockCount, address indexed roomTokenRewardsReservoirAdd); event RewardTransferFailed(TransferRewardState failure); enum TransferRewardState { Succeeded, RewardWalletEmpty } constructor () public { owner = msg.sender; uint256 rewardBlockCount = 1036800; // 5760 * 30 * 6; six months = 1,036,800 blocks uint256 totalRewards = 240000e18; // total rewards 240,000 Room in six months _rewardPerBlock = totalRewards * (1e18) / rewardBlockCount; // *(1e18) for math precisio finishBlock = blockNumber() + rewardBlockCount; endTime = ((finishBlock-blockNumber()) * 15) + (block.timestamp); lastUpdateBlock = blockNumber(); } function changeFarmingParameters(uint256 rewardPerBlock, uint256 rewardBlockCount, address roomTokenRewardsReservoirAdd) external { require(msg.sender == owner, "can be called by owner only"); updateReward(address(0)); _rewardPerBlock = rewardPerBlock.mul(1e18); // for math precision finishBlock = blockNumber().add(rewardBlockCount); endTime = finishBlock.sub(blockNumber()).mul(15).add(block.timestamp); roomTokenRewardsReservoirAddress = roomTokenRewardsReservoirAdd; emit FarmingParametersChanged(_rewardPerBlock, rewardBlockCount, roomTokenRewardsReservoirAddress); } function updateReward(address account) public { // reward algorithm // in general: rewards = (reward per token ber block) user balances uint256 cnBlock = blockNumber(); // update accRewardPerToken, in case totalStaked is zero; do not increment accRewardPerToken if (totalStaked() > 0) { uint256 lastRewardBlock = cnBlock < finishBlock ? cnBlock : finishBlock; if (lastRewardBlock > lastUpdateBlock) { _accRewardPerToken = lastRewardBlock.sub(lastUpdateBlock) .mul(_rewardPerBlock) .div(totalStaked()) .add(_accRewardPerToken); } } lastUpdateBlock = cnBlock; if (account != address(0)) { uint256 accRewardPerTokenForUser = _accRewardPerToken.sub(_prevAccRewardPerToken[account]); if (accRewardPerTokenForUser > 0) { _rewards[account] = _balances[account] .mul(accRewardPerTokenForUser) .div(1e18) .add(_rewards[account]); _prevAccRewardPerToken[account] = _accRewardPerToken; } } } function stake(uint256 amount) external { updateReward(msg.sender); _totalStaked = _totalStaked.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); // Transfer from owner of Room Token to this address. roomLPToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } function unstake(uint256 amount, bool claim) external returns(uint256 reward, TransferRewardState reason) { updateReward(msg.sender); _totalStaked = _totalStaked.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); // Send Room token staked to the original owner. roomLPToken.safeTransfer(msg.sender, amount); if (claim) { (reward, reason) = _executeRewardTransfer(msg.sender); } emit Unstaked(msg.sender, amount); } function claimReward() external returns (uint256 reward, TransferRewardState reason) { updateReward(msg.sender); return _executeRewardTransfer(msg.sender); } function _executeRewardTransfer(address account) internal returns(uint256 reward, TransferRewardState reason) { reward = _rewards[account]; if (reward > 0) { uint256 walletBalanace = roomToken.balanceOf(roomTokenRewardsReservoirAddress); if (walletBalanace < reward) { // This fails, and we send reason 1 for the UI // to display a meaningful message for the user. // 1 means the wallet is empty. reason = TransferRewardState.RewardWalletEmpty; emit RewardTransferFailed(reason); } else { // We will transfer and then empty the rewards // for the sender. _rewards[msg.sender] = 0; roomToken.transferFrom(roomTokenRewardsReservoirAddress, msg.sender, reward); emit ClaimReward(msg.sender, reward); } } } function rewards(address account) external view returns (uint256 reward) { // read version of update uint256 cnBlock = blockNumber(); uint256 accRewardPerToken = _accRewardPerToken; // update accRewardPerToken, in case totalStaked is zero; do not increment accRewardPerToken if (totalStaked() > 0) { uint256 lastRewardBlock = cnBlock < finishBlock ? cnBlock : finishBlock; if (lastRewardBlock > lastUpdateBlock) { accRewardPerToken = lastRewardBlock.sub(lastUpdateBlock) .mul(_rewardPerBlock).div(totalStaked()) .add(accRewardPerToken); } } reward = _balances[account] .mul(accRewardPerToken.sub(_prevAccRewardPerToken[account])) .div(1e18) .add(_rewards[account]); } function info() external view returns ( uint256 cBlockNumber, uint256 rewardPerBlock, uint256 rewardFinishBlock, uint256 rewardEndTime, uint256 walletBalance) { cBlockNumber = blockNumber(); rewardFinishBlock = finishBlock; rewardPerBlock = _rewardPerBlock.div(1e18); rewardEndTime = endTime; walletBalance = roomToken.balanceOf(roomTokenRewardsReservoirAddress); } // expected reward, // please note this is only an estimation, because total balance may change during the program function expectedRewardsToday(uint256 amount) external view returns (uint256 reward) { uint256 cnBlock = blockNumber(); uint256 prevAccRewardPerToken = _accRewardPerToken; uint256 accRewardPerToken = _accRewardPerToken; // update accRewardPerToken, in case totalStaked is zero do; not increment accRewardPerToken uint256 lastRewardBlock = cnBlock < finishBlock ? cnBlock : finishBlock; if (lastRewardBlock > lastUpdateBlock) { accRewardPerToken = lastRewardBlock.sub(lastUpdateBlock) .mul(_rewardPerBlock).div(totalStaked().add(amount)) .add(accRewardPerToken); } uint256 rewardsPerBlock = amount .mul(accRewardPerToken.sub(prevAccRewardPerToken)) .div(1e18); reward = rewardsPerBlock.mul(5760); // 5760 blocks per day } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function totalStaked() public view returns (uint256) { return _totalStaked; } function blockNumber() public view returns (uint256) { return block.number; } }
Send Room token staked to the original owner.
function unstake(uint256 amount, bool claim) external returns(uint256 reward, TransferRewardState reason) { updateReward(msg.sender); _totalStaked = _totalStaked.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); roomLPToken.safeTransfer(msg.sender, amount); if (claim) { (reward, reason) = _executeRewardTransfer(msg.sender); } emit Unstaked(msg.sender, amount); }
13,088,877
[ 1, 3826, 27535, 1147, 384, 9477, 358, 326, 2282, 3410, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 640, 334, 911, 12, 11890, 5034, 3844, 16, 1426, 7516, 13, 3903, 1135, 12, 11890, 5034, 19890, 16, 12279, 17631, 1060, 1119, 3971, 13, 288, 203, 3639, 1089, 17631, 1060, 12, 3576, 18, 15330, 1769, 203, 203, 203, 3639, 389, 4963, 510, 9477, 273, 389, 4963, 510, 9477, 18, 1717, 12, 8949, 1769, 203, 3639, 389, 70, 26488, 63, 3576, 18, 15330, 65, 273, 389, 70, 26488, 63, 3576, 18, 15330, 8009, 1717, 12, 8949, 1769, 203, 3639, 7725, 14461, 1345, 18, 4626, 5912, 12, 3576, 18, 15330, 16, 3844, 1769, 203, 3639, 203, 203, 3639, 309, 261, 14784, 13, 288, 203, 1850, 261, 266, 2913, 16, 3971, 13, 273, 389, 8837, 17631, 1060, 5912, 12, 3576, 18, 15330, 1769, 203, 3639, 289, 203, 540, 203, 540, 3626, 1351, 334, 9477, 12, 3576, 18, 15330, 16, 3844, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.17; pragma experimental ABIEncoderV2; import "./StakingStorage.sol"; import "./SafeMath96.sol"; /** * @title Checkpoints contract. * @notice Increases and decreases storage values for users, delegatees and * total daily stake. * */ contract Checkpoints is StakingStorage, SafeMath96 { /// @notice An event emitted when an account changes its delegate. event DelegateChanged(address indexed delegator, uint256 lockedUntil, address indexed fromDelegate, address indexed toDelegate); /// @notice An event emitted when a delegate account's stake balance changes. event DelegateStakeChanged(address indexed delegate, uint256 lockedUntil, uint256 previousBalance, uint256 newBalance); /// @notice An event emitted when tokens get staked. event TokensStaked(address indexed staker, uint256 amount, uint256 lockedUntil, uint256 totalStaked); /// @notice An event emitted when tokens get withdrawn. event TokensWithdrawn(address indexed staker, address receiver, uint256 amount); /// @notice An event emitted when vesting tokens get withdrawn. event VestingTokensWithdrawn(address vesting, address receiver); /// @notice An event emitted when the owner unlocks all tokens. event TokensUnlocked(uint256 amount); /// @notice An event emitted when a staking period gets extended. event ExtendedStakingDuration(address indexed staker, uint256 previousDate, uint256 newDate); /** * @notice Increases the user's stake for a giving lock date and writes a checkpoint. * @param account The user address. * @param lockedTS The lock date. * @param value The value to add to the staked balance. * */ function _increaseUserStake( address account, uint256 lockedTS, uint96 value ) internal { uint32 nCheckpoints = numUserStakingCheckpoints[account][lockedTS]; uint96 staked = userStakingCheckpoints[account][lockedTS][nCheckpoints - 1].stake; uint96 newStake = add96(staked, value, "Staking::_increaseUserStake: staked amount overflow"); _writeUserCheckpoint(account, lockedTS, nCheckpoints, newStake); } /** * @notice Decreases the user's stake for a giving lock date and writes a checkpoint. * @param account The user address. * @param lockedTS The lock date. * @param value The value to substract to the staked balance. * */ function _decreaseUserStake( address account, uint256 lockedTS, uint96 value ) internal { uint32 nCheckpoints = numUserStakingCheckpoints[account][lockedTS]; uint96 staked = userStakingCheckpoints[account][lockedTS][nCheckpoints - 1].stake; uint96 newStake = sub96(staked, value, "Staking::_decreaseUserStake: staked amount underflow"); _writeUserCheckpoint(account, lockedTS, nCheckpoints, newStake); } /** * @notice Writes on storage the user stake. * @param account The user address. * @param lockedTS The lock date. * @param nCheckpoints The number of checkpoints, to find out the last one index. * @param newStake The new staked balance. * */ function _writeUserCheckpoint( address account, uint256 lockedTS, uint32 nCheckpoints, uint96 newStake ) internal { uint32 blockNumber = safe32(block.number, "Staking::_writeStakingCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && userStakingCheckpoints[account][lockedTS][nCheckpoints - 1].fromBlock == blockNumber) { userStakingCheckpoints[account][lockedTS][nCheckpoints - 1].stake = newStake; } else { userStakingCheckpoints[account][lockedTS][nCheckpoints] = Checkpoint(blockNumber, newStake); numUserStakingCheckpoints[account][lockedTS] = nCheckpoints + 1; } } /** * @notice Increases the delegatee's stake for a giving lock date and writes a checkpoint. * @param delegatee The delegatee address. * @param lockedTS The lock date. * @param value The value to add to the staked balance. * */ function _increaseDelegateStake( address delegatee, uint256 lockedTS, uint96 value ) internal { uint32 nCheckpoints = numDelegateStakingCheckpoints[delegatee][lockedTS]; uint96 staked = delegateStakingCheckpoints[delegatee][lockedTS][nCheckpoints - 1].stake; uint96 newStake = add96(staked, value, "Staking::_increaseDelegateeStake: staked amount overflow"); _writeDelegateCheckpoint(delegatee, lockedTS, nCheckpoints, newStake); } /** * @notice Decreases the delegatee's stake for a giving lock date and writes a checkpoint. * @param delegatee The delegatee address. * @param lockedTS The lock date. * @param value The value to substract to the staked balance. * */ function _decreaseDelegateStake( address delegatee, uint256 lockedTS, uint96 value ) internal { uint32 nCheckpoints = numDelegateStakingCheckpoints[delegatee][lockedTS]; uint96 staked = delegateStakingCheckpoints[delegatee][lockedTS][nCheckpoints - 1].stake; uint96 newStake = sub96(staked, value, "Staking::_decreaseDailyStake: staked amount underflow"); _writeDelegateCheckpoint(delegatee, lockedTS, nCheckpoints, newStake); } /** * @notice Writes on storage the delegate stake. * @param delegatee The delegate address. * @param lockedTS The lock date. * @param nCheckpoints The number of checkpoints, to find out the last one index. * @param newStake The new staked balance. * */ function _writeDelegateCheckpoint( address delegatee, uint256 lockedTS, uint32 nCheckpoints, uint96 newStake ) internal { uint32 blockNumber = safe32(block.number, "Staking::_writeStakingCheckpoint: block number exceeds 32 bits"); uint96 oldStake = delegateStakingCheckpoints[delegatee][lockedTS][nCheckpoints - 1].stake; if (nCheckpoints > 0 && delegateStakingCheckpoints[delegatee][lockedTS][nCheckpoints - 1].fromBlock == blockNumber) { delegateStakingCheckpoints[delegatee][lockedTS][nCheckpoints - 1].stake = newStake; } else { delegateStakingCheckpoints[delegatee][lockedTS][nCheckpoints] = Checkpoint(blockNumber, newStake); numDelegateStakingCheckpoints[delegatee][lockedTS] = nCheckpoints + 1; } emit DelegateStakeChanged(delegatee, lockedTS, oldStake, newStake); } /** * @notice Increases the total stake for a giving lock date and writes a checkpoint. * @param lockedTS The lock date. * @param value The value to add to the staked balance. * */ function _increaseDailyStake(uint256 lockedTS, uint96 value) internal { uint32 nCheckpoints = numTotalStakingCheckpoints[lockedTS]; uint96 staked = totalStakingCheckpoints[lockedTS][nCheckpoints - 1].stake; uint96 newStake = add96(staked, value, "Staking::_increaseDailyStake: staked amount overflow"); _writeStakingCheckpoint(lockedTS, nCheckpoints, newStake); } /** * @notice Decreases the total stake for a giving lock date and writes a checkpoint. * @param lockedTS The lock date. * @param value The value to substract to the staked balance. * */ function _decreaseDailyStake(uint256 lockedTS, uint96 value) internal { uint32 nCheckpoints = numTotalStakingCheckpoints[lockedTS]; uint96 staked = totalStakingCheckpoints[lockedTS][nCheckpoints - 1].stake; uint96 newStake = sub96(staked, value, "Staking::_decreaseDailyStake: staked amount underflow"); _writeStakingCheckpoint(lockedTS, nCheckpoints, newStake); } /** * @notice Writes on storage the total stake. * @param lockedTS The lock date. * @param nCheckpoints The number of checkpoints, to find out the last one index. * @param newStake The new staked balance. * */ function _writeStakingCheckpoint( uint256 lockedTS, uint32 nCheckpoints, uint96 newStake ) internal { uint32 blockNumber = safe32(block.number, "Staking::_writeStakingCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && totalStakingCheckpoints[lockedTS][nCheckpoints - 1].fromBlock == blockNumber) { totalStakingCheckpoints[lockedTS][nCheckpoints - 1].stake = newStake; } else { totalStakingCheckpoints[lockedTS][nCheckpoints] = Checkpoint(blockNumber, newStake); numTotalStakingCheckpoints[lockedTS] = nCheckpoints + 1; } } }
* @notice Decreases the delegatee's stake for a giving lock date and writes a checkpoint. @param delegatee The delegatee address. @param lockedTS The lock date. @param value The value to substract to the staked balance. /
function _decreaseDelegateStake( address delegatee, uint256 lockedTS, uint96 value ) internal { uint32 nCheckpoints = numDelegateStakingCheckpoints[delegatee][lockedTS]; uint96 staked = delegateStakingCheckpoints[delegatee][lockedTS][nCheckpoints - 1].stake; uint96 newStake = sub96(staked, value, "Staking::_decreaseDailyStake: staked amount underflow"); _writeDelegateCheckpoint(delegatee, lockedTS, nCheckpoints, newStake); }
12,589,148
[ 1, 23326, 3304, 326, 7152, 73, 1807, 384, 911, 364, 279, 21057, 2176, 1509, 471, 7262, 279, 9776, 18, 225, 7152, 73, 1021, 7152, 73, 1758, 18, 225, 8586, 8047, 1021, 2176, 1509, 18, 225, 460, 1021, 460, 358, 2373, 621, 358, 326, 384, 9477, 11013, 18, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 389, 323, 11908, 9586, 510, 911, 12, 203, 202, 202, 2867, 7152, 73, 16, 203, 202, 202, 11890, 5034, 8586, 8047, 16, 203, 202, 202, 11890, 10525, 460, 203, 202, 13, 2713, 288, 203, 202, 202, 11890, 1578, 290, 1564, 4139, 273, 818, 9586, 510, 6159, 1564, 4139, 63, 22216, 73, 6362, 15091, 8047, 15533, 203, 202, 202, 11890, 10525, 384, 9477, 273, 7152, 510, 6159, 1564, 4139, 63, 22216, 73, 6362, 15091, 8047, 6362, 82, 1564, 4139, 300, 404, 8009, 334, 911, 31, 203, 202, 202, 11890, 10525, 394, 510, 911, 273, 720, 10525, 12, 334, 9477, 16, 460, 16, 315, 510, 6159, 2866, 67, 323, 11908, 40, 12857, 510, 911, 30, 384, 9477, 3844, 3613, 2426, 8863, 203, 202, 202, 67, 2626, 9586, 14431, 12, 22216, 73, 16, 8586, 8047, 16, 290, 1564, 4139, 16, 394, 510, 911, 1769, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xef0F6F951F0e62774597eB29b86065498bB7aC32/sources/contracts/periphery/UniswapControllerHelper.sol
* @notice uniswap swap callback function for flashswap @param amount0Delta amount of token0 @param amount1Delta amount of token1 @param _data callback data encoded as SwapCallbackData struct/ensure that callback comes from uniswap pooldetermine the amount that needs to be repaid as part of the flashswapcalls the function that uses the proceeds from flash swap and executes logic to have an amount of token to repay the flash swap
function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata _data ) external override { SwapCallbackData memory data = abi.decode(_data, (SwapCallbackData)); (address tokenIn, address tokenOut, uint24 fee) = data.path.decodeFirstPool(); address pool = address(CallbackValidation.verifyCallback(factory, tokenIn, tokenOut, fee)); uint256 amountToPay = amount0Delta > 0 ? uint256(amount0Delta) : uint256(amount1Delta); _swapCallback(data.caller, tokenIn, pool, amountToPay, data.callData, data.callSource); }
11,610,424
[ 1, 318, 291, 91, 438, 7720, 1348, 445, 364, 9563, 22270, 225, 3844, 20, 9242, 3844, 434, 1147, 20, 225, 3844, 21, 9242, 3844, 434, 1147, 21, 225, 389, 892, 1348, 501, 3749, 487, 12738, 2428, 751, 1958, 19, 15735, 716, 1348, 14535, 628, 640, 291, 91, 438, 2845, 24661, 326, 3844, 716, 4260, 358, 506, 2071, 20736, 487, 1087, 434, 326, 9563, 22270, 12550, 326, 445, 716, 4692, 326, 11247, 87, 628, 9563, 7720, 471, 11997, 4058, 358, 1240, 392, 3844, 434, 1147, 358, 2071, 528, 326, 9563, 7720, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 640, 291, 91, 438, 58, 23, 12521, 2428, 12, 203, 3639, 509, 5034, 3844, 20, 9242, 16, 203, 3639, 509, 5034, 3844, 21, 9242, 16, 203, 3639, 1731, 745, 892, 389, 892, 203, 565, 262, 3903, 3849, 288, 203, 203, 3639, 12738, 2428, 751, 3778, 501, 273, 24126, 18, 3922, 24899, 892, 16, 261, 12521, 2428, 751, 10019, 203, 3639, 261, 2867, 1147, 382, 16, 1758, 1147, 1182, 16, 2254, 3247, 14036, 13, 273, 501, 18, 803, 18, 3922, 3759, 2864, 5621, 203, 203, 3639, 1758, 2845, 273, 1758, 12, 2428, 4354, 18, 8705, 2428, 12, 6848, 16, 1147, 382, 16, 1147, 1182, 16, 14036, 10019, 203, 203, 3639, 2254, 5034, 3844, 774, 9148, 273, 3844, 20, 9242, 405, 374, 692, 2254, 5034, 12, 8949, 20, 9242, 13, 294, 2254, 5034, 12, 8949, 21, 9242, 1769, 203, 203, 3639, 389, 22270, 2428, 12, 892, 18, 16140, 16, 1147, 382, 16, 2845, 16, 3844, 774, 9148, 16, 501, 18, 1991, 751, 16, 501, 18, 1991, 1830, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: UNLICENSED // _ _ _ _ __ _ // | | (_) | | | / _(_) // | | ___| |_| |_ ___ _ __ | |_ _ _ __ __ _ _ __ ___ ___ // | |/ / | __| __/ _ \ '_ \ | _| | '_ \ / _` | '_ \ / __/ _ \ // | <| | |_| || __/ | | |_| | | | | | | (_| | | | | (_| __/ // |_|\_\_|\__|\__\___|_| |_(_)_| |_|_| |_|\__,_|_| |_|\___\___| // // KittenSwap Lending v0 // // https://www.KittenSwap.org/ // pragma solidity ^0.6.12; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require (c >= a, "!!add"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require (b <= a, "!!sub"); uint256 c = a - b; return c; } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require (b <= a, errorMessage); uint c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require (c / a == b, "!!mul"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require (b > 0, "!!div"); uint256 c = a / b; return c; } } contract ERC20Detailed { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } } //////////////////////////////////////////////////////////////////////////////// interface LIQUID_TOKEN { function totalSupply ( ) external view returns ( uint256 ); function getTokenReserve ( ) external view returns ( uint256 ); function getEthReserve ( ) external view returns ( uint256 ); function balanceOf ( address account ) external view returns ( uint256 ); function transfer ( address recipient, uint256 amount ) external returns ( bool ); function transferFrom ( address sender, address recipient, uint256 amount ) external returns ( bool ); function buyToken ( uint256 minTokenAmt, uint256 expireTimestamp ) external payable; function sellToken ( uint256 tokenAmt, uint256 minEthAmt, uint256 expireTimestamp ) external; } //////////////////////////////////////////////////////////////////////////////// contract KittenETHv0 is ERC20Detailed { using SafeMath for uint; address public constant LIQUID_ADDR = 0xC618D56b6D606E59c6B87Af724AB5a91eb40D1cb; uint public MIGRATION_TIMESTAMP = 0; // for migration uint public MIGRATION_LIQUIDATION_WAIT = 14 days; // gov can liquidate forgotten loans some days after migration starts uint public FLASH_LOAN_BP = 10; // in terms of basis points //////////////////////////////////////////////////////////////////////////////// LIQUID_TOKEN private constant LIQUID = LIQUID_TOKEN(LIQUID_ADDR); address public govAddr; constructor () public ERC20Detailed("KittenETHv0", "KittenETHv0", 18) { govAddr = msg.sender; } modifier govOnly() { require (msg.sender == govAddr, "!gov"); _; } function govTransferAddr(address newAddr) external govOnly { require (newAddr != address(0), "!addr"); govAddr = newAddr; } function govSetMIGRATION_TIMESTAMP(uint $MIGRATION_TIMESTAMP) external govOnly { require ($MIGRATION_TIMESTAMP > block.timestamp); MIGRATION_TIMESTAMP = $MIGRATION_TIMESTAMP; } function govSetFLASH_LOAN_BP(uint $FLASH_LOAN_BP) external govOnly { require (FLASH_LOAN_BP <= 60); FLASH_LOAN_BP = $FLASH_LOAN_BP; } //////////////////////////////////////////////////////////////////////////////// function _msgSender() internal view returns (address payable) { return msg.sender; } event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); mapping (address => uint) private _balances; mapping (address => mapping (address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns (uint) { return _totalSupply; } function balanceOf(address account) public view returns (uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require (sender != address(0), "ERC20: transfer from the zero address"); require (recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } //------------------------------------------------------------------------------ function allowance(address owner, address spender) public view returns (uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } function _approve(address owner, address spender, uint amount) internal { require (owner != address(0), "ERC20: approve from the zero address"); require (spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } //------------------------------------------------------------------------------ function _mint(address account, uint amount) internal { require (account != address(0), "ERC20: mint to the zero address"); _balances[account] = _balances[account].add(amount); _totalSupply = _totalSupply.add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require (account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } //////////////////////////////////////////////////////////////////////////////// uint constant PRICE_SCALE = 10 ** 10; function getLiqEthFloorPriceScaled() internal view returns (uint) { uint AMM_PRODUCT = (LIQUID.getTokenReserve()).mul(LIQUID.getEthReserve()); uint TOTAL_SUPPLY = LIQUID.totalSupply(); return PRICE_SCALE.mul(AMM_PRODUCT).div(TOTAL_SUPPLY).div(TOTAL_SUPPLY); } //////////////////////////////////////////////////////////////////////////////// event LOCK_ETH(address indexed user, uint ethAmt, uint kethAmt); event UNLOCK_ETH(address indexed user, uint ethAmt, uint kethAmt); function getContractValueInEth() public view returns (uint) { uint ethValue = (address(this).balance); uint liqValue = (LIQUID.balanceOf(address(this))).mul(getLiqEthFloorPriceScaled()) / (PRICE_SCALE); return ethValue.add(liqValue); } function lockEth() external payable // lock ETH for lending, and mint KittenEth { //-------- receive ETH from user -------- address user = msg.sender; uint ethInAmt = msg.value; require (ethInAmt > 0, '!ethInAmt'); //-------- compute KittenETH mint amt -------- uint kethMintAmt = 0; if (_totalSupply == 0) { kethMintAmt = ethInAmt; // initial price: 1 kETH = 1 ETH } else { kethMintAmt = ethInAmt.mul(_totalSupply).div(getContractValueInEth().sub(ethInAmt)); } //-------- mint KittenETH to user -------- _mint(user, kethMintAmt); emit LOCK_ETH(user, ethInAmt, kethMintAmt); } function unlockEth(uint kethBurnAmt) external // unlock ETH, and burn KittenEth { require (kethBurnAmt > 0, '!kethBurnAmt'); address payable user = msg.sender; //-------- compute ETH out amt -------- uint ethOutAmt = kethBurnAmt.mul(getContractValueInEth()).div(_totalSupply); require (address(this).balance >= ethOutAmt, '!ethInContract'); //-------- burn KittenETH from user -------- _burn(user, kethBurnAmt); //-------- send ETH to user -------- user.transfer(ethOutAmt); emit UNLOCK_ETH(user, ethOutAmt, kethBurnAmt); } //////////////////////////////////////////////////////////////////////////////// mapping (address => uint) public liqLocked; event LOCK_LIQ(address indexed user, uint liqAmt, uint ethAmt); event UNLOCK_LIQ(address indexed user, uint liqAmt, uint ethAmt); function lockLiq(uint liqInAmt) external // lock LIQUID to borrow ETH { require (liqInAmt > 0, '!liqInAmt'); require (block.timestamp < MIGRATION_TIMESTAMP, '!migration'); // can't lock after migration starts address payable user = msg.sender; //-------- compute ETH out amt -------- uint ethOutAmt = liqInAmt.mul(getLiqEthFloorPriceScaled()) / (PRICE_SCALE); require (address(this).balance >= ethOutAmt, '!ethInContract'); //-------- send LIQUID to contract -------- LIQUID.transferFrom(user, address(this), liqInAmt); liqLocked[user] = liqLocked[user].add(liqInAmt); //-------- send ETH to user -------- user.transfer(ethOutAmt); emit LOCK_LIQ(user, liqInAmt, ethOutAmt); } function unlockLiq() external payable // payback ETH to unlock LIQUID { //-------- receive ETH from user -------- uint ethInAmt = msg.value; require (ethInAmt > 0, '!ethInAmt'); uint ethReturnAmt = 0; address payable user = msg.sender; //-------- compute LIQUID out amt -------- uint LiqEthFloorPriceScaled = getLiqEthFloorPriceScaled(); uint liqOutAmt = ethInAmt.mul(PRICE_SCALE).div(LiqEthFloorPriceScaled); if (liqOutAmt > liqLocked[user]) { liqOutAmt = liqLocked[user]; ethReturnAmt = ethInAmt.sub( liqOutAmt.mul(LiqEthFloorPriceScaled) / (PRICE_SCALE) ); } //-------- send LIQUID to user -------- liqLocked[user] = liqLocked[user].sub(liqOutAmt); LIQUID.transfer(user, liqOutAmt); //-------- return extra ETH to user -------- if (ethReturnAmt > 10 ** 8) { // ignore dust user.transfer(ethReturnAmt); } emit UNLOCK_LIQ(user, liqOutAmt, ethInAmt.sub(ethReturnAmt)); } //////////////////////////////////////////////////////////////////////////////// receive() external payable { // receive ETH (from selling LIQUID) require(msg.sender == LIQUID_ADDR, '!sender'); } function flashUnlockLiqAndSell(address payable user, uint liqUnlockAmt, uint liqSellAmt, uint liqSellMinEthAmt, uint liqSellExpireTimestamp) external payable { require ( (user == msg.sender) || // gov can liquidate forgotten loans some days after migration starts ((block.timestamp.sub(MIGRATION_LIQUIDATION_WAIT) > MIGRATION_TIMESTAMP) && (govAddr == msg.sender)) , '!user'); if (liqUnlockAmt > liqLocked[user]) liqUnlockAmt = liqLocked[user]; if (liqSellAmt > liqUnlockAmt) liqSellAmt = liqUnlockAmt; //-------- receive ETH from user -------- uint ethInAmt = msg.value; //-------- compute ETH required for unlocking LIQUID -------- uint ethBorrowAmt = 0; uint ethOutAmt = 0; uint ethRequiredForUnlock = liqUnlockAmt.mul(getLiqEthFloorPriceScaled()) / (PRICE_SCALE); if (ethRequiredForUnlock > ethInAmt) { ethBorrowAmt = (ethRequiredForUnlock - ethInAmt).mul(10000 + FLASH_LOAN_BP) / 10000; // add FLASH_LOAN_BP fee } else { ethOutAmt = ethInAmt - ethRequiredForUnlock; } //-------- sell LIQUID -------- uint liqLoss = 0; uint ethGain = 0; if (liqSellAmt > 0) { uint liqBefore = LIQUID.balanceOf(address(this)); uint ethBefore = address(this).balance; LIQUID.sellToken(liqSellAmt, liqSellMinEthAmt, liqSellExpireTimestamp); // sell LIQUID liqLoss = liqBefore.sub(LIQUID.balanceOf(address(this)), '!liqLoss'); // now contract has less LIQUID ethGain = (address(this).balance).sub(ethBefore, '!ethGain'); // now contract has more ETH } //-------- payback flash-loan (if occured) -------- if (ethBorrowAmt > 0) { // ethOutAmt = 0 ethOutAmt = ethGain.sub(ethBorrowAmt, '!ethBorrowAmt'); // will throw if not enough } else { // ethBorrowAmt = 0 ethOutAmt = ethOutAmt.add(ethGain); } //-------- unlock LIQUID -------- liqLocked[user] = liqLocked[user].sub(liqUnlockAmt, '!liqUnlockAmt'); //-------- send LIQUID to user -------- if (liqUnlockAmt > liqLoss) { LIQUID.transfer(user, liqUnlockAmt - liqLoss); } //-------- send ETH to user -------- if (ethOutAmt > 10 ** 8) { // ignore dust user.transfer(ethOutAmt); } emit UNLOCK_LIQ(user, liqUnlockAmt, ethRequiredForUnlock); } function flashBuyLiqAndLock(uint ethBorrowAmt, uint liqLockAmt, uint liqBuyMinAmt, uint liqBuyExpireTimestamp) external payable { require (block.timestamp < MIGRATION_TIMESTAMP, '!migration'); // can't lock after migration starts address payable user = msg.sender; //-------- receive ETH from user -------- uint ethInAmt = msg.value; //-------- buy LIQUID -------- uint liqGain = 0; uint ethLoss = 0; { uint liqBefore = LIQUID.balanceOf(address(this)); uint ethBefore = address(this).balance; //-------- borrow flash-loan -------- uint ethTotalInAmt = ethInAmt.add(ethBorrowAmt); require (ethBefore >= ethTotalInAmt, '!ethInContract'); LIQUID.buyToken {value: ethTotalInAmt} (liqBuyMinAmt, liqBuyExpireTimestamp); // buy LIQUID liqGain = (LIQUID.balanceOf(address(this))).sub(liqBefore, '!liqGain'); // now contract has more LIQUID ethLoss = ethBefore.sub(address(this).balance, '!ethLoss'); // now contract has less ETH } //-------- compute ETH gain from locking LIQUID -------- if (liqLockAmt > liqGain) { liqLockAmt = liqGain; } uint ethLockOutAmt = liqLockAmt.mul(getLiqEthFloorPriceScaled()) / (PRICE_SCALE); //-------- payback flash-loan -------- uint ethOutAmt = ethInAmt.add(ethLockOutAmt).sub(ethLoss, '!ethLockOutAmt'); // will throw if not enough ethOutAmt = ethOutAmt.sub(ethBorrowAmt.mul(FLASH_LOAN_BP) / 10000, '!ethBorrowAmt'); //-------- lock LIQUID -------- liqLocked[user] = liqLocked[user].add(liqLockAmt); //-------- send LIQUID to user -------- if (liqGain > liqLockAmt) { LIQUID.transfer(user, liqGain - liqLockAmt); } //-------- send ETH to user -------- if (ethOutAmt > 10 ** 8) { // ignore dust require (address(this).balance >= ethOutAmt, '!ethOutAmt'); user.transfer(ethOutAmt); } emit LOCK_LIQ(user, liqLockAmt, ethLockOutAmt); } }
now contract has less LIQUID
liqLoss = liqBefore.sub(LIQUID.balanceOf(address(this)), '!liqLoss');
14,785,706
[ 1, 3338, 6835, 711, 5242, 8961, 53, 3060, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 4501, 85, 20527, 273, 4501, 85, 4649, 18, 1717, 12, 2053, 53, 3060, 18, 12296, 951, 12, 2867, 12, 2211, 13, 3631, 11817, 549, 85, 20527, 8284, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xA5E38d098b54C00F10e32E51647086232a9A0afD/sources/contracts/AtomicSwap.sol
* @notice Signers can create an order with order params @dev Secret used to generate secret hash for iniatiation should be generated randomly and sha256 hash should be used to support hashing methods on other non-evm chains. Signers cannot generate orders with same secret hash or override an existing order. @param _redeemer public address of the redeemer @param _expiry expiry in period for the htlc order @param _amount amount of tokens to trade @param _secretHash sha256 hash of the secret used for redemtion/
function initiate( address _redeemer, uint256 _expiry, uint256 _amount, bytes32 _secretHash ) external checkSafe(_redeemer, msg.sender, _expiry, _amount) { bytes32 OrderId = sha256(abi.encode(_secretHash, msg.sender)); Order memory order = atomicSwapOrders[OrderId]; require(order.redeemer == address(0x0), "AtomicSwap: duplicate order"); Order memory newOrder = Order({ redeemer: _redeemer, initiator: msg.sender, expiry: _expiry, initiatedAt: block.number, amount: _amount, isFulfilled: false }); atomicSwapOrders[OrderId] = newOrder; emit Initiated( OrderId, _secretHash, newOrder.initiatedAt, newOrder.amount ); token.safeTransferFrom(msg.sender, address(this), newOrder.amount); }
9,794,789
[ 1, 2766, 414, 848, 752, 392, 1353, 598, 1353, 859, 1377, 7875, 1399, 358, 2103, 4001, 1651, 364, 6896, 270, 7072, 1410, 506, 4374, 20153, 1850, 471, 6056, 5034, 1651, 1410, 506, 1399, 358, 2865, 24641, 2590, 603, 1308, 1661, 17, 73, 3489, 13070, 18, 1850, 4383, 414, 2780, 2103, 11077, 598, 1967, 4001, 1651, 578, 3849, 392, 2062, 1353, 18, 565, 389, 266, 24903, 264, 225, 1071, 1758, 434, 326, 283, 24903, 264, 565, 389, 22409, 225, 10839, 316, 3879, 364, 326, 18962, 1353, 565, 389, 8949, 225, 3844, 434, 2430, 358, 18542, 565, 389, 5875, 2310, 225, 6056, 5034, 1651, 434, 326, 4001, 1399, 364, 283, 323, 1010, 285, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18711, 12, 203, 3639, 1758, 389, 266, 24903, 264, 16, 203, 3639, 2254, 5034, 389, 22409, 16, 203, 3639, 2254, 5034, 389, 8949, 16, 203, 3639, 1731, 1578, 389, 5875, 2310, 203, 565, 262, 3903, 866, 9890, 24899, 266, 24903, 264, 16, 1234, 18, 15330, 16, 389, 22409, 16, 389, 8949, 13, 288, 203, 3639, 1731, 1578, 4347, 548, 273, 6056, 5034, 12, 21457, 18, 3015, 24899, 5875, 2310, 16, 1234, 18, 15330, 10019, 203, 3639, 4347, 3778, 1353, 273, 7960, 12521, 16528, 63, 21303, 15533, 203, 3639, 2583, 12, 1019, 18, 266, 24903, 264, 422, 1758, 12, 20, 92, 20, 3631, 315, 23102, 12521, 30, 6751, 1353, 8863, 203, 3639, 4347, 3778, 394, 2448, 273, 4347, 12590, 203, 5411, 283, 24903, 264, 30, 389, 266, 24903, 264, 16, 203, 5411, 26030, 30, 1234, 18, 15330, 16, 203, 5411, 10839, 30, 389, 22409, 16, 203, 5411, 27183, 861, 30, 1203, 18, 2696, 16, 203, 5411, 3844, 30, 389, 8949, 16, 203, 5411, 17646, 332, 13968, 30, 629, 203, 3639, 15549, 203, 3639, 7960, 12521, 16528, 63, 21303, 65, 273, 394, 2448, 31, 203, 3639, 3626, 4378, 10206, 12, 203, 5411, 4347, 548, 16, 203, 5411, 389, 5875, 2310, 16, 203, 5411, 394, 2448, 18, 2738, 10206, 861, 16, 203, 5411, 394, 2448, 18, 8949, 203, 3639, 11272, 203, 3639, 1147, 18, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 394, 2448, 18, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; //cToken import "./CToken/CErc20Delegator.sol"; import "./CToken/CErc20Delegate.sol"; import "./Governance/Comp.sol"; //comptroller import "./Comptroller/Unitroller.sol"; import "./Comptroller/Comptroller.sol"; //interestModel import "./InterestModel/JumpRateModelV2.sol"; //priceOracle import "./Oracle/SimplePriceOracle.sol"; import "./Governance/Timelock.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; // underlying asset //import "./tokenForTest/TestERC20Asset.sol"; contract Setup { // address public TT1 = 0xe09D4de9f1dCC8A4d5fB19c30Fb53830F8e2a047; address public TT1; Comp public comp; CErc20Delegator public cTT1; CErc20Delegate public cTT1Delegate; Unitroller public unitrollerProxy; Comptroller public comptrollerImpl; Comptroller public unitrollerProxyToImpl; JumpRateModelV2 public interestRateModel; SimplePriceOracle public priceOracle; Timelock public timelock; constructor(address tt1_) { // underlying asset TT1 = tt1_; timelock = new Timelock(msg.sender, uint256(1 seconds)); // governance token for borrow and incentives comp = new Comp(msg.sender); // price oracle set mannually priceOracle = new SimplePriceOracle(); // interest rate model interestRateModel = new JumpRateModelV2( (5 * 10**18) / 100, // baseRatePerYear (12 * 10**18) / 100, // multiplierPerYear (24 * 10**18) / 100, // jumpMultiplierPerYear (80 * 10**18) / 100, // kink_ address(timelock) // owner ); /* configure comptroller: 1. unitrollerProxy as proxy with data storage; 2. comptrollerImpl as implementation; */ unitrollerProxy = new Unitroller(); comptrollerImpl = new Comptroller(); unitrollerProxyToImpl = Comptroller(address(unitrollerProxy)); unitrollerProxy._setPendingImplementation(address(comptrollerImpl)); // call from address(this) comptrollerImpl._become(unitrollerProxy); unitrollerProxyToImpl._setPriceOracle(priceOracle); // maximum fraction of origin loan that can be liquidated unitrollerProxyToImpl._setCloseFactor(500000000000000000); // 50% // collateral received as a multiplier of amount liquidator paid unitrollerProxyToImpl._setLiquidationIncentive(1080000000000000000); // 108% /* configure CToken: 1. CErc20Delegator as proxy; 2. CErc20Delegate as implementation; */ cTT1Delegate = new CErc20Delegate(); bytes memory data = new bytes(0x00); cTT1 = new CErc20Delegator( address(TT1), // underlying token ComptrollerInterface(address(unitrollerProxy)), InterestRateModel(address(interestRateModel)), // 2 * 10 ** 8 cTT1 = 1 TT1 2 * 10**8 * 10**18, "Compound TT1", // name "cTT1", // symbol 8, // decimals address(uint160(address(this))), // admin address(cTT1Delegate), // implementation data ); cTT1._setReserveFactor((25 * 10**18) / 100); // 25% interest charged for reserve // set price of TT1 priceOracle.setUnderlyingPrice(CToken(address(cTT1)), 1e18); // set markets supported by comptroller unitrollerProxyToImpl._supportMarket(CToken(address(cTT1))); // multiplier of collateral for borrowing cap unitrollerProxyToImpl._setCollateralFactor( CToken(address(cTT1)), (60 * 10**18) / 100 ); // valid collateral rate is 60% CToken[] memory ct = new CToken[](1); ct[0] = CToken(address(cTT1)); uint256[] memory mbc = new uint256[](1); mbc[0] = 0; uint256[] memory bs = new uint256[](1); bs[0] = (67 * 10**18) / 1000; uint256[] memory ss = new uint256[](1); ss[0] = (67 * 10**18) / 1000; unitrollerProxyToImpl._setMarketBorrowCaps(ct, mbc); unitrollerProxyToImpl._setCompSpeeds( ct, bs, // supplySpeed: Comp per block ss // borrowSpeed: Comp per block ); } }
address public TT1 = 0xe09D4de9f1dCC8A4d5fB19c30Fb53830F8e2a047;
contract Setup { address public TT1; Comp public comp; CErc20Delegator public cTT1; CErc20Delegate public cTT1Delegate; Unitroller public unitrollerProxy; Comptroller public comptrollerImpl; Comptroller public unitrollerProxyToImpl; JumpRateModelV2 public interestRateModel; SimplePriceOracle public priceOracle; Timelock public timelock; pragma solidity ^0.8.0; import "./CToken/CErc20Delegator.sol"; import "./Comptroller/Unitroller.sol"; import "./InterestModel/JumpRateModelV2.sol"; import "./Oracle/SimplePriceOracle.sol"; constructor(address tt1_) { TT1 = tt1_; timelock = new Timelock(msg.sender, uint256(1 seconds)); comp = new Comp(msg.sender); priceOracle = new SimplePriceOracle(); interestRateModel = new JumpRateModelV2( ); 1. unitrollerProxy as proxy with data storage; 2. comptrollerImpl as implementation; unitrollerProxy = new Unitroller(); comptrollerImpl = new Comptroller(); unitrollerProxyToImpl = Comptroller(address(unitrollerProxy)); unitrollerProxy._setPendingImplementation(address(comptrollerImpl)); comptrollerImpl._become(unitrollerProxy); unitrollerProxyToImpl._setPriceOracle(priceOracle); unitrollerProxyToImpl._setCloseFactor(500000000000000000); unitrollerProxyToImpl._setLiquidationIncentive(1080000000000000000); 1. CErc20Delegator as proxy; 2. CErc20Delegate as implementation; cTT1Delegate = new CErc20Delegate(); bytes memory data = new bytes(0x00); cTT1 = new CErc20Delegator( ComptrollerInterface(address(unitrollerProxy)), InterestRateModel(address(interestRateModel)), 2 * 10**8 * 10**18, data ); cTT1._setReserveFactor((25 * 10**18) / 100); priceOracle.setUnderlyingPrice(CToken(address(cTT1)), 1e18); unitrollerProxyToImpl._supportMarket(CToken(address(cTT1))); unitrollerProxyToImpl._setCollateralFactor( CToken(address(cTT1)), (60 * 10**18) / 100 ); CToken[] memory ct = new CToken[](1); ct[0] = CToken(address(cTT1)); uint256[] memory mbc = new uint256[](1); mbc[0] = 0; uint256[] memory bs = new uint256[](1); bs[0] = (67 * 10**18) / 1000; uint256[] memory ss = new uint256[](1); ss[0] = (67 * 10**18) / 1000; unitrollerProxyToImpl._setMarketBorrowCaps(ct, mbc); unitrollerProxyToImpl._setCompSpeeds( ct, ); } }
7,315,271
[ 1, 2867, 1071, 19912, 21, 273, 374, 6554, 5908, 40, 24, 323, 29, 74, 21, 72, 6743, 28, 37, 24, 72, 25, 74, 38, 3657, 71, 5082, 42, 70, 25, 7414, 5082, 42, 28, 73, 22, 69, 3028, 27, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 10939, 288, 203, 565, 1758, 225, 1071, 19912, 21, 31, 203, 565, 5427, 1071, 1161, 31, 203, 565, 29538, 1310, 3462, 15608, 639, 1071, 276, 1470, 21, 31, 203, 565, 29538, 1310, 3462, 9586, 1071, 276, 1470, 21, 9586, 31, 203, 565, 8380, 1539, 1071, 2836, 1539, 3886, 31, 203, 565, 1286, 337, 1539, 1071, 532, 337, 1539, 2828, 31, 203, 565, 1286, 337, 1539, 1071, 2836, 1539, 3886, 774, 2828, 31, 203, 565, 804, 2801, 4727, 1488, 58, 22, 1071, 16513, 4727, 1488, 31, 203, 565, 4477, 5147, 23601, 1071, 6205, 23601, 31, 203, 565, 12652, 292, 975, 1071, 1658, 292, 975, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 5666, 25165, 1268, 969, 19, 1441, 1310, 3462, 15608, 639, 18, 18281, 14432, 203, 5666, 25165, 799, 337, 1539, 19, 2802, 1539, 18, 18281, 14432, 203, 5666, 25165, 29281, 1488, 19, 26743, 4727, 1488, 58, 22, 18, 18281, 14432, 203, 5666, 25165, 23601, 19, 5784, 5147, 23601, 18, 18281, 14432, 203, 203, 565, 3885, 12, 2867, 3574, 21, 67, 13, 288, 203, 3639, 19912, 21, 273, 3574, 21, 67, 31, 203, 203, 3639, 1658, 292, 975, 273, 394, 12652, 292, 975, 12, 3576, 18, 15330, 16, 2254, 5034, 12, 21, 3974, 10019, 203, 3639, 1161, 273, 394, 5427, 12, 3576, 18, 15330, 1769, 203, 3639, 6205, 23601, 273, 394, 4477, 5147, 23601, 5621, 203, 3639, 16513, 4727, 1488, 273, 394, 804, 2801, 4727, 1488, 58, 22, 12, 203, 3639, 11272, 203, 5411, 404, 18, 2836, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.10; pragma experimental ABIEncoderV2; import {IGelatoCore, Provider, Task} from "../../../gelato_core/interfaces/IGelatoCore.sol"; import {IGelatoProviders, TaskSpec} from "../../../gelato_core/interfaces/IGelatoProviders.sol"; import {IGelatoProviderModule} from "../../../gelato_provider_modules/IGelatoProviderModule.sol"; contract ActionSubmitTask { IGelatoCore public immutable gelatoCore; constructor(address _gelatoCore) public { gelatoCore = IGelatoCore(_gelatoCore); } /// @dev will be delegate called by ds_proxy function submitTask(Provider memory _provider, Task memory _task, uint256 _expiryDate) public payable { gelatoCore.submitTask(_provider, _task, _expiryDate); } /// @dev will be delegate called by ds_proxy function submitTaskAndMultiProvide( Provider memory _provider, Task memory _task, uint256 _expiryDate, address _executor, IGelatoProviderModule[] memory _providerModules, uint256 _ethToDeposit ) public payable { gelatoCore.submitTask(_provider, _task, _expiryDate); TaskSpec[] memory taskSpecs = new TaskSpec[](0); IGelatoProviders(address(gelatoCore)).multiProvide{value: _ethToDeposit}( _executor, taskSpecs, _providerModules ); } /// @dev will be delegate called by ds_proxy function submitTaskCycle( Provider memory _provider, Task[] memory _tasks, uint256 _expiryDate, uint256 _cycles ) public payable { gelatoCore.submitTaskCycle(_provider, _tasks, _expiryDate, _cycles); } /// @dev will be delegate called by ds_proxy function submitTaskCycleAndMultiProvide( Provider memory _provider, Task[] memory _tasks, uint256 _expiryDate, uint256 _cycles, address _executor, IGelatoProviderModule[] memory _providerModules, uint256 _ethToDeposit ) public payable { gelatoCore.submitTaskCycle(_provider, _tasks, _expiryDate, _cycles); TaskSpec[] memory taskSpecs = new TaskSpec[](0); IGelatoProviders(address(gelatoCore)).multiProvide{value: _ethToDeposit}( _executor, taskSpecs, _providerModules ); } /// @dev will be delegate called by ds_proxy function submitTaskChain( Provider memory _provider, Task[] memory _tasks, uint256 _expiryDate, uint256 _sumOfRequestedTaskSubmits ) public payable { gelatoCore.submitTaskChain(_provider, _tasks, _expiryDate, _sumOfRequestedTaskSubmits); } /// @dev will be delegate called by ds_proxy function submitTaskChainAndMultiProvide( Provider memory _provider, Task[] memory _tasks, uint256 _expiryDate, uint256 _sumOfRequestedTaskSubmits, address _executor, IGelatoProviderModule[] memory _providerModules, uint256 _ethToDeposit ) public payable { gelatoCore.submitTaskChain(_provider, _tasks, _expiryDate, _sumOfRequestedTaskSubmits); TaskSpec[] memory taskSpecs = new TaskSpec[](0); IGelatoProviders(address(gelatoCore)).multiProvide{value: _ethToDeposit}( _executor, taskSpecs, _providerModules ); } }
@dev will be delegate called by ds_proxy
function submitTaskChain( Provider memory _provider, Task[] memory _tasks, uint256 _expiryDate, uint256 _sumOfRequestedTaskSubmits ) public payable { gelatoCore.submitTaskChain(_provider, _tasks, _expiryDate, _sumOfRequestedTaskSubmits); }
2,560,136
[ 1, 20194, 506, 7152, 2566, 635, 3780, 67, 5656, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4879, 2174, 3893, 12, 203, 3639, 7561, 3778, 389, 6778, 16, 203, 3639, 3837, 8526, 3778, 389, 9416, 16, 203, 3639, 2254, 5034, 389, 22409, 1626, 16, 203, 3639, 2254, 5034, 389, 1364, 951, 11244, 2174, 1676, 22679, 203, 565, 262, 203, 3639, 1071, 203, 3639, 8843, 429, 203, 565, 288, 203, 3639, 314, 292, 31093, 4670, 18, 9297, 2174, 3893, 24899, 6778, 16, 389, 9416, 16, 389, 22409, 1626, 16, 389, 1364, 951, 11244, 2174, 1676, 22679, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-04-28 */ // SPDX-License-Identifier: MIT //Developer Info: //Written by Ghazanfar Perdakh //Email: [email protected] //Whatsapp NO.: +923331578650 //fiverr: fiverr.com/ghazanfarperdakh // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: contracts/new.sol pragma solidity ^0.8.4; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerQueryForNonexistentToken(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 0; } /** * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); // Reentrancy protection if (_currentIndex != startTokenId) revert(); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev This is equivalent to _burn(tokenId, false) */ function _burn(uint256 tokenId) internal virtual { _burn(tokenId, false); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } pragma solidity ^0.8.7; contract Travelbots is ERC721A, Ownable { using Strings for uint256; string private uriPrefix ; string private uriSuffix = ".json"; string public hiddenURL ; uint256 public publicSaleCost = 0.07 ether; uint256 public preSaleCost = 0.055 ether; uint256 public whiteListCost = 0.04 ether; uint256 public vipSaleCost = 0.175 ether; uint16 public constant maxSupply = 6666; uint8 public maxMintAmountPerTxInPublicSale = 20; uint8 public maxMintAmountPerTx = 3; bool public whitelistPaused = true; bool public publicSalePaused = true; bool public preSalePaused = true; bool public VIPpaused = true; bool public reveal =false; bytes32 public whitelistMerkleRoot = 0x92a26021f02bf0889e65fe076091cd8b93fd43dbc22de2302e6ceb83bf3996c8; uint16 counter; constructor() ERC721A("Travelbots", "TRVB") { } function VIPMint(uint8 _mintAmount) external payable { uint16 totalSupply = uint16(totalSupply()); require(totalSupply + _mintAmount <= maxSupply, "Excedes max supply."); require(_mintAmount <= maxMintAmountPerTx, "Exceeds max per transaction."); require(!VIPpaused, "The contract is paused!"); require(msg.value == vipSaleCost * _mintAmount, "Insufficient funds!"); _safeMint(msg.sender , _mintAmount * 5 ); counter = counter + _mintAmount ; // counter limit is 500 because NFTs are sold in bulk and 500 x 5 = 2500 // VIP sale will be automatically paused after 2500 NFTs are minted in this phase if ( counter >= 500) { VIPpaused = true; counter = 0; } delete totalSupply; delete _mintAmount; } function presaleMint(uint16 _mintAmount) external payable { uint16 totalSupply = uint16(totalSupply()); require(totalSupply + _mintAmount <= maxSupply, "Excedes max supply."); require(_mintAmount <= maxMintAmountPerTx, "Exceeds max per transaction."); require(!preSalePaused, "The contract is paused!"); require(msg.value == preSaleCost * _mintAmount, "Insufficient funds!"); _safeMint(msg.sender , _mintAmount); counter = counter + _mintAmount ; // preSale will be automatically paused after 1000 NFTs are minted in this phase if ( counter >= 1000) { preSalePaused = true; counter = 0; } delete totalSupply; delete _mintAmount; } function publicMint(uint16 _mintAmount) external payable { uint16 totalSupply = uint16(totalSupply()); require(totalSupply + _mintAmount <= maxSupply, "Excedes max supply."); require(_mintAmount <= maxMintAmountPerTx, "Exceeds max per transaction."); require(!publicSalePaused, "The contract is paused!"); require(msg.value == publicSaleCost * _mintAmount, "Insufficient funds!"); _safeMint(msg.sender , _mintAmount); delete totalSupply; delete _mintAmount; } function Reserve(uint16 _mintAmount, address _receiver) external onlyOwner { uint16 totalSupply = uint16(totalSupply()); require(totalSupply + _mintAmount <= maxSupply, "Excedes max supply."); _safeMint(_receiver , _mintAmount); delete _mintAmount; delete _receiver; delete totalSupply; } function Airdrop(uint16 _mintAmount, address _receiver) external onlyOwner { uint16 totalSupply = uint16(totalSupply()); require(totalSupply + _mintAmount <= maxSupply, "Excedes max supply."); _safeMint(_receiver , _mintAmount); delete _mintAmount; delete _receiver; delete totalSupply; } function burn(uint _tokenID) external onlyOwner { _burn(_tokenID); } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require( _exists(_tokenId), "ERC721Metadata: URI query for nonexistent token" ); if ( reveal == false) { return hiddenURL; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString() ,uriSuffix)) : ""; } function setWhitelistPaused() external onlyOwner { whitelistPaused = !whitelistPaused; VIPpaused = true; counter = 0; } function setPreSalePaused() external onlyOwner { preSalePaused = !preSalePaused; whitelistPaused = true; counter = 0; } function setPublicSalePaused() external onlyOwner { publicSalePaused= !publicSalePaused; preSalePaused = true; counter = 0; } function setVIPSalePaused() external onlyOwner { VIPpaused= !VIPpaused; counter = 0; } function setWhitelistCost(uint256 _cost) external onlyOwner { whiteListCost = _cost; delete _cost; } function setPresaleCost(uint256 _cost) external onlyOwner { preSaleCost = _cost; delete _cost; } function setPublicSaleCost(uint256 _cost) external onlyOwner { publicSaleCost = _cost; delete _cost; } function setVIPSaleCost(uint256 _cost) external onlyOwner { vipSaleCost= _cost; delete _cost; } function setMaxMintPerTx(uint8 _limit) external onlyOwner{ maxMintAmountPerTx = _limit; delete _limit; } function setMaxMintPerTxInPublicSale(uint8 _limit) external onlyOwner{ maxMintAmountPerTxInPublicSale = _limit; delete _limit; } function setWhitelistMerkleRoot(bytes32 _whitelistMerkleRoot) external onlyOwner { whitelistMerkleRoot = _whitelistMerkleRoot; } function getLeafNode(address _leaf) internal pure returns (bytes32 temp) { return keccak256(abi.encodePacked(_leaf)); } function _verify(bytes32 leaf, bytes32[] memory proof) internal view returns (bool) { return MerkleProof.verify(proof, whitelistMerkleRoot, leaf); } function whitelistMint(uint8 _mintAmount, bytes32[] calldata merkleProof) external payable { bytes32 leafnode = getLeafNode(msg.sender); require(_verify(leafnode , merkleProof ), "Invalid merkle proof"); require (_mintAmount <= maxMintAmountPerTx, "Exceeds max tx per address"); require(!whitelistPaused, "Whitelist minting is over!"); require(msg.value == whiteListCost * _mintAmount, "Insufficient funds!"); uint16 totalSupply = uint16(totalSupply()); _safeMint(msg.sender , _mintAmount); counter = counter + _mintAmount ; // preSale will be automatically paused after 1000 NFTs are minted in this phase if ( counter >= 1000) { whitelistPaused = true; counter = 0; } delete totalSupply; delete _mintAmount; } function setBaseURI(string memory _uriPrefix) external onlyOwner { uriPrefix = _uriPrefix; } function setHiddenUri(string memory _uriPrefix) external onlyOwner { hiddenURL = _uriPrefix; } function setRevealed() external onlyOwner{ reveal = !reveal; } function withdraw() external onlyOwner { uint _balance = address(this).balance; payable(msg.sender).transfer(_balance ); } function _baseURI() internal view override returns (string memory) { return uriPrefix; } }
preSale will be automatically paused after 1000 NFTs are minted in this phase
function whitelistMint(uint8 _mintAmount, bytes32[] calldata merkleProof) external payable { bytes32 leafnode = getLeafNode(msg.sender); require(_verify(leafnode , merkleProof ), "Invalid merkle proof"); require (_mintAmount <= maxMintAmountPerTx, "Exceeds max tx per address"); require(!whitelistPaused, "Whitelist minting is over!"); require(msg.value == whiteListCost * _mintAmount, "Insufficient funds!"); uint16 totalSupply = uint16(totalSupply()); _safeMint(msg.sender , _mintAmount); counter = counter + _mintAmount ; if ( counter >= 1000) { whitelistPaused = true; counter = 0; } delete totalSupply; delete _mintAmount; }
2,094,385
[ 1, 1484, 30746, 225, 903, 506, 6635, 17781, 1839, 4336, 423, 4464, 87, 854, 312, 474, 329, 316, 333, 6855, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 915, 10734, 49, 474, 12, 11890, 28, 389, 81, 474, 6275, 16, 1731, 1578, 8526, 745, 892, 30235, 20439, 13, 3903, 8843, 429, 288, 203, 540, 203, 4202, 1731, 1578, 225, 7839, 2159, 273, 336, 16545, 12, 3576, 18, 15330, 1769, 203, 4202, 203, 4202, 2583, 24899, 8705, 12, 12070, 2159, 269, 282, 30235, 20439, 262, 16, 225, 315, 1941, 30235, 14601, 8863, 203, 4202, 2583, 261, 67, 81, 474, 6275, 1648, 943, 49, 474, 6275, 2173, 4188, 16, 315, 424, 5288, 87, 943, 2229, 1534, 1758, 8863, 203, 4202, 203, 203, 203, 565, 2583, 12, 5, 20409, 28590, 16, 315, 18927, 312, 474, 310, 353, 1879, 4442, 1769, 203, 565, 2583, 12, 3576, 18, 1132, 422, 27859, 8018, 380, 389, 81, 474, 6275, 16, 315, 5048, 11339, 284, 19156, 4442, 1769, 203, 203, 4202, 2254, 2313, 2078, 3088, 1283, 273, 2254, 2313, 12, 4963, 3088, 1283, 10663, 203, 377, 389, 4626, 49, 474, 12, 3576, 18, 15330, 269, 389, 81, 474, 6275, 1769, 203, 1850, 3895, 273, 3895, 397, 389, 81, 474, 6275, 274, 203, 1377, 309, 261, 3895, 1545, 4336, 13, 203, 1377, 288, 203, 4202, 10734, 28590, 273, 638, 31, 203, 4202, 3895, 273, 374, 31, 203, 1377, 289, 203, 1377, 1430, 2078, 3088, 1283, 31, 203, 1377, 1430, 389, 81, 474, 6275, 31, 203, 4202, 203, 377, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.5.0; //Libraries import './libraries/SafeMath.sol'; // Inheritance import "./Ownable.sol"; import './interfaces/IFeePool.sol'; // Internal references import "./interfaces/IERC20.sol"; import "./interfaces/IAddressResolver.sol"; import "./adapters/interfaces/IBaseUbeswapAdapter.sol"; contract FeePool is Ownable, IFeePool { using SafeMath for uint; IAddressResolver public immutable ADDRESS_RESOLVER; mapping (address => uint) public balances; address[] public positionKeys; uint public totalSupply; constructor(IAddressResolver _addressResolver) public Ownable() { ADDRESS_RESOLVER = _addressResolver; } /* ========== VIEWS ========== */ /** * @notice Returns the number of fee tokens the user has * @param account Address of the user * @return uint Number of fee tokens */ function getTokenBalance(address account) external view override returns (uint) { require(account != address(0), "Invalid address"); return balances[account]; } /** * @dev Returns the currency address and balance of each position the pool has, as well as the cumulative value * @return (address[], uint[], uint) Currency address and balance of each position the pool has, and the cumulative value of positions */ function getPositionsAndTotal() public view override returns (address[] memory, uint[] memory, uint) { address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter"); address[] memory addresses = new address[](positionKeys.length); uint[] memory positionBalances = new uint[](positionKeys.length); uint sum = 0; for (uint i = 0; i < positionKeys.length; i++) { positionBalances[i] = IERC20(positionKeys[i]).balanceOf(address(this)); addresses[i] = positionKeys[i]; uint numberOfDecimals = IERC20(positionKeys[i]).decimals(); uint USDperToken = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(positionKeys[i]); uint positionBalanceInUSD = positionBalances[i].mul(USDperToken).div(10 ** numberOfDecimals); sum = sum.add(positionBalanceInUSD); } return (addresses, positionBalances, sum); } /** * @dev Returns the value of the pool in USD * @return uint Value of the pool in USD */ function getPoolBalance() public view override returns (uint) { (,, uint positionBalance) = getPositionsAndTotal(); return positionBalance; } /** * @dev Returns the balance of the user in USD * @return uint Balance of the user in USD */ function getUSDBalance(address user) public view override returns (uint) { require(user != address(0), "Invalid address"); uint poolBalance = getPoolBalance(); return poolBalance.mul(balances[user]).div(totalSupply); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Allow a user to claim available fees in the specified currency * @param currencyKey Address of the currency to claim * @param numberOfTokens Number of tokens to claim in the given currency */ function claimAvailableFees(address currencyKey, uint numberOfTokens) external override { require(currencyKey != address(0), "FeePool: Invalid currency key"); require(numberOfTokens > 0, "FeePool: Number of tokens must be greater than 0"); uint poolAssetBalance = IERC20(currencyKey).balanceOf(address(this)); uint tokensAvailableToWithdraw = poolAssetBalance.mul(balances[msg.sender]).div(totalSupply); require(tokensAvailableToWithdraw >= numberOfTokens, "FeePool: Not enough tokens in given currency"); //Calculate number of fee tokens address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter"); uint USDperAssetToken = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(currencyKey); uint numberOfDecimals = IERC20(currencyKey).decimals(); uint feeUSDValue = USDperAssetToken.mul(numberOfTokens).div(10 ** numberOfDecimals); uint poolUSDBalance = getPoolBalance(); uint numberOfFeeTokens = totalSupply.mul(feeUSDValue).div(poolUSDBalance); //Update state variables balances[msg.sender] = balances[msg.sender].sub(numberOfFeeTokens); totalSupply = totalSupply.sub(numberOfFeeTokens); //Transfer asset to user IERC20(currencyKey).transfer(msg.sender, numberOfTokens); //Find index of position in positionKeys array uint index; for (index = 0; index < positionKeys.length; index++) { if (positionKeys[index] == currencyKey) { break; } } //Remove position key if no balance left if (IERC20(positionKeys[index]).balanceOf(address(this)) == 0) { positionKeys[index] = positionKeys[positionKeys.length - 1]; positionKeys.pop(); } emit ClaimedFees(msg.sender, currencyKey, numberOfTokens, block.timestamp); } /** * @notice Adds fees to user * @notice Function gets called by Pool whenever users withdraw for a profit * @param user Address of the user * @param feeAmount USD value of fee */ function addFees(address user, uint feeAmount) public override onlyPoolOrStrategy { require(feeAmount > 0, "Amount must be greater than 0"); require(user != address(0), "Invalid address"); uint poolBalance = getPoolBalance(); uint numberOfFeeTokens = (totalSupply > 0) ? totalSupply.mul(feeAmount).div(poolBalance) : feeAmount; balances[user] = balances[user].add(numberOfFeeTokens); totalSupply = totalSupply.add(numberOfFeeTokens); emit AddedFees(user, feeAmount, block.timestamp); } /** * @notice Adds currency key to positionKeys array if no position yet * @notice Function gets called by Pool whenever users pay performance fee * @param positions Address of each position the pool/bot had when paying fee */ function addPositionKeys(address[] memory positions) public override onlyPoolOrStrategy { //Add positions to positionKeys array if no existing position for (uint i = 0; i < positions.length; i++) { if (IERC20(positions[i]).balanceOf(address(this)) == 0) { positionKeys.push(positions[i]); } } } /* ========== MODIFIERS ========== */ modifier onlyPoolOrStrategy() { require(ADDRESS_RESOLVER.checkIfPoolAddressIsValid(msg.sender) || ADDRESS_RESOLVER.checkIfStrategyAddressIsValid(msg.sender), "Only the Pool or Strategy contract can call this function"); _; } /* ========== EVENTS ========== */ event ClaimedFees(address user, address currencyKey, uint numberOfTokens, uint timestamp); event AddedFees(address user, uint numberOfFeeTokens, uint timestamp); }
* @dev Returns the currency address and balance of each position the pool has, as well as the cumulative value @return (address[], uint[], uint) Currency address and balance of each position the pool has, and the cumulative value of positions/
function getPositionsAndTotal() public view override returns (address[] memory, uint[] memory, uint) { address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter"); address[] memory addresses = new address[](positionKeys.length); uint[] memory positionBalances = new uint[](positionKeys.length); uint sum = 0; for (uint i = 0; i < positionKeys.length; i++) { positionBalances[i] = IERC20(positionKeys[i]).balanceOf(address(this)); addresses[i] = positionKeys[i]; uint numberOfDecimals = IERC20(positionKeys[i]).decimals(); uint USDperToken = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(positionKeys[i]); uint positionBalanceInUSD = positionBalances[i].mul(USDperToken).div(10 ** numberOfDecimals); sum = sum.add(positionBalanceInUSD); } return (addresses, positionBalances, sum); }
2,572,489
[ 1, 1356, 326, 5462, 1758, 471, 11013, 434, 1517, 1754, 326, 2845, 711, 16, 487, 5492, 487, 326, 15582, 460, 327, 261, 2867, 63, 6487, 2254, 63, 6487, 2254, 13, 13078, 1758, 471, 11013, 434, 1517, 1754, 326, 2845, 711, 16, 471, 326, 15582, 460, 434, 6865, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 11024, 1876, 5269, 1435, 1071, 1476, 3849, 1135, 261, 2867, 8526, 3778, 16, 2254, 8526, 3778, 16, 2254, 13, 288, 203, 3639, 1758, 1026, 57, 70, 281, 91, 438, 4216, 1887, 273, 11689, 10203, 67, 17978, 2204, 18, 588, 8924, 1887, 2932, 2171, 57, 70, 281, 91, 438, 4216, 8863, 203, 3639, 1758, 8526, 3778, 6138, 273, 394, 1758, 8526, 12, 3276, 2396, 18, 2469, 1769, 203, 3639, 2254, 8526, 3778, 1754, 38, 26488, 273, 394, 2254, 8526, 12, 3276, 2396, 18, 2469, 1769, 203, 3639, 2254, 2142, 273, 374, 31, 203, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 1754, 2396, 18, 2469, 31, 277, 27245, 203, 3639, 288, 203, 5411, 1754, 38, 26488, 63, 77, 65, 273, 467, 654, 39, 3462, 12, 3276, 2396, 63, 77, 65, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 5411, 6138, 63, 77, 65, 273, 1754, 2396, 63, 77, 15533, 203, 203, 5411, 2254, 7922, 31809, 273, 467, 654, 39, 3462, 12, 3276, 2396, 63, 77, 65, 2934, 31734, 5621, 203, 5411, 2254, 587, 9903, 457, 1345, 273, 467, 2171, 57, 70, 281, 91, 438, 4216, 12, 1969, 57, 70, 281, 91, 438, 4216, 1887, 2934, 588, 5147, 12, 3276, 2396, 63, 77, 19226, 203, 5411, 2254, 1754, 13937, 382, 3378, 40, 273, 1754, 38, 26488, 63, 77, 8009, 16411, 12, 3378, 40, 457, 1345, 2934, 2892, 12, 2163, 2826, 7922, 31809, 1769, 203, 5411, 2142, 273, 2142, 18, 1289, 12, 3276, 13937, 382, 3378, 40, 1769, 203, 3639, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; import "./SaleBase.sol"; /** * @title Base auction contract * @author Sanan bin Tahir * @dev This is the base auction contract which implements the auction functionality */ contract AuctionBase is SaleBase { using Address for address payable; // auction struct to keep track of the auctions struct Auction { bool isArtistNFT; bool isERC721; address seller; address nftContract; address buyer; uint128 currentPrice; uint64 duration; uint64 startedAt; uint16 platformCut; uint256 amount; // only relevant for ERC1155 } // mapping for tokenId to its auction mapping (address => mapping(uint256 => Auction)) tokenIdToAuction; // The minimum percentage difference between the last bid amount and the current bid. uint8 public minBidIncrementPercentage = 50; event AuctionCreated(bool isArtistNFT, bool isERC721, uint256 amount, uint256 tokenId, uint256 startingPrice, uint64 startingTime, uint256 duration, address seller, uint16 platformCut); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, uint256 duration, address winner, address seller, uint16 platformCut); event BidCreated(uint256 tokenId, uint256 totalPrice, uint256 duration, address winner, address seller); /** * @dev Add the auction to the mapping and emit the AuctionCreated event, duration must meet the requirements * @param _tokenId ID of the token to auction * @param _auction Reference to the auction struct to add to the mapping */ function _addAuction(uint256 _tokenId, Auction memory _auction) internal { // check minimum and maximum time requirements require(_auction.duration >= 1 hours && _auction.duration <= 30 days, "time requirement failed"); // update mapping tokenIdToAuction[_auction.nftContract][_tokenId] = _auction; // emit event emit AuctionCreated( _auction.isArtistNFT, _auction.isERC721, _auction.amount, _tokenId, _auction.currentPrice, _auction.startedAt, _auction.duration, _auction.seller, _auction.platformCut ); } /** * @dev Remove the auction from the mapping (sets everything to zero/false) * @param _nftAddress Address of NFT * @param _tokenId ID of the token to remove auction of */ function _removeAuction(address _nftAddress, uint256 _tokenId) internal { delete tokenIdToAuction[_nftAddress][_tokenId]; } /** * @dev Internal function to check the current price of the auction * @param auction Reference to the auction to check price of * @return uint128 The current price of the auction */ function _currentPrice(Auction storage auction) internal view returns (uint128) { return (auction.currentPrice); } /** * @dev Internal function to return the bid to the previous bidder if there was one * @param _destination Address of the previous bidder * @param _amount Amount to return to the previous bidder */ function _returnBid(address payable _destination, uint256 _amount) private { // zero address means there was no previous bidder if (_destination != address(0)) { _destination.sendValue(_amount); } } /** * @dev Internal function to check if an auction started. By default startedAt is at 0 * @param _auction Reference to the auction struct to check * @return bool Weather the auction has started */ function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0 && _auction.startedAt <= block.timestamp); } /** * @dev Internal function to implement the bid functionality * @param _nftAddress Address of NFT * @param _tokenId ID of the token to bid upon * @param _bidAmount Amount to bid */ function _bid(address _nftAddress, uint _tokenId, uint _bidAmount) internal { // get reference to the auction struct Auction storage auction = tokenIdToAuction[_nftAddress][_tokenId]; // check if the item is on auction require(_isOnAuction(auction), "Item is not on auction"); // check if auction time has ended uint256 secondsPassed = block.timestamp - auction.startedAt; require(secondsPassed <= auction.duration, "Auction time has ended"); // check if bid is higher than the previous one uint256 price = auction.currentPrice; require(_bidAmount > price, "Bid is too low"); require(_bidAmount >= (price + ((price * minBidIncrementPercentage) / 1000)), "increment not met"); // return the previous bidder's bid amount _returnBid(payable(auction.buyer), auction.currentPrice); // update the current bid amount and the bidder address auction.currentPrice = uint128(_bidAmount); auction.buyer = msg.sender; // if the bid is made in the last 15 minutes, increase the duration of the // auction so that the timer resets to 15 minutes uint256 timeRemaining = auction.duration - secondsPassed; if (timeRemaining <= 15 minutes) { uint256 timeToAdd = 15 minutes - timeRemaining; auction.duration += uint64(timeToAdd); } emit BidCreated( _tokenId, auction.currentPrice, auction.duration, auction.buyer, auction.seller ); } /** * @dev Internal function to finish the auction after the auction time has ended * @param _nftAddress Address of NFT * @param _tokenId ID of the token to finish auction of */ function _finishAuction(address _nftAddress, uint256 _tokenId) internal { // using storage for _isOnAuction Auction storage auction = tokenIdToAuction[_nftAddress][_tokenId]; // check if token was on auction require(_isOnAuction(auction), "Token was not on auction"); // check if auction time has ended uint256 secondsPassed = block.timestamp - auction.startedAt; require(secondsPassed > auction.duration, "Auction hasn't ended"); // using struct to avoid stack too deep error Auction memory referenceAuction = auction; address _nftContract = auction.nftContract; // delete the auction _removeAuction(_nftAddress, _tokenId); // if there was no successful bid, return token to the seller if (referenceAuction.buyer == address(0)) { _transfer(_nftContract, referenceAuction.seller, _tokenId, referenceAuction.isERC721, referenceAuction.amount); emit AuctionSuccessful( _tokenId, 0, referenceAuction.duration, referenceAuction.seller, referenceAuction.seller, referenceAuction.platformCut ); } // if there was a successful bid, pay the seller and transfer the token to the buyer else { _payout( referenceAuction.isArtistNFT, payable(referenceAuction.seller), referenceAuction.platformCut, referenceAuction.currentPrice ); _transfer(_nftContract, referenceAuction.buyer, _tokenId, referenceAuction.isERC721, referenceAuction.amount); emit AuctionSuccessful( _tokenId, referenceAuction.currentPrice, referenceAuction.duration, referenceAuction.buyer, referenceAuction.seller, referenceAuction.platformCut ); } } /** * @dev This is an internal function to end auction meant to only be used as a safety * mechanism if an NFT got locked within the contract. Can only be called by the super admin * after a period of 7 days has passed since the auction ended * @param _nftAddress Address of NFT * @param _tokenId Id of the token to end auction of * @param _nftBeneficiary Address to send the NFT to * @param _paymentBeneficiary Address to send the payment to */ function _forceFinishAuction( address _nftAddress, uint256 _tokenId, address _nftBeneficiary, address _paymentBeneficiary ) internal { // using storage for _isOnAuction Auction storage auction = tokenIdToAuction[_nftAddress][_tokenId]; // check if token was on auction require(_isOnAuction(auction), "Token was not on auction"); // check if auction time has ended uint256 secondsPassed = block.timestamp - auction.startedAt; require(secondsPassed > auction.duration, "Auction hasn't ended"); // check if its been more than 7 days since auction ended require(secondsPassed - auction.duration >= 7 days); // using struct to avoid stack too deep error Auction memory referenceAuction = auction; // delete the auction _removeAuction(_nftAddress, _tokenId); // transfer ether to the beneficiary payable(_paymentBeneficiary).sendValue(referenceAuction.currentPrice); // transfer nft to the nft beneficiary _transfer(referenceAuction.nftContract, _nftBeneficiary, _tokenId, referenceAuction.isERC721, referenceAuction.amount); emit AuctionSuccessful( _tokenId, 0, referenceAuction.duration, _nftBeneficiary, _paymentBeneficiary, referenceAuction.platformCut ); } } /** * @title Auction sale contract that provides external functions * @author Sanan bin Tahir * @dev Implements the external and public functions of the auction implementation */ contract AuctionSale is AuctionBase { // sanity check for the nft contract bool public isEcchiSaleAuction = true; /** * @dev Internal function to create auction. * @param _isArtistNFT If this NFT is an artist NFT (different fees) * @param _isERC721 If this token is an ERC721 token * @param _tokenId ID of the token to create auction for * @param _amount Amount of tokens in this sale (only relevant for ERC1155) * @param _nftAddress Address of NFT * @param _startingPrice Starting price of the auction in wei * @param _duration Duration of the auction in seconds * @param _seller Address of the seller of the NFT * @param _platformCut The cut that goes to the platform if it is a primary sale */ function createAuctionSale( bool _isArtistNFT, bool _isERC721, uint256 _tokenId, uint256 _amount, // only relevant for ERC1155 address _nftAddress, uint128 _startingPrice, uint64 _startingTime, uint64 _duration, address _seller, uint16 _platformCut ) internal { // create and add the auction Auction memory auction = Auction( _isArtistNFT, _isERC721, _seller, _nftAddress, address(0), uint128(_startingPrice), uint64(_duration), _startingTime, _platformCut, _amount ); _addAuction(_tokenId, auction); } /** * @dev External payable bid function. Sellers can not bid on their own artworks * @param _nftAddress Address of NFT * @param _tokenId ID of the token to bid on */ function bid(address _nftAddress, uint256 _tokenId) external payable { // do not allow sellers to bid on their own artwork require(tokenIdToAuction[_nftAddress][_tokenId].seller != msg.sender, "Sellers not allowed"); _bid(_nftAddress, _tokenId, msg.value); } /** * @dev External function to finish the auction. Currently can be called by anyone * @param _nftAddress Address of NFT * @param _tokenId ID of the token to finish auction of */ function finishAuction(address _nftAddress, uint256 _tokenId) external { _finishAuction(_nftAddress, _tokenId); } /** * @dev External view function to get the details of an auction * @param _nftAddress Address of NFT * @param _tokenId ID of the token to get the auction information of * @return seller Address of the seller * @return buyer Address of the buyer * @return currentPrice Current Price of the auction in wei * @return duration Duration of the auction in seconds * @return startedAt Unix timestamp for when the auction started */ function getAuction(address _nftAddress, uint256 _tokenId) external view returns ( address seller, address buyer, uint256 currentPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_nftAddress][_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, auction.buyer, auction.currentPrice, auction.duration, auction.startedAt ); } /** * @dev External view function to get the current price of an auction * @param _nftAddress Address of NFT * @param _tokenId ID of the token to get the current price of * @return uint128 Current price of the auction in wei */ function getCurrentPrice(address _nftAddress, uint256 _tokenId) external view returns (uint128) { Auction storage auction = tokenIdToAuction[_nftAddress][_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } /** * @dev This is an internal function to end auction meant to only be used as a safety * mechanism if an NFT got locked within the contract. Can only be called by the super admin * after a period f 7 days has passed since the auction ended * @param _nftAddress Address of NFT * @param _tokenId Id of the token to end auction of * @param _nftBeneficiary Address to send the NFT to * @param _paymentBeneficiary Address to send the payment to */ function forceFinishAuction( address _nftAddress, uint256 _tokenId, address _nftBeneficiary, address _paymentBeneficiary ) external onlyRole(DEFAULT_ADMIN_ROLE) { _forceFinishAuction(_nftAddress, _tokenId, _nftBeneficiary, _paymentBeneficiary); } }
* @dev External payable bid function. Sellers can not bid on their own artworks @param _nftAddress Address of NFT @param _tokenId ID of the token to bid on/ do not allow sellers to bid on their own artwork
function bid(address _nftAddress, uint256 _tokenId) external payable { require(tokenIdToAuction[_nftAddress][_tokenId].seller != msg.sender, "Sellers not allowed"); _bid(_nftAddress, _tokenId, msg.value); }
12,767,976
[ 1, 6841, 8843, 429, 9949, 445, 18, 348, 1165, 414, 848, 486, 9949, 603, 3675, 4953, 3688, 18597, 225, 389, 82, 1222, 1887, 5267, 434, 423, 4464, 225, 389, 2316, 548, 1599, 434, 326, 1147, 358, 9949, 603, 19, 741, 486, 1699, 357, 3135, 358, 9949, 603, 3675, 4953, 3688, 1252, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 9949, 12, 2867, 389, 82, 1222, 1887, 16, 2254, 5034, 389, 2316, 548, 13, 3903, 8843, 429, 288, 203, 3639, 2583, 12, 2316, 28803, 37, 4062, 63, 67, 82, 1222, 1887, 6362, 67, 2316, 548, 8009, 1786, 749, 480, 1234, 18, 15330, 16, 203, 5411, 315, 55, 1165, 414, 486, 2935, 8863, 203, 203, 3639, 389, 19773, 24899, 82, 1222, 1887, 16, 389, 2316, 548, 16, 1234, 18, 1132, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.21; import "@openzeppelin/contracts/utils/Strings.sol"; contract EcommerceStore { enum ProductStatus { Open, Sold, UnSold } enum ProductCondition { New, Used } uint256 public productIndex; mapping(address => mapping(uint256 => Product)) stores; mapping(uint256 => address) productIdInStore; // 产品id 关联 哪个用户 struct Product { uint256 id; string name; string category; string imageLink; string descLink; uint256 auctionStartTime; // 拍卖开始时间 uint256 auctionEndTime; // 拍卖结束时间 uint256 totalBids; uint256 startPrice; // 起拍价格 address highestBidder; // 最高出价人 uint256 highestBid; uint256 secondHighestBid; ProductStatus status; ProductCondition condition; mapping(address => mapping(bytes32 => Bid)) bids; } struct Bid { address bidder; uint256 productId; uint256 value; bool revealed; } constructor() { productIndex = 0; } function addProductToStore( string memory _name, string memory _category, string memory _imageLink, string memory _descLink, uint256 _auctionStartTime, uint256 _auctionEndTime, uint256 _startPrice, uint256 _productCondition ) public { require(_auctionStartTime < _auctionEndTime); productIndex += 1; Product storage product = stores[msg.sender][productIndex]; product.name = _name; product.category = _category; product.imageLink = _imageLink; product.descLink = _descLink; product.auctionStartTime = _auctionStartTime; product.auctionEndTime = _auctionEndTime; product.startPrice = _startPrice; product.condition = ProductCondition(_productCondition); product.status = ProductStatus.Open; product.highestBidder = address(0); product.highestBid = 0; product.secondHighestBid = 0; product.totalBids = 0; productIdInStore[productIndex] = msg.sender; } function getProduct(uint256 _productId) public view returns (string[10] memory, string[10] memory) { Product storage product = stores[productIdInStore[_productId]][ _productId ]; string[10] memory returnNames = [ "id", "name", "category", "imageLink", "descLink", "auctionStartTime", "auctionEndTime", "startPrice", "status", "condition" ]; string[10] memory returnData = [ Strings.toString(product.id), product.name, product.category, product.imageLink, product.descLink, Strings.toString(product.auctionStartTime), Strings.toString(product.auctionEndTime), Strings.toString(product.startPrice), Strings.toString(uint(product.status)), Strings.toString(uint(product.condition)) ]; return ( returnNames, returnData ); } function bid(uint256 _productId, bytes32 _bid) public payable returns (bool) { Product storage product = stores[productIdInStore[_productId]][ _productId ]; require(block.timestamp >= product.auctionStartTime); require(block.timestamp <= product.auctionEndTime); require(msg.value > product.startPrice); require(product.bids[msg.sender][_bid].bidder == address(0)); product.bids[msg.sender][_bid] = Bid( msg.sender, _productId, msg.value, false ); product.totalBids += 1; return true; } function revealBid( uint256 _productId, string memory _amount, string memory _secret ) public { Product storage product = stores[productIdInStore[_productId]][ _productId ]; require(block.timestamp > product.auctionEndTime, "Still in bid"); bytes32 sealedBid = keccak256(abi.encodePacked(_amount, _secret)); Bid memory bidInfo = product.bids[msg.sender][sealedBid]; require(bidInfo.bidder > address(0), "bidder not null"); require(bidInfo.revealed == false, "bid has been deal"); uint256 refund; uint256 amount = stringToUint(_amount); if (bidInfo.value < amount) { refund = bidInfo.value; } else { if (address(product.highestBidder) == address(0)) { product.highestBidder = msg.sender; product.highestBid = amount; product.secondHighestBid = product.startPrice; refund = bidInfo.value - amount; } else { if (amount > product.highestBid) { product.secondHighestBid = product.highestBid; payable(product.highestBidder).transfer(product.highestBid); product.highestBidder = msg.sender; product.highestBid = amount; refund = bidInfo.value - amount; } else if (amount > product.secondHighestBid) { product.secondHighestBid = amount; refund = bidInfo.value; } else { refund = bidInfo.value; } } } product.bids[msg.sender][sealedBid].revealed = true; if (refund > 0) { payable(msg.sender).transfer(refund); } } function highestBidderInfo(uint256 _productId) public view returns ( address, uint256, uint256 ) { Product storage product = stores[productIdInStore[_productId]][ _productId ]; return ( product.highestBidder, product.highestBid, product.secondHighestBid ); } function totalBids(uint256 _productId) public view returns (uint256) { Product storage product = stores[productIdInStore[_productId]][ _productId ]; return product.totalBids; } function stringToUint(string memory s) private pure returns (uint256) { bytes memory b = bytes(s); uint256 result = 0; for (uint256 i = 0; i < b.length; i++) { if (b[i] >= 0x30 && b[i] <= 0x39) { result = result * 10 + (uint8(b[i]) - 48); } } return result; } }
SPDX-License-Identifier: MIT
pragma solidity >=0.6.21;
12,713,967
[ 1, 3118, 28826, 17, 13211, 17, 3004, 30, 490, 1285, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 683, 9454, 18035, 560, 1545, 20, 18, 26, 18, 5340, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; /** * @title BDACoin * @author BDACoin * @dev BDACoin is an ERC223 Token with ERC20 functions and events * Fully backward compatible with ERC20 */ /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization * control functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the * sender account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * 彡(^)(^) * @title ERC223 * @dev ERC223 contract interface with ERC20 functions and events * Fully backward compatible with ERC20 * Recommended implementation used at https://github.com/Dexaran/ERC223-token-standard/tree/Recommended */ contract ERC223 { uint public totalSupply; // ERC223 and ERC20 functions and events function balanceOf(address who) public view returns (uint); function totalSupply() public view returns (uint256 _supply); function transfer(address to, uint value) public returns (bool ok); function transfer(address to, uint value, bytes data) public returns (bool ok); function transfer(address to, uint value, bytes data, string customFallback) public returns (bool ok); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); // ERC223 functions function name() public view returns (string _name); function symbol() public view returns (string _symbol); function decimals() public view returns (uint8 _decimals); // ERC20 functions and events function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } /** * @title ContractReceiver * @dev Contract that is working with ERC223 tokens */ contract ContractReceiver { struct TKN { address sender; uint value; bytes data; bytes4 sig; } function tokenFallback(address _from, uint _value, bytes _data) public pure { TKN memory tkn; tkn.sender = _from; tkn.value = _value; tkn.data = _data; uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24); tkn.sig = bytes4(u); /* * tkn variable is analogue of msg variable of Ether transaction * tkn.sender is person who initiated this token transaction (analogue of msg.sender) * tkn.value the number of tokens that were sent (analogue of msg.value) * tkn.data is data of token transaction (analogue of msg.data) * tkn.sig is 4 bytes signature of function if data of token transaction is a function execution */ } } /** * @title BDACoin * @author BLACK DIA COIN TEAM * @dev BDACoin is an ERC223 Token with ERC20 functions and events * Fully backward compatible with ERC20 */ contract BDACoin is ERC223, Ownable { using SafeMath for uint256; string public name = "BLACK DIA COIN"; string public symbol = "BDA"; string public constant AAcontributors = "BLACK DIA COIN TEAM"; uint8 public decimals = 8; uint256 public totalSupply = 1e10 * 4e8; uint256 public distributeAmount = 0; bool public mintingFinished = false; mapping(address => uint256) public balanceOf; mapping(address => mapping (address => uint256)) public allowance; mapping (address => bool) public frozenAccount; mapping (address => uint256) public unlockUnixTime; event FrozenFunds(address indexed target, bool frozen); event LockedFunds(address indexed target, uint256 locked); event Burn(address indexed from, uint256 amount); event Mint(address indexed to, uint256 amount); event MintFinished(); /** * @dev Constructor is called only once and can not be called again */ function BDACoin() public { balanceOf[msg.sender] = totalSupply; } function name() public view returns (string _name) { return name; } function symbol() public view returns (string _symbol) { return symbol; } function decimals() public view returns (uint8 _decimals) { return decimals; } function totalSupply() public view returns (uint256 _totalSupply) { return totalSupply; } function balanceOf(address _owner) public view returns (uint256 balance) { return balanceOf[_owner]; } /** * @dev Prevent targets from sending or receiving tokens * @param targets Addresses to be frozen * @param isFrozen either to freeze it or not */ function freezeAccounts(address[] targets, bool isFrozen) onlyOwner public { require(targets.length > 0); for (uint j = 0; j < targets.length; j++) { require(targets[j] != 0x0); frozenAccount[targets[j]] = isFrozen; FrozenFunds(targets[j], isFrozen); } } /** * @dev Prevent targets from sending or receiving tokens by setting Unix times * @param targets Addresses to be locked funds * @param unixTimes Unix times when locking up will be finished */ function lockupAccounts(address[] targets, uint[] unixTimes) onlyOwner public { require(targets.length > 0 && targets.length == unixTimes.length); for(uint j = 0; j < targets.length; j++){ require(unlockUnixTime[targets[j]] < unixTimes[j]); unlockUnixTime[targets[j]] = unixTimes[j]; LockedFunds(targets[j], unixTimes[j]); } } /** * @dev Function that is called when a user or another contract wants to transfer funds */ function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data)); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } else { return transferToAddress(_to, _value, _data); } } function transfer(address _to, uint _value, bytes _data) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } /** * @dev Standard function transfer similar to ERC20 transfer with no _data * Added due to backwards compatibility reasons */ function transfer(address _to, uint _value) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); 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 is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length > 0); } // function that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } // function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * Added due to backwards compatibility with ERC20 * @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 success) { require(_to != address(0) && _value > 0 && balanceOf[_from] >= _value && allowance[_from][msg.sender] >= _value && frozenAccount[_from] == false && frozenAccount[_to] == false && now > unlockUnixTime[_from] && now > unlockUnixTime[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Allows _spender to spend no more than _value tokens in your behalf * Added due to backwards compatibility with ERC20 * @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; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender * Added due to backwards compatibility with ERC20 * @param _owner address The address which owns the funds * @param _spender address The address which will spend the funds */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowance[_owner][_spender]; } /** * @dev Burns a specific amount of tokens. * @param _from The address that will burn the tokens. * @param _unitAmount The amount of token to be burned. */ function burn(address _from, uint256 _unitAmount) onlyOwner public { require(_unitAmount > 0 && balanceOf[_from] >= _unitAmount); balanceOf[_from] = balanceOf[_from].sub(_unitAmount); totalSupply = totalSupply.sub(_unitAmount); Burn(_from, _unitAmount); } modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _unitAmount The amount of tokens to mint. */ function mint(address _to, uint256 _unitAmount) onlyOwner canMint public returns (bool) { require(_unitAmount > 0); totalSupply = totalSupply.add(_unitAmount); balanceOf[_to] = balanceOf[_to].add(_unitAmount); Mint(_to, _unitAmount); Transfer(address(0), _to, _unitAmount); return true; } /** * @dev Function to stop minting new tokens. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } /** * @dev Function to distribute tokens to the list of addresses by the provided amount */ function distributeAirdrop(address[] addresses, uint256 amount) public returns (bool) { require(amount > 0 && addresses.length > 0 && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); amount = amount.mul(1e8); uint256 totalAmount = amount.mul(addresses.length); require(balanceOf[msg.sender] >= totalAmount); for (uint j = 0; j < addresses.length; j++) { require(addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amount); Transfer(msg.sender, addresses[j], amount); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; } function distributeAirdrop(address[] addresses, uint[] amounts) public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); uint256 totalAmount = 0; for(uint j = 0; j < addresses.length; j++){ require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e8); totalAmount = totalAmount.add(amounts[j]); } require(balanceOf[msg.sender] >= totalAmount); for (j = 0; j < addresses.length; j++) { balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amounts[j]); Transfer(msg.sender, addresses[j], amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; } /** * @dev Function to collect tokens from the list of addresses */ function collectTokens(address[] addresses, uint[] amounts) onlyOwner public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length); uint256 totalAmount = 0; for (uint j = 0; j < addresses.length; j++) { require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e8); require(balanceOf[addresses[j]] >= amounts[j]); balanceOf[addresses[j]] = balanceOf[addresses[j]].sub(amounts[j]); totalAmount = totalAmount.add(amounts[j]); Transfer(addresses[j], msg.sender, amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].add(totalAmount); return true; } function setDistributeAmount(uint256 _unitAmount) onlyOwner public { distributeAmount = _unitAmount; } /** * @dev Function to distribute tokens to the msg.sender automatically * If distributeAmount is 0, this function doesn't work */ function autoDistribute() payable public { require(distributeAmount > 0 && balanceOf[owner] >= distributeAmount && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); if(msg.value > 0) owner.transfer(msg.value); balanceOf[owner] = balanceOf[owner].sub(distributeAmount); balanceOf[msg.sender] = balanceOf[msg.sender].add(distributeAmount); Transfer(owner, msg.sender, distributeAmount); } /** * @dev fallback function */ function() payable public { autoDistribute(); } }
* @dev Function to check the amount of tokens that an owner allowed to a spender Added due to backwards compatibility with ERC20 @param _owner address The address which owns the funds @param _spender address The address which will spend the funds/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowance[_owner][_spender]; }
1,405,265
[ 1, 2083, 358, 866, 326, 3844, 434, 2430, 716, 392, 3410, 2935, 358, 279, 17571, 264, 1377, 25808, 6541, 358, 12727, 8926, 598, 4232, 39, 3462, 225, 389, 8443, 1758, 1021, 1758, 1492, 29065, 326, 284, 19156, 225, 389, 87, 1302, 264, 1758, 1021, 1758, 1492, 903, 17571, 326, 284, 19156, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1699, 1359, 12, 2867, 389, 8443, 16, 1758, 389, 87, 1302, 264, 13, 1071, 1476, 1135, 261, 11890, 5034, 4463, 13, 288, 203, 3639, 327, 1699, 1359, 63, 67, 8443, 6362, 67, 87, 1302, 264, 15533, 203, 565, 289, 203, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.7.6; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.4-solc-0.7/contracts/access/Ownable.sol"; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.4-solc-0.7/contracts/math/Math.sol"; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.4-solc-0.7/contracts/math/SafeMath.sol"; import "./FarmController.sol"; import "./TokenWrapper.sol"; import "./IRewardDistributionRecipientTokenOnly.sol"; /** * MIT License * =========== * * Copyright (c) 2020 Synthetix * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ contract LPFarm is TokenWrapper, IRewardDistributionRecipientTokenOnly { using SafeMath for uint256; using SafeERC20 for IERC20; FarmController public controller; IERC20 public override rewardToken; uint256 public constant DURATION = 7 days; uint256 public periodFinish; uint256 public rewardRate; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); modifier onlyController() { require(msg.sender == address(controller), "Caller is not controller"); _; } modifier onlyOwner() { require(msg.sender == Ownable(address(controller)).owner(), "Caller is not owner"); _; } /** * @dev Updates user rewards * @param account User to update */ modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } /** * @dev Init the farm * @param _stakeToken Token user needs to deposit * @param _controller Controller contract address */ function initialize(address _stakeToken, address _controller) external { require(address(stakeToken) == address(0), "already initialized"); stakeToken = IERC20(_stakeToken); controller = FarmController(_controller); rewardToken = controller.rewardToken(); periodFinish = 0; rewardRate = 0; } /** * @dev Check the last time when reward was considered active * @returns Last eligible time of rewards */ function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } /** * @dev Check how much rewards you can earn at this point of time * @returns Rewards per deposited token */ function rewardPerToken() public view returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalSupply()) ); } /** * @dev Check how much rewards the account has earned * @param account Address to check * @returns Rewards accumulated */ function earned(address account) public view returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } /** * @dev Deposit token * @param amount Amount to deposit */ function stake(uint256 amount) public override updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); super.stake(amount); emit Staked(msg.sender, amount); } /** * @dev Withdraw staked token * @param amount Amount to withdraw */ function withdraw(uint256 amount) public override updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); super.withdraw(amount); emit Withdrawn(msg.sender, amount); } /** * @dev Leave farm */ function exit() external { withdraw(balanceOf(msg.sender)); getReward(); } /** * @dev Claim earned rewards */ function getReward() public updateReward(msg.sender) { uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; rewardToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } /** * @dev Controller notifies when the new reward is available * @param reward Amount of reward token dedicated to this farm */ function notifyRewardAmount(uint256 reward) external override onlyController updateReward(address(0)) { rewardToken.safeTransferFrom(msg.sender, address(this), reward); if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } }
* @dev Check the last time when reward was considered active @returns Last eligible time of rewards/
function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); }
12,998,384
[ 1, 1564, 326, 1142, 813, 1347, 19890, 1703, 7399, 2695, 1135, 6825, 21351, 813, 434, 283, 6397, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 31323, 17631, 1060, 27873, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 2361, 18, 1154, 12, 2629, 18, 5508, 16, 3879, 11641, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/4/0xBe885e630567b97871395DDe4F937516Fba30E74/sources/UP.sol
for StableSwap and interest-bearing assets, or Deposit and underlying_coins
function burn(address swap2, uint[] calldata amts, uint maxBurn) virtual external returns (uint amtBurn) {
16,978,185
[ 1, 1884, 934, 429, 12521, 471, 16513, 17, 29400, 310, 7176, 16, 578, 4019, 538, 305, 471, 6808, 67, 71, 9896, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 18305, 12, 2867, 7720, 22, 16, 2254, 8526, 745, 892, 25123, 87, 16, 2254, 943, 38, 321, 13, 5024, 3903, 1135, 261, 11890, 25123, 38, 321, 13, 288, 6647, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.26; contract SafeMath { function safeAdd(uint256 a, uint256 b) public pure returns (uint256 c) { c = a + b; require(c >= a); } function safeSub(uint256 a, uint256 b) public pure returns (uint256 c) { require(b <= a); c = a - b; } function safeMul(uint256 a, uint256 b) public pure returns (uint256 c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint256 a, uint256 b) public pure returns (uint256 c) { require(b > 0); c = a / b; } } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } contract NV_Cardano is Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint256 public _totalSupply; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "ADAn"; name = "NV Cardano"; decimals = 18; _totalSupply = 1000000000000000000000000000; balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } function totalSupply() external constant returns (uint256) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) external constant returns (uint256 balance) { return balances[tokenOwner]; } function transfer(address to, uint256 tokens) external returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint256 tokens) external returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint256 tokens) external returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) external constant returns (uint256 remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint256 tokens, bytes data) external returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () external payable { revert(); } function transferAnyERC20Token(uint256 tokens) external onlyOwner returns (bool success) { return this.transfer(owner, tokens); } }
------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract NV_Cardano is Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint256 public _totalSupply; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); constructor() public { symbol = "ADAn"; name = "NV Cardano"; decimals = 18; _totalSupply = 1000000000000000000000000000; balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } function totalSupply() external constant returns (uint256) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) external constant returns (uint256 balance) { return balances[tokenOwner]; } function transfer(address to, uint256 tokens) external returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint256 tokens) external returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint256 tokens) external returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) external constant returns (uint256 remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint256 tokens, bytes data) external returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () external payable { revert(); } function transferAnyERC20Token(uint256 tokens) external onlyOwner returns (bool success) { return this.transfer(owner, tokens); } }
13,624,101
[ 1, 29461, 11417, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 423, 58, 67, 6415, 31922, 353, 14223, 11748, 16, 14060, 10477, 288, 203, 565, 533, 1071, 3273, 31, 203, 565, 533, 1071, 225, 508, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 2254, 5034, 1071, 389, 4963, 3088, 1283, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 324, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 2935, 31, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 2430, 1769, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 1147, 5541, 16, 1758, 8808, 17571, 264, 16, 2254, 5034, 2430, 1769, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 3273, 273, 315, 1880, 979, 14432, 203, 3639, 508, 273, 315, 11679, 14338, 31922, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2130, 12648, 12648, 2787, 11706, 31, 203, 3639, 324, 26488, 63, 8443, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 3410, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 3903, 5381, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 225, 300, 324, 26488, 63, 2867, 12, 20, 13, 15533, 203, 565, 289, 203, 203, 203, 565, 445, 11013, 951, 12, 2867, 1147, 5541, 13, 3903, 5381, 1135, 261, 11890, 5034, 11013, 13, 288, 203, 3639, 327, 324, 26488, 63, 2316, 5541, 15533, 203, 565, 2 ]
// File: contracts/VeloxTransferHelper.sol // SPDX-FileCopyrightText: © 2020 Velox <[email protected]> // SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.8.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library VeloxTransferHelper { function safeApprove(address token, address to, uint value) internal { require(token != address(0), 'VeloxTransferHelper: ZERO_ADDRESS'); require(to != address(0), 'VeloxTransferHelper: TO_ZERO_ADDRESS'); // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'VeloxTransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { require(token != address(0), 'VeloxTransferHelper: ZERO_ADDRESS'); require(to != address(0), 'VeloxTransferHelper: TO_ZERO_ADDRESS'); // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'VeloxTransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { require(token != address(0), 'VeloxTransferHelper: TOKEN_ZERO_ADDRESS'); require(from != address(0), 'VeloxTransferHelper: FROM_ZERO_ADDRESS'); require(to != address(0), 'VeloxTransferHelper: TO_ZERO_ADDRESS'); // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'VeloxTransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { require(to != address(0), 'VeloxTransferHelper: TO_ZERO_ADDRESS'); (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File: contracts/interfaces/IERC20.sol pragma solidity >=0.8.0; interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } // File: contracts/interfaces/IERC20NONStandard.sol pragma solidity >=0.8.0; /** * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ abstract contract IERC20NONStandard { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ uint256 public totalSupply; function balanceOf(address owner) virtual public view returns (uint256 balance); /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC20 specification /// will return Whether the transfer was successful or not function transfer(address to, uint256 value) virtual public; /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC20 specification /// will return Whether the transfer was successful or not function transferFrom(address from, address to, uint256 value) virtual public; function approve(address spender, uint256 value) virtual public returns (bool success); function allowance(address owner, address spender) virtual public view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/SwapExceptions.sol pragma solidity >=0.8.0; contract SwapExceptions { event SwapException(uint exception, uint info, uint detail); enum Exception { NO_ERROR, GENERIC_ERROR, UNAUTHORIZED, INTEGER_OVERFLOW, INTEGER_UNDERFLOW, DIVISION_BY_ZERO, BAD_INPUT, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_TRANSFER_FAILED, MARKET_NOT_SUPPORTED, SUPPLY_RATE_CALCULATION_FAILED, BORROW_RATE_CALCULATION_FAILED, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_OUT_FAILED, INSUFFICIENT_LIQUIDITY, INSUFFICIENT_BALANCE, INVALID_COLLATERAL_RATIO, MISSING_ASSET_PRICE, EQUITY_INSUFFICIENT_BALANCE, INVALID_CLOSE_AMOUNT_REQUESTED, ASSET_NOT_PRICED, INVALID_LIQUIDATION_DISCOUNT, INVALID_COMBINED_RISK_PARAMETERS, ZERO_ORACLE_ADDRESS, CONTRACT_PAUSED } /* * Note: Reason (but not Exception) is kept in alphabetical order * This is because Reason grows significantly faster, and * the order of Exception has some meaning, while the order of Reason * is arbitrary. */ enum Reason { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, BORROW_ACCOUNT_SHORTFALL_PRESENT, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_AMOUNT_LIQUIDITY_SHORTFALL, BORROW_AMOUNT_VALUE_CALCULATION_FAILED, BORROW_CONTRACT_PAUSED, BORROW_MARKET_NOT_SUPPORTED, BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, BORROW_ORIGINATION_FEE_CALCULATION_FAILED, BORROW_TRANSFER_OUT_FAILED, EQUITY_WITHDRAWAL_AMOUNT_VALIDATION, EQUITY_WITHDRAWAL_CALCULATE_EQUITY, EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK, EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED, LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED, LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED, LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH, LIQUIDATE_CONTRACT_PAUSED, LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_FETCH_ASSET_PRICE_FAILED, LIQUIDATE_TRANSFER_IN_FAILED, LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_CONTRACT_PAUSED, REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_ASSET_PRICE_CHECK_ORACLE, SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_ORACLE_OWNER_CHECK, SET_ORIGINATION_FEE_OWNER_CHECK, SET_PAUSED_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_RISK_PARAMETERS_OWNER_CHECK, SET_RISK_PARAMETERS_VALIDATION, SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED, SUPPLY_CONTRACT_PAUSED, SUPPLY_MARKET_NOT_SUPPORTED, SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED, SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, SUPPLY_TRANSFER_IN_FAILED, SUPPLY_TRANSFER_IN_NOT_POSSIBLE, SUPPORT_MARKET_FETCH_PRICE_FAILED, SUPPORT_MARKET_OWNER_CHECK, SUPPORT_MARKET_PRICE_CHECK, SUSPEND_MARKET_OWNER_CHECK, WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, WITHDRAW_ACCOUNT_SHORTFALL_PRESENT, WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED, WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL, WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED, WITHDRAW_CAPACITY_CALCULATION_FAILED, WITHDRAW_CONTRACT_PAUSED, WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, WITHDRAW_TRANSFER_OUT_FAILED, WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE } /** * @dev report a known exception */ function raiseException(Exception exception, Reason reason) internal returns (uint) { emit SwapException(uint(exception), uint(reason), 0); return uint(exception); } /** * @dev report an opaque error from an upgradeable collaborator contract */ function raiseGenericException(Reason reason, uint genericException) internal returns (uint) { emit SwapException(uint(Exception.GENERIC_ERROR), uint(reason), genericException); return uint(Exception.GENERIC_ERROR); } } // File: contracts/Swappable.sol pragma solidity 0.8.0; /** * @title Swappable Interface */ contract Swappable is SwapExceptions { /** * @dev Checks whether or not there is sufficient allowance for this contract to move amount from `from` and * whether or not `from` has a balance of at least `amount`. Does NOT do a transfer. */ function checkTransferIn(address asset, address from, uint amount) internal view returns (Exception) { IERC20 token = IERC20(asset); if (token.allowance(from, address(this)) < amount) { return Exception.TOKEN_INSUFFICIENT_ALLOWANCE; } if (token.balanceOf(from) < amount) { return Exception.TOKEN_INSUFFICIENT_BALANCE; } return Exception.NO_ERROR; } /** * @dev This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address asset, address from, uint amount) internal returns (Exception) { IERC20NONStandard token = IERC20NONStandard(asset); bool result; // Should we use Helper.safeTransferFrom? require(token.allowance(from, address(this)) >= amount, 'Not enough allowance from client'); token.transferFrom(from, address(this), amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Exception.TOKEN_TRANSFER_FAILED; } return Exception.NO_ERROR; } /** * @dev Checks balance of this contract in asset */ function getCash(address asset) internal view returns (uint) { IERC20 token = IERC20(asset); return token.balanceOf(address(this)); } /** * @dev Checks balance of `from` in `asset` */ function getBalanceOf(address asset, address from) internal view returns (uint) { IERC20 token = IERC20(asset); return token.balanceOf(from); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address asset, address to, uint amount) internal returns (Exception) { IERC20NONStandard token = IERC20NONStandard(asset); bool result; token.transfer(to, amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Exception.TOKEN_TRANSFER_OUT_FAILED; } return Exception.NO_ERROR; } } // File: contracts/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 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 payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts/Ownable.sol pragma solidity >=0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/interfaces/IVeloxSwapV3.sol pragma solidity >=0.8.0; interface IVeloxSwapV3 { function withdrawToken(address token, uint256 amount) external; function withdrawETH(uint256 amount) external; function sellExactTokensForTokens( string calldata exchange, uint256 strategyId, address seller, address tokenInAddress, address tokenOutAddress, uint256 tokenInAmount, uint256 minTokenOutAmount, uint16 feeFactor, bool takeFeeFromInput, uint256 deadline) external returns (uint256 amountOut); function sellExactTokensForTokens( string calldata exchange, uint256 strategyId, address seller, address tokenInAddress, address tokenOutAddress, uint256 tokenInAmount, uint256 minTokenOutAmount, uint16 feeFactor, bool takeFeeFromInput, uint256 deadline, uint estimatedGasFundingCost) external returns (uint256 amountOut); function sellTokensForExactTokens( string calldata exchange, uint256 strategyId, address seller, address tokenInAddress, address tokenOutAddress, uint256 maxTokenInAmount, uint256 tokenOutAmount, uint16 feeFactor, bool takeFeeFromInput, uint256 deadline) external returns (uint256 amountIn); function sellTokensForExactTokens( string calldata exchange, uint256 strategyId, address seller, address tokenInAddress, address tokenOutAddress, uint256 maxTokenInAmount, uint256 tokenOutAmount, uint16 feeFactor, bool takeFeeFromInput, uint256 deadline, uint estimatedGasFundingCost) external returns (uint256 amountIn); function fundGasCost(uint256 strategyId, address seller, bytes32 txHash, uint256 wethAmount) external; } // File: contracts/BackingStore.sol pragma solidity >=0.8.0; abstract contract BackingStore { address public MAIN_CONTRACT; address public UNISWAP_FACTORY_ADDRESS = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; address public UNISWAP_ROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public ADMIN_ADDRESS; } // File: contracts/lib/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/lib/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/lib/AccessControl.sol pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping (address => bool) members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override { require(hasRole(getRoleAdmin(role), _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override { require(hasRole(getRoleAdmin(role), _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File: contracts/AccessManager.sol pragma solidity 0.8.0; contract AccessManager is AccessControl{ bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); /** * @dev Throws if called by any account other than the admin. */ modifier hasAdminRole() { require(hasRole(ADMIN_ROLE, _msgSender()), "VELOXSWAP: NOT_ADMIN"); _; } } // File: contracts/VeloxSwapV3.sol pragma solidity 0.8.0; /** * @title VeloxSwap based on algorithmic conditional trading exeuctions */ abstract contract VeloxSwapV3 is BackingStore, Ownable, Swappable, IVeloxSwapV3, AccessManager { function setUpAdminRole(address _c) public onlyOwner returns (bool succeeded) { require(_c != owner(), "VELOXPROXY_ADMIN_OWNER"); _setupRole(ADMIN_ROLE, _c); return true; } function setRootRole() public onlyOwner returns (bool succeeded) { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); return true; } function grantAdminRole(address _c) public onlyOwner returns (bool succeeded) { require(_c != owner(), "VELOXPROXY_ADMIN_OWNER"); grantRole(ADMIN_ROLE, _c); return true; } function revokeAdminRole(address _c) public onlyOwner returns (bool succeeded) { require(_c != owner(), "VELOXPROXY_ADMIN_OWNER"); revokeRole(ADMIN_ROLE, _c); return true; } struct SwapInput { address seller; address tokenInAddress; address tokenOutAddress; uint256 tokenInAmount; uint256 tokenOutAmount; uint16 feeFactor; bool takeFeeFromInput; uint256 deadline; } address private gasFundingTokenAddress; uint constant FEE_SCALE = 10000; uint constant GAS_FUNDING_ESTIMATED_GAS = 26233; event ValueSwapped(uint256 indexed strategyId, address indexed seller, address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOut); event GasFunded(uint256 indexed strategyId, address indexed seller, bytes32 indexed txHash, uint256 gasCost); event GasFundingTokenChanged(address oldValue, address newValue); event ExchangeRegistered(string indexed exchange, address indexed routerAddress); function setGasFundingTokenAddress(address tokenAddress) external onlyOwner { require(tokenAddress != address(0), "VELOXSWAP: ZERO_GAS_FUNDING_TOKEN_ADDRESS"); address oldValue = gasFundingTokenAddress; gasFundingTokenAddress = tokenAddress; emit GasFundingTokenChanged(oldValue, gasFundingTokenAddress); } function getGasFundingTokenAddress() public view returns (address) { return gasFundingTokenAddress; } function setKnownExchange(string calldata exchangeName, address routerAddress) onlyOwner external virtual { require(routerAddress != address(0), "VELOXSWAP: INVALID_ROUTER_ZERO_ADDRESS"); _setKnownExchange(exchangeName, routerAddress); emit ExchangeRegistered(exchangeName, routerAddress); } function withdrawToken(address token, uint256 amount) onlyOwner override external { VeloxTransferHelper.safeTransfer(token, msg.sender, amount); } function withdrawETH(uint256 amount) onlyOwner override external { VeloxTransferHelper.safeTransferETH(msg.sender, amount); } function fundGasCost(uint256 strategyId, address seller, bytes32 txHash, uint256 wethAmount) hasAdminRole override external { require(txHash.length > 0, "VELOXSWAP: INVALID_TX_HASH"); _fundGasCost(strategyId, seller, txHash, wethAmount); } function _fundGasCost(uint256 strategyId, address seller, bytes32 txHash, uint256 wethAmount) private { VeloxTransferHelper.safeTransferFrom(gasFundingTokenAddress, seller, _msgSender(), wethAmount); emit GasFunded(strategyId, seller, txHash, wethAmount); } /** * @dev This function should ONLY be executed when algorithmic conditons are met * function sellExactTokensForTokens * @param exchange string name of a existing exchange in routersByName * @param strategyId uint256 - strategy ID * @param seller address * @param tokenInAddress address * @param tokenOutAddress address * @param tokenInAmount uint256 * @param minTokenOutAmount uint256 * @param feeFactor uint - 1/10000 fraction of the amount, i.e. feeFactor of 1 means 0.01% fee * @param takeFeeFromInput bool * @param deadline uint256 - UNIX timestamp * @param estimatedGasFundingCost uint - estimated gas for gas funding transaction */ function sellExactTokensForTokens( string calldata exchange, uint256 strategyId, address seller, address tokenInAddress, address tokenOutAddress, uint256 tokenInAmount, uint256 minTokenOutAmount, uint16 feeFactor, bool takeFeeFromInput, uint256 deadline, uint estimatedGasFundingCost ) override hasAdminRole public returns (uint256 amountOut) { uint256 initialGas = gasleft(); SwapInput memory input = SwapInput({ seller: seller, tokenInAddress: tokenInAddress, tokenOutAddress: tokenOutAddress, tokenInAmount: tokenInAmount, tokenOutAmount: minTokenOutAmount, feeFactor: feeFactor, takeFeeFromInput: takeFeeFromInput, deadline: deadline }); ( , amountOut) = swapTokens(exchange, strategyId, input, true); // Not sure if it should be 0 or just minus something if (isTakingOutputFeeInGasToken(input)) { estimatedGasFundingCost = 0; } uint256 gasCost = (initialGas - gasleft() + estimatedGasFundingCost) * tx.gasprice; bytes32 txHash; _fundGasCost(strategyId, seller, txHash, gasCost); } /** * @dev This function should ONLY be executed when algorithmic conditons are met * function sellExactTokensForTokens * @param exchange string name of a existing exchange in routersByName * @param strategyId uint256 - strategy ID * @param seller address * @param tokenInAddress address * @param tokenOutAddress address * @param tokenInAmount uint256 * @param minTokenOutAmount uint256 * @param feeFactor uint - 1/10000 fraction of the amount, i.e. feeFactor of 1 means 0.01% fee * @param takeFeeFromInput bool * @param deadline uint256 - UNIX timestamp */ function sellExactTokensForTokens( string calldata exchange, uint256 strategyId, address seller, address tokenInAddress, address tokenOutAddress, uint256 tokenInAmount, uint256 minTokenOutAmount, uint16 feeFactor, bool takeFeeFromInput, uint256 deadline ) override hasAdminRole public returns (uint256 amountOut) { amountOut = sellExactTokensForTokens(exchange, strategyId, seller, tokenInAddress, tokenOutAddress, tokenInAmount, minTokenOutAmount, feeFactor, takeFeeFromInput, deadline, GAS_FUNDING_ESTIMATED_GAS); } /** * @dev This function should ONLY be executed when algorithmic conditons are met * function sellTokensForExactTokens * @param exchange string name of a existing exchange in routersByName * @param strategyId uint256 - strategy ID * @param seller address * @param tokenInAddress address * @param tokenOutAddress address * @param maxTokenInAmount uint256 * @param tokenOutAmount uint256 * @param feeFactor uint - 1/10000 fraction of the amount, i.e. feeFactor of 1 means 0.01% fee * @param takeFeeFromInput bool * @param deadline uint256 - UNIX timestamp * @param estimatedGasFundingCost uint - estimated gas for gas funding transaction */ function sellTokensForExactTokens( string calldata exchange, uint256 strategyId, address seller, address tokenInAddress, address tokenOutAddress, uint256 maxTokenInAmount, uint256 tokenOutAmount, uint16 feeFactor, bool takeFeeFromInput, uint256 deadline, uint estimatedGasFundingCost) override hasAdminRole public returns (uint256 amountIn) { uint256 initialGas = gasleft(); SwapInput memory input = SwapInput({ seller: seller, tokenInAddress: tokenInAddress, tokenOutAddress: tokenOutAddress, tokenInAmount: maxTokenInAmount, tokenOutAmount: tokenOutAmount, feeFactor: feeFactor, takeFeeFromInput: takeFeeFromInput, deadline: deadline }); (amountIn, ) = swapTokens(exchange, strategyId, input, false); // Not sure if it should be 0 or just minus something if (isTakingOutputFeeInGasToken(input)) { estimatedGasFundingCost = 0; } uint256 gasCost = (initialGas - gasleft() + estimatedGasFundingCost) * tx.gasprice; bytes32 txHash; _fundGasCost(strategyId, seller, txHash, gasCost); } /** * @dev This function should ONLY be executed when algorithmic conditons are met * function sellTokensForExactTokens * @param exchange string name of a existing exchange in routersByName * @param strategyId uint256 - strategy ID * @param seller address * @param tokenInAddress address * @param tokenOutAddress address * @param maxTokenInAmount uint256 * @param tokenOutAmount uint256 * @param feeFactor uint - 1/10000 fraction of the amount, i.e. feeFactor of 1 means 0.01% fee * @param takeFeeFromInput bool * @param deadline uint256 - UNIX timestamp */ function sellTokensForExactTokens( string calldata exchange, uint256 strategyId, address seller, address tokenInAddress, address tokenOutAddress, uint256 maxTokenInAmount, uint256 tokenOutAmount, uint16 feeFactor, bool takeFeeFromInput, uint256 deadline) override hasAdminRole public returns (uint256 amountIn) { amountIn = sellTokensForExactTokens(exchange, strategyId, seller, tokenInAddress, tokenOutAddress, maxTokenInAmount, tokenOutAmount, feeFactor, takeFeeFromInput, deadline, GAS_FUNDING_ESTIMATED_GAS); } function swapTokens(string calldata exchange, uint256 strategyId, SwapInput memory input, bool exactIn) private returns (uint256 amountIn, uint256 amountOut) { uint256 amountInForSwap; uint256 amountOutForSwap; address swapTargetAddress; (amountInForSwap, amountOutForSwap, swapTargetAddress) = prepareSwap(exchange, input); uint actualAmountOut; // Execute the swap (amountIn, actualAmountOut) = doSwap(exchange, input.tokenInAddress, input.tokenOutAddress, amountInForSwap, amountOutForSwap, swapTargetAddress, input.deadline, exactIn); // Take the fee from the output if not taken from the input if (!input.takeFeeFromInput) { amountOut = takeOutputFee(actualAmountOut, input.feeFactor, input.tokenOutAddress, input.seller); } emit ValueSwapped(strategyId, input.seller, input.tokenInAddress, input.tokenOutAddress, input.tokenInAmount, amountOut); } function prepareSwap(string calldata exchange, SwapInput memory input) private returns (uint256 amountInForSwap, uint256 amountOurForSwap, address targetAddress) { // Sanity checks validateInput(input.seller, input.tokenInAddress, input.tokenOutAddress, input.tokenInAmount, input.tokenOutAmount, input.feeFactor, input.deadline); // Be 100% sure there's available allowance in this token contract Exception exception = doTransferIn(input.tokenInAddress, input.seller, input.tokenInAmount); require(exception == Exception.NO_ERROR, 'VELOXSWAP: ALLOWANCE_TOO_LOW'); // Checking In/Out reserves checkLiquidity(exchange, input.tokenInAddress, input.tokenOutAddress, input.tokenOutAmount); // Fee (amountInForSwap, amountOurForSwap, targetAddress) = adjustInputBasedOnFee(input.takeFeeFromInput, input.feeFactor, input.tokenInAmount, input.tokenOutAmount, input.seller); } function validateInput(address seller, address tokenInAddress, address tokenOutAddress, uint256 tokenInAmount, uint256 tokenOutAmount, uint16 feeFactor, uint256 deadline) private view { require(deadline >= block.timestamp, 'VELOXSWAP: EXPIRED'); require(feeFactor <= 30, 'VELOXSWAP: FEE_OVER_03_PERCENT'); require(gasFundingTokenAddress != address(0), 'VELOXSWAP: GAS_FUNDING_ADDRESS_NOT_FOUND'); require (seller != address(0) && tokenInAddress != address(0) && tokenOutAddress != address(0) && tokenInAmount > 0 && tokenOutAmount > 0, 'VELOXSWAP: ZERO_DETECTED'); } /** * @dev Adjust input values based on the fee strategy * @param takeFeeFromInput bool * @param feeFactor uint - 1/10000 fraction of the amount, i.e. feeFactor of 1 means 0.01% fee * @param amountIn uint256 * @param amountOut uint256 * @param sellerAddress address */ function adjustInputBasedOnFee(bool takeFeeFromInput, uint16 feeFactor, uint256 amountIn, uint256 amountOut, address sellerAddress) private view returns (uint256 amountInForSwap, uint256 amountOurForSwap, address targetAddress) { // Take fee from input if (takeFeeFromInput) { // Use less tokens for swap so we can keep the difference and make one less transfer amountInForSwap = deductFee(amountIn, feeFactor); amountOurForSwap = deductFee(amountOut, feeFactor); // If we took fee from the input, transfer the result directly to client, // otherwise, transfer to contract address so we can take fee from output targetAddress = sellerAddress; } else { amountInForSwap = amountIn; amountOurForSwap = amountOut; targetAddress = address(this); } } function doSwap(string calldata exchange, address tokenInAddress, address tokenOutAddress, uint256 tokenInAmount, uint256 minTokenOutAmount, address targetAddress, uint256 deadline, bool exactIn) private returns (uint amountIn, uint amountOut) { // Safely Approve UNISWAP V2 Router for token amount safeApproveExchangeRouter(exchange, tokenInAddress, tokenInAmount); // Path address[] memory path = new address[](2); path[0] = tokenInAddress; path[1] = tokenOutAddress; uint[] memory amounts; if (exactIn) { amounts = swapExactTokensForTokens( exchange, tokenInAmount, minTokenOutAmount, path, targetAddress, deadline ); } else { amounts = swapTokensForExactTokens( exchange, tokenInAmount, minTokenOutAmount, path, targetAddress, deadline ); } amountIn = amounts[0]; amountOut = amounts[amounts.length - 1]; } function checkLiquidity(string calldata exchange, address tokenInAddress, address tokenOutAddress, uint256 minTokenOutAmount) private view { (uint reserveIn, uint reserveOut) = getLiquidityForPair(exchange, tokenInAddress, tokenOutAddress); require(reserveIn > 0 && reserveOut > 0, 'VELOXSWAP: ZERO_RESERVE_DETECTED'); require(reserveOut > minTokenOutAmount, 'VELOXSWAP: NOT_ENOUGH_LIQUIDITY'); } function takeOutputFee(uint256 amountOut, uint16 feeFactor, address tokenOutAddress, address from) private returns (uint256 transferredAmount) { // Transfer to client address the value of amountOut - fee and keep difference in contract address transferredAmount = deductFee(amountOut, feeFactor); Exception exception = doTransferOut(tokenOutAddress, from, transferredAmount); require (exception == Exception.NO_ERROR, 'VELOXSWAP: ERROR_GETTING_OUTPUT_FEE'); } function deductFee(uint256 amount, uint16 feeFactor) private pure returns (uint256 deductedAmount) { deductedAmount = (amount * (FEE_SCALE - feeFactor)) / FEE_SCALE; } function isTakingOutputFeeInGasToken(SwapInput memory input) private view returns (bool) { return !input.takeFeeFromInput && input.tokenOutAddress == gasFundingTokenAddress; } /** ABSTRACT METHODS */ function _setKnownExchange(string calldata exchangeName, address routerAddress) internal virtual; function safeApproveExchangeRouter(string calldata exchange, address tokenInAddress, uint256 tokenInAmount) internal virtual; function getLiquidityForPair(string calldata exchange, address tokenInAddress, address tokenOutAddress) view internal virtual returns (uint reserveIn, uint reserveOut); function swapExactTokensForTokens( string calldata exchange, uint amountIn, uint amountOutMin, address[] memory path, address to, uint deadline ) internal virtual returns (uint[] memory amounts); function swapTokensForExactTokens( string calldata exchange, uint amountIn, uint amountOutMin, address[] memory path, address to, uint deadline ) internal virtual returns (uint[] memory amounts); } // File: contracts/interfaces/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, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // File: contracts/interfaces/IUniswapV2Router02.sol pragma solidity >=0.8.0; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // File: contracts/interfaces/IUniswapV2Pair.sol pragma solidity >=0.8.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File: contracts/interfaces/IUniswapV2Factory.sol pragma solidity >=0.8.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // File: contracts/EthereumVeloxSwapV3.sol pragma solidity 0.8.0; /** * @title VeloxSwap based on algorithmic conditional trading exeuctions */ contract EthereumVeloxSwapV3 is VeloxSwapV3 { mapping (string=>IUniswapV2Router02) routersByName; function _setKnownExchange(string calldata exchangeName, address uniswapLikeRouterAddress) onlyOwner override internal { require(uniswapLikeRouterAddress != address(0), "VELOXSWAP: INVALID_ROUTER_ADDRESS"); // Check how to validate this IUniswapV2Router02 newRouter = IUniswapV2Router02(uniswapLikeRouterAddress); require(address(newRouter.factory()) != address(0), "VELOXSWAP: INVALID_ROUTER"); routersByName[exchangeName] = newRouter; } function safeApproveExchangeRouter(string calldata exchange, address tokenInAddress, uint256 tokenInAmount) override internal { IUniswapV2Router02 router = getRouter(exchange); VeloxTransferHelper.safeApprove(tokenInAddress, address(router), tokenInAmount); } function getLiquidityForPair(string calldata exchange, address tokenInAddress, address tokenOutAddress) view internal override returns (uint reserveIn, uint reserveOut) { IUniswapV2Router02 router = getRouter(exchange); IUniswapV2Factory factory = IUniswapV2Factory(router.factory()); IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(tokenInAddress, tokenOutAddress)); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); if (pair.token0() == tokenOutAddress) { reserveIn = reserve1; reserveOut = reserve0; } else { reserveIn = reserve0; reserveOut = reserve1; } } function getRouter(string memory exchange) private view returns (IUniswapV2Router02 router) { router = routersByName[exchange]; require(address(router) != address(0), "VELOXSWAP: UNKNOWN_EXCHANGE"); } function swapExactTokensForTokens( string calldata exchange, uint amountIn, uint amountOutMin, address[] memory path, address to, uint deadline ) override internal virtual returns (uint[] memory amounts) { IUniswapV2Router02 router = getRouter(exchange); amounts = router.swapExactTokensForTokens( amountIn, amountOutMin, path, to, deadline ); } function swapTokensForExactTokens( string calldata exchange, uint amountIn, uint amountOutMin, address[] memory path, address to, uint deadline ) override internal virtual returns (uint[] memory amounts) { IUniswapV2Router02 router = getRouter(exchange); amounts = router.swapTokensForExactTokens( amountIn, amountOutMin, path, to, deadline ); } }
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`/
abstract contract IERC20NONStandard { function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. uint256 public totalSupply; function balanceOf(address owner) virtual public view returns (uint256 balance); function transfer(address to, uint256 value) virtual public; function transferFrom(address from, address to, uint256 value) virtual public; function approve(address spender, uint256 value) virtual public returns (bool success); function allowance(address owner, address spender) virtual public view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); }
10,282,643
[ 1, 1444, 434, 4232, 39, 3462, 598, 1158, 327, 924, 364, 1375, 13866, 68, 471, 1375, 13866, 1265, 68, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 467, 654, 39, 3462, 3993, 8336, 288, 203, 565, 445, 2078, 3088, 1283, 1435, 5381, 1135, 261, 11890, 5034, 14467, 1769, 203, 565, 353, 8089, 598, 30, 203, 565, 2254, 5034, 1071, 2078, 3088, 1283, 31, 203, 565, 1220, 6635, 3414, 279, 7060, 445, 364, 326, 2078, 3088, 1283, 18, 203, 565, 1220, 353, 10456, 358, 326, 1026, 6835, 3241, 1071, 7060, 4186, 854, 486, 203, 565, 4551, 14603, 5918, 487, 392, 4471, 434, 326, 3607, 8770, 203, 565, 445, 635, 326, 5274, 18, 203, 203, 565, 2254, 5034, 1071, 2078, 3088, 1283, 31, 203, 565, 445, 11013, 951, 12, 2867, 3410, 13, 5024, 1071, 1476, 1135, 261, 11890, 5034, 11013, 1769, 203, 203, 565, 445, 7412, 12, 2867, 358, 16, 2254, 5034, 460, 13, 5024, 1071, 31, 203, 203, 565, 445, 7412, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 460, 13, 5024, 1071, 31, 203, 203, 203, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 460, 13, 5024, 1071, 1135, 261, 6430, 2216, 1769, 203, 565, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 5024, 1071, 1476, 1135, 261, 11890, 5034, 4463, 1769, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 5034, 460, 1769, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* AMP Copyright 2017-2020 AMP Development 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. This code does not constitute an offer or a means to sell or a solicitation of an offer to buy a security in any jurisdiction in which it is unlawful to make such an offer or solicitation. This technology is not built to enable securitization, but accounting transparency in asset-backed and non-asset-backed transactions. All notices regarding the AMP market include notices of restrictions for the participation by US-citizens and residents of the US, South Korea, United Kingdom and the EU. */ pragma experimental ABIEncoderV2; pragma solidity 0.6.6; // Uniswap import '@uniswap/v2-periphery/contracts/UniswapV2Router02.sol'; interface OrFeedInterface { function getExchangeRate ( string calldata fromSymbol, string calldata toSymbol, string calldata venue, uint256 amount ) external view returns ( uint256 ); function getTokenDecimalCount ( address tokenAddress ) external view returns ( uint256 ); function getTokenAddress ( string calldata symbol ) external view returns ( address ); function getSynthBytes32 ( string calldata symbol ) external view returns ( bytes32 ); function getForexAddress ( string calldata symbol ) external view returns ( address ); function requestAsyncEvent(string calldata eventName, string calldata source) external view returns(string memory); function arb(address fundsReturnToAddress, address liquidityProviderContractAddress, string[] calldata tokens, uint256 amount, string[] calldata exchanges) external payable returns (bool); } contract Amp { using SafeMath for uint256; // orfeed interface OrFeedInterface orfeed; // dai tokenAddress IERC20 daiToken; // the uniswap v2 router UniswapV2Router02 uniswap; // the owner of the contract address owner; // the address of the uniswap v2 router to use address payable uniswapAddress; // Represents a single asset struct Asset { address tokenAddress; string title; string description; string entityName; uint256 proposedMarketCapUSD; string fileHash1; string fileHash2; string photo1URL; string photo2URL; string photo3URL; uint256 assetSaleRewards; uint256 assetRegularRewards; } // Represents a single prediction struct Prediction { address userAddress; bool predictFor; uint256 amountStableCoinStaked; } // Represents a token issuer i.e. the person who adds the asset to the assurance market struct TokenIssuer { address issuerAddress; uint256 dateIssued; // date the token was added to the market } // a mapping of assets in the contract mapping (address => Asset) assets; // a mapping of assets in the contract mapping (address => TokenIssuer) tokenIssuers; // a mapping of predictions for each asset mapping (address => Prediction[]) predictions; // a mapping of each tokens resolution date mapping (address => uint256) assetResolutionDates; constructor(address _daiTokenAddress, address payable _uniswapAddress) public { // set the owner of the contract owner = msg.sender; // init the dai token address daiToken = IERC20(_daiTokenAddress); //init the uniswap router uniswapAddress = _uniswapAddress; uniswap = UniswapV2Router02(_uniswapAddress); } // check that the user is the owner of the contract modifier onlyOwner() { if (msg.sender != owner) { revert(); } _; } // contract events event AssetAdded(address _tokenAddress, uint256 _resolutionDate); event AssetInactivated(address _tokenAddress, string _reasonGivenByAdminOrCreator); /// @notice allow the owner to set the address of the orfeed contract /// @param _orfeedAddress the new address of the orfeed contract /// @return true function setOrfeedAddress(address _orfeedAddress) onlyOwner external returns(bool) { orfeed = OrFeedInterface(_orfeedAddress); return true; } function getCreditScore(address entityAddress) public view returns (uint256 score){ // placeholder for now (score) = 200; } function getPrice(string memory fromTokenSymbol, uint256 amount, string memory venue) public view returns (uint256 price){ (price) = orfeed.getExchangeRate(fromTokenSymbol, "USD", venue, amount); } function getSwapPrice(string memory fromTokenSymbol, string memory toTokenSymbol, uint256 amount, string memory venue) public view returns (uint256 price) { (price) = orfeed.getExchangeRate(fromTokenSymbol, toTokenSymbol, venue, amount); } function getProposedYield(address tokenAddress) public view returns (uint256 percentage){ // placeholder for now (percentage) = 200; } function getHistoricYield(address tokenAddress, uint256 numOfYears) public view returns (uint256 percentage){ // placeholder for now (percentage) = 200; } function getProposedMarketCap(address tokenAddress) external view returns (uint256 marketCap){ // placeholder for now (marketCap) = assets[tokenAddress].proposedMarketCapUSD; } function getAssetPredictionScoreAndSize(address tokenAddress) external view returns (uint256 score, uint256 totalPredictionMarketSize){ uint256 assetScore = getCreditScore(tokenAddress); (score, totalPredictionMarketSize) = (assetScore, 200); } function getPredictionMarketAssetExpirationDate(address tokenAddress) external view returns (uint256 timestamp) { (timestamp) = assetResolutionDates[tokenAddress]; } function getPredictionBalance(address predictorAddress, address tokenAddress) public view returns (uint256 currentBalance, uint256 side){ // placeholder for now (currentBalance, side) = (200, 200); } function isAssetOnAMP(address tokenAddress) public view returns (bool isOn){ address assetAddress = assets[tokenAddress].tokenAddress; if (assetAddress != address(0)){ (isOn) = true; } else{ (isOn) = false; } } function isPredictionMarketResolved(address tokenAddress) public view returns (bool isOn){ uint256 resolutionDate = assetResolutionDates[tokenAddress]; if (now > resolutionDate){ (isOn) = true; } else{ (isOn) = false; } } function rateEntityForCreditScore(address entityAddress, uint256 proposedScore) public returns(bool){ // placeholder for now return true; } function swapAsset( address fromAsset, address toAsset, string calldata fromTokenSymbol, string calldata toTokenSymbol, uint256 amountInput, uint256 minimumOutput) external returns(uint256 outputAmount){ // check if the contract is allowed to spend the the swap amount require(IERC20(fromAsset).allowance(msg.sender, address(this)) >= amountInput, 'Please approve this contract to spend the swap amount'); // check if the contract is able to transfer the swap amount from the user to itself if the allowance is given require(IERC20(fromAsset).transferFrom(msg.sender, address(this), amountInput), 'Failed to transfer the from asset to the contract'); // check if the contract is able to approve the asset for swapping in uniswap require(IERC20(fromAsset).approve(address(uniswapAddress), amountInput), 'Token approve failed for the token swap via uniswap.'); uint256 finalOutputAmount = 0; // get the asset swap price via orfeed uint256 swapPrice = getSwapPrice(fromTokenSymbol, toTokenSymbol, amountInput, "UNISWAPBYSYMBOLV2"); if (swapPrice < minimumOutput) { revert("The final output amount for this swap will be less than the minimum amount set!"); } else { // start the token to token swap address[] memory path = new address[](2); path[0] = fromAsset; path[1] = toAsset; uint[] memory swapAmounts = uniswap.swapExactTokensForTokens(amountInput, minimumOutput, path, msg.sender, block.timestamp); for (uint i= 0; i < swapAmounts.length; i++) { // skip the first index amount because it will be the input amount if (i > 0) { // add up the rest of the amounts in the array and return them finalOutputAmount += swapAmounts[i]; } } } (outputAmount) = finalOutputAmount; } function predictForOrAgainst(address tokenAddress, bool predictFor, uint256 amountStableCoinStaked) payable external returns(bool) { bool predicitionSuccessful = false; // first of all check if the contract is allow spend the dai amount set by the sender if(IERC20(daiToken).allowance(msg.sender, address(this)) >= amountStableCoinStaked) { // check if the contract is able to transfer the dai amount from the user to itself if the allowance is given require(IERC20(daiToken).transferFrom(msg.sender, address(this), amountStableCoinStaked), 'Failed to transfer the dai from your address to the contract for prediction'); // if transfer is sucessful, then update the predicitions for the token for this user predictions[tokenAddress].push(Prediction(msg.sender, predictFor, amountStableCoinStaked)); // mark the prediction as successful predicitionSuccessful = true; } else{ require(msg.value > 0, "Please send some ETH that'll be swapped for dai and sused for the prediction"); uint256 swapPrice = orfeed.getExchangeRate("ETH", "DAI", "UNISWAPBYSYMBOLV2", amountStableCoinStaked); if (swapPrice < amountStableCoinStaked) { revert("The final output amount for the ETH/DAI swap will be less than the amount of stable coins to be staked!"); } else { // start the eth to token swap uint256 finalOutputAmount = 0; address[] memory path = new address[](2); path[0] = uniswap.WETH(); path[1] = address(daiToken); // sent uniswap the eth uniswapAddress.transfer(msg.value); // do the swap via uniswap v2 and get the array out the outputs uint[] memory swapAmounts = uniswap.swapETHForExactTokens(amountStableCoinStaked, path, address(this), block.timestamp); for (uint i = 0; i < swapAmounts.length; i++) { // skip the first index amount because it will be the input amount if (i > 0) { // add up the rest of the amounts in the array and return them finalOutputAmount += swapAmounts[i]; } } // update the users predicitions predictions[tokenAddress].push(Prediction(msg.sender, predictFor, amountStableCoinStaked)); // mark the prediction as successful predicitionSuccessful = true; } } return predicitionSuccessful; } function resolvePredictionMarketAsset(address tokenAddress) public returns(bool resolved) { uint256 resolutionDate = assetResolutionDates[tokenAddress]; if (now > resolutionDate){ (resolved) = true; } else{ (resolved) = false; } } function addAssetToMarket(address tokenAddress, string memory title, string memory description, string memory entityName, uint256 proposedMarketCapUSD, string memory fileHash1, string memory fileHash2, string memory photo1URL, string memory photo2URL, string memory photo3URL ) public { // add the asset assets[tokenAddress] = Asset(tokenAddress, title, description, entityName, proposedMarketCapUSD, fileHash1, fileHash2, photo1URL, photo2URL, photo3URL, 0, 0); // set the token issuer tokenIssuers[tokenAddress] = TokenIssuer(msg.sender, now); // calculate and set its resolution date uint256 resolutionDate = now + 365 days; assetResolutionDates[tokenAddress] = resolutionDate; // then emit the appropriate event emit AssetAdded(tokenAddress, resolutionDate); } function inactivateAsset(address tokenAddress, string memory reasonGivenByAdminOrCreator ) public { // remove the asset from the assets mapping delete assets[tokenAddress]; // remove the issuer of the token delete tokenIssuers[tokenAddress]; // delete its resolution date delete assetResolutionDates[tokenAddress]; // then emit an event explaining why the asset was inactivated emit AssetInactivated(tokenAddress, reasonGivenByAdminOrCreator); } function claimPredictionRewards(address tokenAddress) public returns(uint256 amountReturned) { // placeholder for now (amountReturned) = 200; } function claimAssetRewards(address tokenAddress) public returns(uint256 amountReturned) { // placeholder for now (amountReturned) = 200; } function claimAssetSaleRewards(address tokenAddress) public returns(uint256 amountReturned){ // placeholder for now (amountReturned) = 200; } function contributeAssetRegularRewards(address tokenAddress, uint256 amountUSD) public returns(bool){ bool contributionSuccessful = false; // make sure the asset is listed on amp if(isAssetOnAMP(tokenAddress)) { // check if the contract is allowed to spend require(IERC20(daiToken).allowance(msg.sender, address(this)) >= amountUSD, 'Please approve this contract to spend the contribution dai amount'); // check if the contract is able to transfer the dai amount from the user to itself if the allowance is given require(IERC20(daiToken).transferFrom(msg.sender, address(this), amountUSD), 'Failed to transfer the dai from your address to the contract'); // if the transfer is successful, then updaate the regular rewards balance for the asset/token assets[tokenAddress].assetRegularRewards += amountUSD; // then mark the contribution as successful contributionSuccessful = true; } return contributionSuccessful; } function contributeAssetSaleRewards(address tokenAddress, uint256 amountUSD) public returns(bool){ bool contributionSuccessful = false; // make sure the asset is listed on amp if(isAssetOnAMP(tokenAddress)) { // check if the contract is allowed to spend the dai require(IERC20(daiToken).allowance(msg.sender, address(this)) >= amountUSD, 'Please approve this contract to spend the contribution dai amount'); // check if the contract is able to transfer the dai amount from the user to itself if the allowance is given require(IERC20(daiToken).transferFrom(msg.sender, address(this), amountUSD), 'Failed to transfer the dai from your address to the contract'); // if the transfer is successful, then updaate the regular rewards balance for the asset/token assets[tokenAddress].assetSaleRewards += amountUSD; // then mark the contribution as successful contributionSuccessful = true; } return contributionSuccessful; } }
placeholder for now
function getPredictionBalance(address predictorAddress, address tokenAddress) public view returns (uint256 currentBalance, uint256 side){ (currentBalance, side) = (200, 200); }
12,562,678
[ 1, 12988, 364, 2037, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1689, 1118, 2228, 13937, 12, 2867, 7810, 280, 1887, 16, 1758, 1147, 1887, 13, 1071, 1476, 1135, 261, 11890, 5034, 783, 13937, 16, 2254, 5034, 4889, 15329, 203, 3639, 261, 2972, 13937, 16, 4889, 13, 273, 261, 6976, 16, 4044, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0xe2fd8eb78dD4802E58812Af5b3eF62A420bA596d/sources/contracts/Martians.sol
* @dev Throws if called by any account other than the owner./
modifier onlyOwner() { require(owner() == _msgSender(), "ER0"); _; }
4,665,382
[ 1, 21845, 309, 2566, 635, 1281, 2236, 1308, 2353, 326, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 8443, 1435, 422, 389, 3576, 12021, 9334, 315, 654, 20, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0xcc992b0bb9789e4e323bef8b7241ffe85487c2a6 //Contract name: DCAssetBackend //Balance: 0 Ether //Verification Date: 9/15/2016 //Transacion Count: 65 // CODE STARTS HERE contract Assertive { function assert(bool assertion) { if (!assertion) throw; } } contract TokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData); } contract Owned is Assertive { address internal owner; event SetOwner(address indexed previousOwner, address indexed newOwner); function Owned () { owner = msg.sender; } modifier onlyOwner { assert(msg.sender == owner); _ } function setOwner(address newOwner) onlyOwner { SetOwner(owner, newOwner); owner = newOwner; } function getOwner() returns (address out) { return owner; } } contract StateTransferrable is Owned { bool internal locked; event Locked(address indexed from); event PropertySet(address indexed from); modifier onlyIfUnlocked { assert(!locked); _ } modifier setter { _ PropertySet(msg.sender); } modifier onlyOwnerUnlocked { assert(!locked && msg.sender == owner); _ } function lock() onlyOwner onlyIfUnlocked { locked = true; Locked(msg.sender); } function isLocked() returns (bool status) { return locked; } } contract TrustEvents { event AuthInit(address indexed from); event AuthComplete(address indexed from, address indexed with); event AuthPending(address indexed from); event Unauthorized(address indexed from); event InitCancel(address indexed from); event NothingToCancel(address indexed from); event SetMasterKey(address indexed from); event AuthCancel(address indexed from, address indexed with); event NameRegistered(address indexed from, bytes32 indexed name); } contract Trust is StateTransferrable, TrustEvents { mapping (address => bool) public masterKeys; mapping (address => bytes32) public nameRegistry; address[] public masterKeyIndex; mapping (address => bool) public masterKeyActive; mapping (address => bool) public trustedClients; mapping (bytes32 => address) public functionCalls; mapping (address => bytes32) public functionCalling; function activateMasterKey(address addr) internal { if (!masterKeyActive[addr]) { masterKeyActive[addr] = true; masterKeyIndex.push(addr); } } function setTrustedClient(address addr) onlyOwnerUnlocked setter { trustedClients[addr] = true; } function untrustClient(address addr) multisig(sha3(msg.data)) { trustedClients[addr] = false; } function trustClient(address addr) multisig(sha3(msg.data)) { trustedClients[addr] = true; } function setMasterKey(address addr) onlyOwnerUnlocked { assert(!masterKeys[addr]); activateMasterKey(addr); masterKeys[addr] = true; SetMasterKey(msg.sender); } modifier onlyMasterKey { assert(masterKeys[msg.sender]); _ } function extractMasterKeyIndexLength() returns (uint256 length) { return masterKeyIndex.length; } function resetAction(bytes32 hash) internal { address addr = functionCalls[hash]; functionCalls[hash] = 0x0; functionCalling[addr] = bytes32(0); } function authCancel(address from) external returns (uint8 status) { if (!masterKeys[from] || !trustedClients[msg.sender]) { Unauthorized(from); return 0; } bytes32 call = functionCalling[from]; if (call == bytes32(0)) { NothingToCancel(from); return 1; } else { AuthCancel(from, from); functionCalling[from] = bytes32(0); functionCalls[call] = 0x0; return 2; } } function cancel() returns (uint8 code) { if (!masterKeys[msg.sender]) { Unauthorized(msg.sender); return 0; } bytes32 call = functionCalling[msg.sender]; if (call == bytes32(0)) { NothingToCancel(msg.sender); return 1; } else { AuthCancel(msg.sender, msg.sender); bytes32 hash = functionCalling[msg.sender]; functionCalling[msg.sender] = 0x0; functionCalls[hash] = 0; return 2; } } function authCall(address from, bytes32 hash) external returns (uint8 code) { if (!masterKeys[from] && !trustedClients[msg.sender]) { Unauthorized(from); return 0; } if (functionCalling[from] == 0) { if (functionCalls[hash] == 0x0) { functionCalls[hash] = from; functionCalling[from] = hash; AuthInit(from); return 1; } else { AuthComplete(functionCalls[hash], from); resetAction(hash); return 2; } } else { AuthPending(from); return 3; } } modifier multisig (bytes32 hash) { if (!masterKeys[msg.sender]) { Unauthorized(msg.sender); } else if (functionCalling[msg.sender] == 0) { if (functionCalls[hash] == 0x0) { functionCalls[hash] = msg.sender; functionCalling[msg.sender] = hash; AuthInit(msg.sender); } else { AuthComplete(functionCalls[hash], msg.sender); resetAction(hash); _ } } else { AuthPending(msg.sender); } } function voteOutMasterKey(address addr) multisig(sha3(msg.data)) { assert(masterKeys[addr]); masterKeys[addr] = false; } function voteInMasterKey(address addr) multisig(sha3(msg.data)) { assert(!masterKeys[addr]); activateMasterKey(addr); masterKeys[addr] = true; } function identify(bytes32 name) onlyMasterKey { nameRegistry[msg.sender] = name; NameRegistered(msg.sender, name); } function nameFor(address addr) returns (bytes32 name) { return nameRegistry[addr]; } } contract TrustClient is StateTransferrable, TrustEvents { address public trustAddress; function setTrust(address addr) setter onlyOwnerUnlocked { trustAddress = addr; } function nameFor(address addr) constant returns (bytes32 name) { return Trust(trustAddress).nameFor(addr); } function cancel() returns (uint8 status) { assert(trustAddress != address(0x0)); uint8 code = Trust(trustAddress).authCancel(msg.sender); if (code == 0) Unauthorized(msg.sender); else if (code == 1) NothingToCancel(msg.sender); else if (code == 2) AuthCancel(msg.sender, msg.sender); return code; } modifier multisig (bytes32 hash) { assert(trustAddress != address(0x0)); address current = Trust(trustAddress).functionCalls(hash); uint8 code = Trust(trustAddress).authCall(msg.sender, hash); if (code == 0) Unauthorized(msg.sender); else if (code == 1) AuthInit(msg.sender); else if (code == 2) { AuthComplete(current, msg.sender); _ } else if (code == 3) { AuthPending(msg.sender); } } } contract Relay { function relayReceiveApproval(address _caller, address _spender, uint256 _amount, bytes _extraData) returns (bool success); } contract TokenBase is Owned { bytes32 public standard = 'Token 0.1'; bytes32 public name; bytes32 public symbol; uint256 public totalSupply; bool public allowTransactions; event Approval(address indexed from, address indexed spender, uint256 amount); mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); function transfer(address _to, uint256 _value) returns (bool success); function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function () { throw; } } contract Precision { uint8 public decimals; } contract Token is TokenBase, Precision {} contract Util { function pow10(uint256 a, uint8 b) internal returns (uint256 result) { for (uint8 i = 0; i < b; i++) { a *= 10; } return a; } function div10(uint256 a, uint8 b) internal returns (uint256 result) { for (uint8 i = 0; i < b; i++) { a /= 10; } return a; } function max(uint256 a, uint256 b) internal returns (uint256 res) { if (a >= b) return a; return b; } } /** * @title DVIP Contract. DCAsset Membership Token contract. * * @author Ray Pulver, [email protected] */ contract DVIP is Token, StateTransferrable, TrustClient, Util { uint256 public totalSupply; mapping (address => bool) public frozenAccount; mapping (address => address[]) public allowanceIndex; mapping (address => mapping (address => bool)) public allowanceActive; address[] public accountIndex; mapping (address => bool) public accountActive; address public oversightAddress; uint256 public expiry; uint256 public treasuryBalance; bool public isActive; mapping (address => uint256) public exportFee; address[] public exportFeeIndex; mapping (address => bool) exportFeeActive; mapping (address => uint256) public importFee; address[] public importFeeIndex; mapping (address => bool) importFeeActive; event FrozenFunds(address target, bool frozen); event PrecisionSet(address indexed from, uint8 precision); event TransactionsShutDown(address indexed from); event FeeSetup(address indexed from, address indexed target, uint256 amount); /** * Constructor. * */ function DVIP() { isActive = true; treasuryBalance = 0; totalSupply = 0; name = "DVIP"; symbol = "DVIP"; decimals = 6; allowTransactions = true; expiry = 1514764800; //1 jan 2018 } /* --------------- modifiers --------------*/ /** * Makes sure a method is only called by an overseer. */ modifier onlyOverseer { assert(msg.sender == oversightAddress); _ } /* --------------- setter methods, only for the unlocked state --------------*/ /** * Sets the oversight address (not the contract). * * @param addr The oversight contract address. */ function setOversight(address addr) onlyOwnerUnlocked setter { oversightAddress = addr; } /** * Sets the total supply * * @param total Total supply of the asset. */ function setTotalSupply(uint256 total) onlyOwnerUnlocked setter { totalSupply = total; } /** * Set the Token Standard the contract applies to. * * @param std the Standard. */ function setStandard(bytes32 std) onlyOwnerUnlocked setter { standard = std; } /** * Sets the name of the contraxt * * @param _name the name. */ function setName(bytes32 _name) onlyOwnerUnlocked setter { name = _name; } /** * Sets the symbol * * @param sym The Symbol */ function setSymbol(bytes32 sym) onlyOwnerUnlocked setter { symbol = sym; } /** * Sets the precision * * @param precision Amount of decimals */ function setPrecisionDirect(uint8 precision) onlyOwnerUnlocked { decimals = precision; PrecisionSet(msg.sender, precision); } /** * Sets the balance of a certain account. * * @param addr Address of the account * @param amount Amount of assets to set on the account */ function setAccountBalance(address addr, uint256 amount) onlyOwnerUnlocked { balanceOf[addr] = amount; activateAccount(addr); } /** * Sets an allowance from a specific account to a specific account. * * @param from From-part of the allowance * @param to To-part of the allowance * @param amount Amount of the allowance */ function setAccountAllowance(address from, address to, uint256 amount) onlyOwnerUnlocked { allowance[from][to] = amount; activateAllowanceRecord(from, to); } /** * Sets the treasure balance to a certain account. * * @param amount Amount of assets to pre-set in the treasury */ function setTreasuryBalance(uint256 amount) onlyOwnerUnlocked { treasuryBalance = amount; } /** * Sets a certain account on frozen/unfrozen * * @param addr Account that will be frozen/unfrozen * @param frozen Boolean to freeze or unfreeze */ function setAccountFrozenStatus(address addr, bool frozen) onlyOwnerUnlocked { activateAccount(addr); frozenAccount[addr] = frozen; } /** * Sets up a import fee for a certain address. * * @param addr Address that will require fee * @param fee Amount of fee */ function setupImportFee(address addr, uint256 fee) onlyOwnerUnlocked { importFee[addr] = fee; activateImportFeeChargeRecord(addr); FeeSetup(msg.sender, addr, fee); } /** * Sets up a export fee for a certain address. * * @param addr Address that will require fee * @param fee Amount of fee */ function setupExportFee(address addr, uint256 fee) onlyOwnerUnlocked { exportFee[addr] = fee; activateExportFeeChargeRecord(addr); FeeSetup(msg.sender, addr, fee); } /* --------------- main token methods --------------*/ /** * @notice Transfer `_amount` from `msg.sender.address()` to `_to`. * * @param _to Address that will receive. * @param _amount Amount to be transferred. */ function transfer(address _to, uint256 _amount) returns (bool success) { assert(allowTransactions); assert(!frozenAccount[msg.sender]); assert(balanceOf[msg.sender] >= _amount); assert(balanceOf[_to] + _amount >= balanceOf[_to]); activateAccount(msg.sender); activateAccount(_to); balanceOf[msg.sender] -= _amount; if (_to == address(this)) treasuryBalance += _amount; else balanceOf[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } /** * @notice Transfer `_amount` from `_from` to `_to`. * * @param _from Origin address * @param _to Address that will receive * @param _amount Amount to be transferred. * @return result of the method call */ function transferFrom(address _from, address _to, uint256 _amount) returns (bool success) { assert(allowTransactions); assert(!frozenAccount[msg.sender]); assert(!frozenAccount[_from]); assert(balanceOf[_from] >= _amount); assert(balanceOf[_to] + _amount >= balanceOf[_to]); assert(_amount <= allowance[_from][msg.sender]); balanceOf[_from] -= _amount; balanceOf[_to] += _amount; allowance[_from][msg.sender] -= _amount; activateAccount(_from); activateAccount(_to); activateAccount(msg.sender); Transfer(_from, _to, _amount); return true; } /** * @notice Approve spender `_spender` to transfer `_amount` from `msg.sender.address()` * * @param _spender Address that receives the cheque * @param _amount Amount on the cheque * @param _extraData Consequential contract to be executed by spender in same transcation. * @return result of the method call */ function approveAndCall(address _spender, uint256 _amount, bytes _extraData) returns (bool success) { assert(allowTransactions); assert(!frozenAccount[msg.sender]); allowance[msg.sender][_spender] = _amount; activateAccount(msg.sender); activateAccount(_spender); activateAllowanceRecord(msg.sender, _spender); TokenRecipient spender = TokenRecipient(_spender); spender.receiveApproval(msg.sender, _amount, this, _extraData); Approval(msg.sender, _spender, _amount); return true; } /** * @notice Approve spender `_spender` to transfer `_amount` from `msg.sender.address()` * * @param _spender Address that receives the cheque * @param _amount Amount on the cheque * @return result of the method call */ function approve(address _spender, uint256 _amount) returns (bool success) { assert(allowTransactions); assert(!frozenAccount[msg.sender]); allowance[msg.sender][_spender] = _amount; activateAccount(msg.sender); activateAccount(_spender); activateAllowanceRecord(msg.sender, _spender); Approval(msg.sender, _spender, _amount); return true; } /* --------------- multisig admin methods --------------*/ /** * @notice Sets the expiry time in milliseconds since 1970. * * @param ts milliseconds since 1970. * */ function setExpiry(uint256 ts) multisig(sha3(msg.data)) { expiry = ts; } /** * @notice Mints `mintedAmount` new tokens to the hotwallet `hotWalletAddress`. * * @param mintedAmount Amount of new tokens to be minted. */ function mint(uint256 mintedAmount) multisig(sha3(msg.data)) { treasuryBalance += mintedAmount; totalSupply += mintedAmount; } /** * @notice Destroys `destroyAmount` new tokens from the hotwallet `hotWalletAddress` * * @param destroyAmount Amount of new tokens to be minted. */ function destroyTokens(uint256 destroyAmount) multisig(sha3(msg.data)) { assert(treasuryBalance >= destroyAmount); treasuryBalance -= destroyAmount; totalSupply -= destroyAmount; } /** * @notice Transfers `amount` from the treasury to `to` * * @param to Address to transfer to * @param amount Amount to transfer from treasury */ function transferFromTreasury(address to, uint256 amount) multisig(sha3(msg.data)) { assert(treasuryBalance >= amount); treasuryBalance -= amount; balanceOf[to] += amount; activateAccount(to); } /* --------------- fee setting administration methods --------------*/ /** * @notice Sets an import fee of `fee` on address `addr` * * @param addr Address for which the fee is valid * @param addr fee Fee * */ function setImportFee(address addr, uint256 fee) multisig(sha3(msg.data)) { uint256 max = 1; max = pow10(1, decimals); assert(fee <= max); importFee[addr] = fee; activateImportFeeChargeRecord(addr); } /** * @notice Sets an export fee of `fee` on address `addr` * * @param addr Address for which the fee is valid * @param addr fee Fee * */ function setExportFee(address addr, uint256 fee) multisig(sha3(msg.data)) { uint256 max = 1; max = pow10(1, decimals); assert(fee <= max); exportFee[addr] = fee; activateExportFeeChargeRecord(addr); } /* --------------- multisig emergency methods --------------*/ /** * @notice Sets allow transactions to `allow` * * @param allow Allow or disallow transactions */ function voteAllowTransactions(bool allow) multisig(sha3(msg.data)) { assert(allow != allowTransactions); allowTransactions = allow; } /** * @notice Destructs the contract and sends remaining `this.balance` Ether to `beneficiary` * * @param beneficiary Beneficiary of remaining Ether on contract */ function voteSuicide(address beneficiary) multisig(sha3(msg.data)) { selfdestruct(beneficiary); } /** * @notice Sets frozen to `freeze` for account `target` * * @param addr Address to be frozen/unfrozen * @param freeze Freeze/unfreeze account */ function freezeAccount(address addr, bool freeze) multisig(sha3(msg.data)) { frozenAccount[addr] = freeze; activateAccount(addr); } /** * @notice Seizes `seizeAmount` of tokens from `address` and transfers it to hotwallet * * @param addr Adress to seize tokens from * @param amount Amount of tokens to seize */ function seizeTokens(address addr, uint256 amount) multisig(sha3(msg.data)) { assert(balanceOf[addr] >= amount); assert(frozenAccount[addr]); activateAccount(addr); balanceOf[addr] -= amount; treasuryBalance += amount; } /* --------------- fee calculation method ---------------- */ /** * @notice 'Returns the fee for a transfer from `from` to `to` on an amount `amount`. * * Fee's consist of a possible * - import fee on transfers to an address * - export fee on transfers from an address * DVIP ownership on an address * - reduces fee on a transfer from this address to an import fee-ed address * - reduces the fee on a transfer to this address from an export fee-ed address * DVIP discount does not work for addresses that have an import fee or export fee set up against them. * * DVIP discount goes up to 100% * * @param from From address * @param to To address * @param amount Amount for which fee needs to be calculated. * */ function feeFor(address from, address to, uint256 amount) constant external returns (uint256 value) { uint256 fee = exportFee[from] + importFee[to]; if (fee == 0) return 0; uint256 amountHeld; bool discounted = true; uint256 oneDVIPUnit; if (exportFee[from] == 0 && balanceOf[from] != 0 && now < expiry) { amountHeld = balanceOf[from]; } else if (importFee[to] == 0 && balanceOf[to] != 0 && now < expiry) { amountHeld = balanceOf[to]; } else discounted = false; if (discounted) { oneDVIPUnit = pow10(1, decimals); if (amountHeld > oneDVIPUnit) amountHeld = oneDVIPUnit; uint256 remaining = oneDVIPUnit - amountHeld; return div10(amount*fee*remaining, decimals*2); } return div10(amount*fee, decimals); } /* --------------- overseer methods for emergency --------------*/ /** * @notice Shuts down all transaction and approval options on the asset contract */ function shutdownTransactions() onlyOverseer { allowTransactions = false; TransactionsShutDown(msg.sender); } /* --------------- helper methods for siphoning --------------*/ function extractAccountAllowanceRecordLength(address addr) constant returns (uint256 len) { return allowanceIndex[addr].length; } function extractAccountLength() constant returns (uint256 length) { return accountIndex.length; } /* --------------- private methods --------------*/ function activateAccount(address addr) internal { if (!accountActive[addr]) { accountActive[addr] = true; accountIndex.push(addr); } } function activateAllowanceRecord(address from, address to) internal { if (!allowanceActive[from][to]) { allowanceActive[from][to] = true; allowanceIndex[from].push(to); } } function activateExportFeeChargeRecord(address addr) internal { if (!exportFeeActive[addr]) { exportFeeActive[addr] = true; exportFeeIndex.push(addr); } } function activateImportFeeChargeRecord(address addr) internal { if (!importFeeActive[addr]) { importFeeActive[addr] = true; importFeeIndex.push(addr); } } function extractImportFeeChargeLength() returns (uint256 length) { return importFeeIndex.length; } function extractExportFeeChargeLength() returns (uint256 length) { return exportFeeIndex.length; } } /** * @title DCAssetBackend Contract * * @author Ray Pulver, [email protected] */ contract DCAssetBackend is Owned, Precision, StateTransferrable, TrustClient, Util { bytes32 public standard = 'Token 0.1'; bytes32 public name; bytes32 public symbol; bool public allowTransactions; event Approval(address indexed from, address indexed spender, uint256 amount); mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); uint256 public totalSupply; address public hotWalletAddress; address public assetAddress; address public oversightAddress; address public membershipAddress; mapping (address => bool) public frozenAccount; mapping (address => address[]) public allowanceIndex; mapping (address => mapping (address => bool)) public allowanceActive; address[] public accountIndex; mapping (address => bool) public accountActive; bool public isActive; uint256 public treasuryBalance; mapping (address => uint256) public feeCharge; address[] public feeChargeIndex; mapping (address => bool) feeActive; event FrozenFunds(address target, bool frozen); event PrecisionSet(address indexed from, uint8 precision); event TransactionsShutDown(address indexed from); event FeeSetup(address indexed from, address indexed target, uint256 amount); /** * Constructor. * * @param tokenName Name of the Token * @param tokenSymbol The Token Symbol */ function DCAssetBackend(bytes32 tokenSymbol, bytes32 tokenName) { isActive = true; name = tokenName; symbol = tokenSymbol; decimals = 6; allowTransactions = true; } /* --------------- modifiers --------------*/ /** * Makes sure a method is only called by an overseer. */ modifier onlyOverseer { assert(msg.sender == oversightAddress); _ } /** * Make sure only the front end Asset can call the transfer methods */ modifier onlyAsset { assert(msg.sender == assetAddress); _ } /* --------------- setter methods, only for the unlocked state --------------*/ /** * Sets the hot wallet contract address * * @param addr Address of the Hotwallet */ function setHotWallet(address addr) onlyOwnerUnlocked setter { hotWalletAddress = addr; } /** * Sets the token facade contract address * * @param addr Address of the front-end Asset */ function setAsset(address addr) onlyOwnerUnlocked setter { assetAddress = addr; } /** * Sets the membership contract address * * @param addr Address of the membership contract */ function setMembership(address addr) onlyOwnerUnlocked setter { membershipAddress = addr; } /** * Sets the oversight address (not the contract). * * @param addr The oversight contract address. */ function setOversight(address addr) onlyOwnerUnlocked setter { oversightAddress = addr; } /** * Sets the total supply * * @param total Total supply of the asset. */ function setTotalSupply(uint256 total) onlyOwnerUnlocked setter { totalSupply = total; } /** * Set the Token Standard the contract applies to. * * @param std the Standard. */ function setStandard(bytes32 std) onlyOwnerUnlocked setter { standard = std; } /** * Sets the name of the contraxt * * @param _name the name. */ function setName(bytes32 _name) onlyOwnerUnlocked setter { name = _name; } /** * Sets the symbol * * @param sym The Symbol */ function setSymbol(bytes32 sym) onlyOwnerUnlocked setter { symbol = sym; } /** * Sets the precision * * @param precision Amount of decimals */ function setPrecisionDirect(uint8 precision) onlyOwnerUnlocked { decimals = precision; PrecisionSet(msg.sender, precision); } /** * Sets the balance of a certain account. * * @param addr Address of the account * @param amount Amount of assets to set on the account */ function setAccountBalance(address addr, uint256 amount) onlyOwnerUnlocked { balanceOf[addr] = amount; activateAccount(addr); } /** * Sets an allowance from a specific account to a specific account. * * @param from From-part of the allowance * @param to To-part of the allowance * @param amount Amount of the allowance */ function setAccountAllowance(address from, address to, uint256 amount) onlyOwnerUnlocked { allowance[from][to] = amount; activateAllowanceRecord(from, to); } /** * Sets the treasure balance to a certain account. * * @param amount Amount of assets to pre-set in the treasury */ function setTreasuryBalance(uint256 amount) onlyOwnerUnlocked { treasuryBalance = amount; } /** * Sets a certain account on frozen/unfrozen * * @param addr Account that will be frozen/unfrozen * @param frozen Boolean to freeze or unfreeze */ function setAccountFrozenStatus(address addr, bool frozen) onlyOwnerUnlocked { activateAccount(addr); frozenAccount[addr] = frozen; } /* --------------- main token methods --------------*/ /** * @notice Transfer `_amount` from `_caller` to `_to`. * * @param _caller Origin address * @param _to Address that will receive. * @param _amount Amount to be transferred. */ function transfer(address _caller, address _to, uint256 _amount) onlyAsset returns (bool success) { assert(allowTransactions); assert(!frozenAccount[_caller]); assert(balanceOf[_caller] >= _amount); assert(balanceOf[_to] + _amount >= balanceOf[_to]); activateAccount(_caller); activateAccount(_to); balanceOf[_caller] -= _amount; if (_to == address(this)) treasuryBalance += _amount; else { uint256 fee = feeFor(_caller, _to, _amount); balanceOf[_to] += _amount - fee; treasuryBalance += fee; } Transfer(_caller, _to, _amount); return true; } /** * @notice Transfer `_amount` from `_from` to `_to`, invoked by `_caller`. * * @param _caller Invoker of the call (owner of the allowance) * @param _from Origin address * @param _to Address that will receive * @param _amount Amount to be transferred. * @return result of the method call */ function transferFrom(address _caller, address _from, address _to, uint256 _amount) onlyAsset returns (bool success) { assert(allowTransactions); assert(!frozenAccount[_caller]); assert(!frozenAccount[_from]); assert(balanceOf[_from] >= _amount); assert(balanceOf[_to] + _amount >= balanceOf[_to]); assert(_amount <= allowance[_from][_caller]); balanceOf[_from] -= _amount; uint256 fee = feeFor(_from, _to, _amount); balanceOf[_to] += _amount - fee; treasuryBalance += fee; allowance[_from][_caller] -= _amount; activateAccount(_from); activateAccount(_to); activateAccount(_caller); Transfer(_from, _to, _amount); return true; } /** * @notice Approve Approves spender `_spender` to transfer `_amount` from `_caller` * * @param _caller Address that grants the allowance * @param _spender Address that receives the cheque * @param _amount Amount on the cheque * @param _extraData Consequential contract to be executed by spender in same transcation. * @return result of the method call */ function approveAndCall(address _caller, address _spender, uint256 _amount, bytes _extraData) onlyAsset returns (bool success) { assert(allowTransactions); assert(!frozenAccount[_caller]); allowance[_caller][_spender] = _amount; activateAccount(_caller); activateAccount(_spender); activateAllowanceRecord(_caller, _spender); TokenRecipient spender = TokenRecipient(_spender); assert(Relay(assetAddress).relayReceiveApproval(_caller, _spender, _amount, _extraData)); Approval(_caller, _spender, _amount); return true; } /** * @notice Approve Approves spender `_spender` to transfer `_amount` from `_caller` * * @param _caller Address that grants the allowance * @param _spender Address that receives the cheque * @param _amount Amount on the cheque * @return result of the method call */ function approve(address _caller, address _spender, uint256 _amount) onlyAsset returns (bool success) { assert(allowTransactions); assert(!frozenAccount[_caller]); allowance[_caller][_spender] = _amount; activateAccount(_caller); activateAccount(_spender); activateAllowanceRecord(_caller, _spender); Approval(_caller, _spender, _amount); return true; } /* --------------- multisig admin methods --------------*/ /** * @notice Mints `mintedAmount` new tokens to the hotwallet `hotWalletAddress`. * * @param mintedAmount Amount of new tokens to be minted. */ function mint(uint256 mintedAmount) multisig(sha3(msg.data)) { activateAccount(hotWalletAddress); balanceOf[hotWalletAddress] += mintedAmount; totalSupply += mintedAmount; } /** * @notice Destroys `destroyAmount` new tokens from the hotwallet `hotWalletAddress` * * @param destroyAmount Amount of new tokens to be minted. */ function destroyTokens(uint256 destroyAmount) multisig(sha3(msg.data)) { assert(balanceOf[hotWalletAddress] >= destroyAmount); activateAccount(hotWalletAddress); balanceOf[hotWalletAddress] -= destroyAmount; totalSupply -= destroyAmount; } /** * @notice Transfers `amount` from the treasury to `to` * * @param to Address to transfer to * @param amount Amount to transfer from treasury */ function transferFromTreasury(address to, uint256 amount) multisig(sha3(msg.data)) { assert(treasuryBalance >= amount); treasuryBalance -= amount; balanceOf[to] += amount; activateAccount(to); } /* --------------- multisig emergency methods --------------*/ /** * @notice Sets allow transactions to `allow` * * @param allow Allow or disallow transactions */ function voteAllowTransactions(bool allow) multisig(sha3(msg.data)) { if (allow == allowTransactions) throw; allowTransactions = allow; } /** * @notice Destructs the contract and sends remaining `this.balance` Ether to `beneficiary` * * @param beneficiary Beneficiary of remaining Ether on contract */ function voteSuicide(address beneficiary) multisig(sha3(msg.data)) { selfdestruct(beneficiary); } /** * @notice Sets frozen to `freeze` for account `target` * * @param addr Address to be frozen/unfrozen * @param freeze Freeze/unfreeze account */ function freezeAccount(address addr, bool freeze) multisig(sha3(msg.data)) { frozenAccount[addr] = freeze; activateAccount(addr); } /** * @notice Seizes `seizeAmount` of tokens from `address` and transfers it to hotwallet * * @param addr Adress to seize tokens from * @param amount Amount of tokens to seize */ function seizeTokens(address addr, uint256 amount) multisig(sha3(msg.data)) { assert(balanceOf[addr] >= amount); assert(frozenAccount[addr]); activateAccount(addr); balanceOf[addr] -= amount; balanceOf[hotWalletAddress] += amount; } /* --------------- overseer methods for emergency --------------*/ /** * @notice Shuts down all transaction and approval options on the asset contract */ function shutdownTransactions() onlyOverseer { allowTransactions = false; TransactionsShutDown(msg.sender); } /* --------------- helper methods for siphoning --------------*/ function extractAccountAllowanceRecordLength(address addr) returns (uint256 len) { return allowanceIndex[addr].length; } function extractAccountLength() returns (uint256 length) { return accountIndex.length; } /* --------------- private methods --------------*/ function activateAccount(address addr) internal { if (!accountActive[addr]) { accountActive[addr] = true; accountIndex.push(addr); } } function activateAllowanceRecord(address from, address to) internal { if (!allowanceActive[from][to]) { allowanceActive[from][to] = true; allowanceIndex[from].push(to); } } function feeFor(address a, address b, uint256 amount) returns (uint256 value) { if (membershipAddress == address(0x0)) return 0; return DVIP(membershipAddress).feeFor(a, b, amount); } } /** * @title DCAssetFacade, Facade for the underlying back-end dcasset token contract. Allow to be updated later. * * @author P.S.D. Reitsma, [email protected] * */ contract DCAsset is TokenBase, StateTransferrable, TrustClient, Relay { address public backendContract; /** * Constructor * * */ function DCAsset(address _backendContract) { backendContract = _backendContract; } function standard() constant returns (bytes32 std) { return DCAssetBackend(backendContract).standard(); } function name() constant returns (bytes32 nm) { return DCAssetBackend(backendContract).name(); } function symbol() constant returns (bytes32 sym) { return DCAssetBackend(backendContract).symbol(); } function decimals() constant returns (uint8 precision) { return DCAssetBackend(backendContract).decimals(); } function allowance(address from, address to) constant returns (uint256 res) { return DCAssetBackend(backendContract).allowance(from, to); } /* --------------- multisig admin methods --------------*/ /** * @notice Sets the backend contract to `_backendContract`. Can only be switched by multisig. * * @param _backendContract Address of the underlying token contract. */ function setBackend(address _backendContract) multisig(sha3(msg.data)) { backendContract = _backendContract; } /* --------------- main token methods --------------*/ /** * @notice Returns the balance of `_address`. * * @param _address The address of the balance. */ function balanceOf(address _address) constant returns (uint256 balance) { return DCAssetBackend(backendContract).balanceOf(_address); } /** * @notice Returns the total supply of the token * */ function totalSupply() constant returns (uint256 balance) { return DCAssetBackend(backendContract).totalSupply(); } /** * @notice Transfer `_amount` to `_to`. * * @param _to Address that will receive. * @param _amount Amount to be transferred. */ function transfer(address _to, uint256 _amount) returns (bool success) { if (!DCAssetBackend(backendContract).transfer(msg.sender, _to, _amount)) throw; Transfer(msg.sender, _to, _amount); return true; } /** * @notice Approve Approves spender `_spender` to transfer `_amount`. * * @param _spender Address that receives the cheque * @param _amount Amount on the cheque * @param _extraData Consequential contract to be executed by spender in same transcation. * @return result of the method call */ function approveAndCall(address _spender, uint256 _amount, bytes _extraData) returns (bool success) { if (!DCAssetBackend(backendContract).approveAndCall(msg.sender, _spender, _amount, _extraData)) throw; Approval(msg.sender, _spender, _amount); return true; } /** * @notice Approve Approves spender `_spender` to transfer `_amount`. * * @param _spender Address that receives the cheque * @param _amount Amount on the cheque * @return result of the method call */ function approve(address _spender, uint256 _amount) returns (bool success) { if (!DCAssetBackend(backendContract).approve(msg.sender, _spender, _amount)) throw; Approval(msg.sender, _spender, _amount); return true; } /** * @notice Transfer `_amount` from `_from` to `_to`. * * @param _from Origin address * @param _to Address that will receive * @param _amount Amount to be transferred. * @return result of the method call */ function transferFrom(address _from, address _to, uint256 _amount) returns (bool success) { if (!DCAssetBackend(backendContract).transferFrom(msg.sender, _from, _to, _amount)) throw; Transfer(_from, _to, _amount); return true; } /** * @notice Returns fee for transferral of `_amount` from `_from` to `_to`. * * @param _from Origin address * @param _to Address that will receive * @param _amount Amount to be transferred. * @return height of the fee */ function feeFor(address _from, address _to, uint256 _amount) returns (uint256 amount) { return DCAssetBackend(backendContract).feeFor(_from, _to, _amount); } /* --------------- to be called by backend --------------*/ function relayReceiveApproval(address _caller, address _spender, uint256 _amount, bytes _extraData) returns (bool success) { assert(msg.sender == backendContract); TokenRecipient spender = TokenRecipient(_spender); spender.receiveApproval(_caller, _amount, this, _extraData); return true; } }
* Make sure only the front end Asset can call the transfer methods/
modifier onlyAsset { assert(msg.sender == assetAddress); _ }
1,030,511
[ 1, 6464, 3071, 1338, 326, 6641, 679, 10494, 848, 745, 326, 7412, 2590, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 282, 9606, 1338, 6672, 288, 203, 565, 1815, 12, 3576, 18, 15330, 422, 3310, 1887, 1769, 203, 565, 389, 203, 282, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x22a34Ff33fF71708515866CdA88d3f9Cc5479bA4/sources/contracts/Mainnet/V2_Weth/ERC20Generic.sol
@notice Transfer a _value amount of ERC token from msg.sender to _to Throw if msg.sender doesn't have enough tokens @param _to The address of the recipient @param _value The amount of token to send @return success true if success, throw if failed
function transfer(address _to, uint256 _value) public returns (bool success){ require(balanceOf[msg.sender] >= _value, "msg.sender balance is too low"); balanceOf[msg.sender] = balanceOf[msg.sender] - _value; balanceOf[_to] = balanceOf[_to] + _value; emit Transfer(msg.sender, _to, _value); return true; }
12,490,588
[ 1, 5912, 279, 389, 1132, 3844, 434, 4232, 39, 1147, 628, 1234, 18, 15330, 358, 389, 869, 3743, 309, 1234, 18, 15330, 3302, 1404, 1240, 7304, 2430, 225, 389, 869, 1021, 1758, 434, 326, 8027, 225, 389, 1132, 1021, 3844, 434, 1147, 358, 1366, 327, 2216, 638, 309, 2216, 16, 604, 309, 2535, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 2216, 15329, 203, 3639, 2583, 12, 12296, 951, 63, 3576, 18, 15330, 65, 1545, 389, 1132, 16, 315, 3576, 18, 15330, 11013, 353, 4885, 4587, 8863, 203, 3639, 11013, 951, 63, 3576, 18, 15330, 65, 273, 11013, 951, 63, 3576, 18, 15330, 65, 300, 389, 1132, 31, 203, 3639, 11013, 951, 63, 67, 869, 65, 273, 11013, 951, 63, 67, 869, 65, 397, 389, 1132, 31, 203, 3639, 3626, 12279, 12, 3576, 18, 15330, 16, 389, 869, 16, 389, 1132, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]