file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
/* * * $DEWO Token - The Native Token In DecentraWorld's Ecosystem * DecentraWorld - Increasing Privacy Standards In DeFi * * Documentation: http://docs.decentraworld.co/ * GitHub: https://github.com/decentraworldDEWO * DecentraWorld: https://DecentraWorld.co/ * DAO: https://dao.decentraworld.co/ * Governance: https://gov.decentraworld.co/ * DecentraMix: https://decentramix.io/ * *░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *░░██████╗░███████╗░█████╗░███████╗███╗░░██╗████████╗██████╗░░█████╗░░░ *░░██╔══██╗██╔════╝██╔══██╗██╔════╝████╗░██║╚══██╔══╝██╔══██╗██╔══██╗░░ *░░██║░░██║█████╗░░██║░░╚═╝█████╗░░██╔██╗██║░░░██║░░░██████╔╝███████║░░ *░░██║░░██║██╔══╝░░██║░░██╗██╔══╝░░██║╚████║░░░██║░░░██╔══██╗██╔══██║░░ *░░██████╔╝███████╗╚█████╔╝███████╗██║░╚███║░░░██║░░░██║░░██║██║░░██║░░ *░░╚═════╝░╚══════╝░╚════╝░╚══════╝╚═╝░░╚══╝░░░╚═╝░░░╚═╝░░╚═╝╚═╝░░╚═╝░░ *░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *░░░░░░░░░░░░░██╗░░░░░░░██╗░█████╗░██████╗░██╗░░░░░██████╗░░░░░░░░░░░░░ *░░░░░░░░░░░░░██║░░██╗░░██║██╔══██╗██╔══██╗██║░░░░░██╔══██╗░░░░░░░░░░░░ *░░░░░░░░░░░░░╚██╗████╗██╔╝██║░░██║██████╔╝██║░░░░░██║░░██║░░░░░░░░░░░░ *░░░░░░░░░░░░░░████╔═████║░██║░░██║██╔══██╗██║░░░░░██║░░██║░░░░░░░░░░░░ *░░░░░░░░░░░░░░╚██╔╝░╚██╔╝░╚█████╔╝██║░░██║███████╗██████╔╝░░░░░░░░░░░░ *░░░░░░░░░░░░░░░╚═╝░░░╚═╝░░░╚════╝░╚═╝░░╚═╝╚══════╝╚═════╝░░░░░░░░░░░░░ *░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * */ // SPDX-License-Identifier: MIT // File: @OpenZeppelin/contracts/utils/math/SafeMath.sol // 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; } } } // File: @OpenZeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @OpenZeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/DecentraWorld_Multichain.sol /* * * $DEWO Token - The Native Token In DecentraWorld's Ecosystem * DecentraWorld - Increasing Privacy Standards In DeFi * * Documentation: http://docs.decentraworld.co/ * GitHub: https://github.com/decentraworldDEWO * DecentraWorld: https://DecentraWorld.co/ * DAO: https://dao.decentraworld.co/ * Governance: https://gov.decentraworld.co/ * DecentraMix: https://decentramix.io/ * *░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *░░██████╗░███████╗░█████╗░███████╗███╗░░██╗████████╗██████╗░░█████╗░░░ *░░██╔══██╗██╔════╝██╔══██╗██╔════╝████╗░██║╚══██╔══╝██╔══██╗██╔══██╗░░ *░░██║░░██║█████╗░░██║░░╚═╝█████╗░░██╔██╗██║░░░██║░░░██████╔╝███████║░░ *░░██║░░██║██╔══╝░░██║░░██╗██╔══╝░░██║╚████║░░░██║░░░██╔══██╗██╔══██║░░ *░░██████╔╝███████╗╚█████╔╝███████╗██║░╚███║░░░██║░░░██║░░██║██║░░██║░░ *░░╚═════╝░╚══════╝░╚════╝░╚══════╝╚═╝░░╚══╝░░░╚═╝░░░╚═╝░░╚═╝╚═╝░░╚═╝░░ *░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *░░░░░░░░░░░░░██╗░░░░░░░██╗░█████╗░██████╗░██╗░░░░░██████╗░░░░░░░░░░░░░ *░░░░░░░░░░░░░██║░░██╗░░██║██╔══██╗██╔══██╗██║░░░░░██╔══██╗░░░░░░░░░░░░ *░░░░░░░░░░░░░╚██╗████╗██╔╝██║░░██║██████╔╝██║░░░░░██║░░██║░░░░░░░░░░░░ *░░░░░░░░░░░░░░████╔═████║░██║░░██║██╔══██╗██║░░░░░██║░░██║░░░░░░░░░░░░ *░░░░░░░░░░░░░░╚██╔╝░╚██╔╝░╚█████╔╝██║░░██║███████╗██████╔╝░░░░░░░░░░░░ *░░░░░░░░░░░░░░░╚═╝░░░╚═╝░░░╚════╝░╚═╝░░╚═╝╚══════╝╚═════╝░░░░░░░░░░░░░ *░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * */ pragma solidity ^0.8.7; /** * @dev Interfaces */ interface IDEXFactory { 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 IDEXRouter { 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 swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } interface IPancakeswapV2Pair { 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; } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address to, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev 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); } contract DecentraWorld_Multichain is Context, IERC20, IERC20Metadata, Ownable { using SafeMath for uint256; // DecentraWorld - $DEWO uint256 _totalSupply; string private _name; string private _symbol; uint8 private _decimals; // Mapping mapping (string => uint) txTaxes; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; mapping (address => bool) public excludeFromTax; mapping (address => bool) public exclueFromMaxTx; // Addresses Of Tax Receivers address public daoandfarmingAddress; address public marketingAddress; address public developmentAddress; address public coreteamAddress; // Address of the bridge controling the mint/burn of the cross-chain address public MPC; // taxes for differnet levels struct TaxLevels { uint taxDiscount; uint amount; } struct DEWOTokenTax { uint forMarketing; uint forCoreTeam; uint forDevelopment; uint forDAOAndFarming; } struct TxLimit { uint buyMaxTx; uint sellMaxTx; uint txcooldown; mapping(address => uint) buys; mapping(address => uint) sells; mapping(address => uint) lastTx; } mapping (uint => TaxLevels) taxTiers; TxLimit txSettings; IDEXRouter public router; address public pair; constructor() { _name = "DecentraWorld"; _symbol = "$DEWO"; _decimals = 18; //Temporary Tax Receivers daoandfarmingAddress = msg.sender; marketingAddress = 0x5d5a0368b8C383c45c625a7241473A1a4F61eA4E; developmentAddress = 0xdA9f5e831b7D18c35CA7778eD271b4d4f3bE183E; coreteamAddress = 0x797BD28BaE691B21e235E953043337F4794Ff9DB; // Exclude From Taxes By Default excludeFromTax[msg.sender] = true; excludeFromTax[daoandfarmingAddress] = true; excludeFromTax[marketingAddress] = true; excludeFromTax[developmentAddress] = true; excludeFromTax[coreteamAddress] = true; // Exclude From MaxTx By Default exclueFromMaxTx[msg.sender] = true; exclueFromMaxTx[daoandfarmingAddress] = true; exclueFromMaxTx[marketingAddress] = true; exclueFromMaxTx[developmentAddress] = true; exclueFromMaxTx[coreteamAddress] = true; // Cross-Chain Bridge Temp Settings MPC = msg.sender; // Transaction taxes apply solely on swaps (buys/sells) // Tier 1 - Default Buy Fee [6% Total] // Tier 2 - Buy Fee [3% Total] // Tier 3 - Buy Fee [0% Total] // // Automatically set the default transactions taxes // [Tier 1: 6% Buy Fee] txTaxes["marketingBuyTax"] = 3; // [3%] DAO, Governance, Farming Pools txTaxes["developmentBuyTax"] = 1; // [1%] Marketing Fee txTaxes["coreteamBuyTax"] = 1; // [1%] Development Fee txTaxes["daoandfarmingBuyTax"] = 1; // [1%] DecentraWorld's Core-Team // [Tier 1: 10% Sell Fee] txTaxes["marketingSellTax"] = 4; // 4% DAO, Governance, Farming Pools txTaxes["developmentSellTax"] = 3; // 3% Marketing Fee txTaxes["coreteamSellTax"] = 1; // 1% Development Fee txTaxes["daoandfarmingSellTax"] = 2; // 2% DecentraWorld's Core-Team /* Buy Transaction Tax - 3 tiers: *** Must buy these amounts to qualify Tier 1: 6%/10% (0+ $DEWO balance) Tier 2: 3%/8% (100K+ $DEWO balance) Tier 3: 0%/6% (400K+ $DEWO balance) Sell Transaction Tax - 3 tiers: *** Must hold these amounts to qualify Tier 1: 6%/10% (0+ $DEWO balance) Tier 2: 3%/8% (150K+ $DEWO balance) Tier 3: 0%/6% (300K+ $DEWO balance) Tax Re-distribution Buys (6%/3%/0%): DAO Fund/Farming: 3% | 1% | 0% Marketing Budget: 1% | 1% | 0% Development Fund: 1% | 0% | 0% Core-Team: 1% | 1% | 0% Tax Re-distribution Sells (10%/8%/6%): DAO Fund/Farming: 4% | 3% | 3% Marketing Budget: 3% | 2% | 1% Development Fund: 1% | 1% | 1% Core-Team: 2% | 2% | 1% The community can disable the holder rewards fee and migrate that fee to the rewards/staking pool. This can be done via the Governance portal. */ // Default Tax Tiers & Discounts // Get a 50% discount on purchase tax taxes taxTiers[0].taxDiscount = 50; // When buying over 0.1% of total supply (100,000 $DEWO) taxTiers[0].amount = 100000 * (10 ** decimals()); // Get a 100% discount on purchase tax taxes taxTiers[1].taxDiscount = 99; // When buying over 0.4% of total supply (400,000 $DEWO) taxTiers[1].amount = 400000 * (10 ** decimals()); // Get a 20% discount on sell tax taxes taxTiers[2].taxDiscount = 20; // When holding over 0.15% of total supply (150,000 $DEWO) taxTiers[2].amount = 150000 * (10 ** decimals()); // Get a 40% discount on sell tax taxes taxTiers[3].taxDiscount = 40; // When holding over 0.3% of total supply (300,000 $DEWO) taxTiers[3].amount = 300000 * (10 ** decimals()); // Default txcooldown limit in minutes txSettings.txcooldown = 30 minutes; // Default buy limit: 1.25% of total supply txSettings.buyMaxTx = _totalSupply.div(80); // Default sell limit: 0.25% of total supply txSettings.sellMaxTx = _totalSupply.div(800); /** Removed from the cross-chain $DEWO token, the pair settings were replaced with a function, and the mint function of 100,000,000 $DEWO to deployer was replaced with 0. Since this token is a cross-chain token and not the native EVM chain where $DEWO was deployed (BSC) then there's no need in any additional supply. The Multichain.org bridge will call burn/mint functions accordingly. --- // Create a PancakeSwap (DEX) Pair For $DEWO // This will be used to track the price of $DEWO & charge taxes to all pool buys/sells address WBNB = 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c; // Wrapped BNB on Binance Smart Chain address _router = 0x10ED43C718714eb63d5aA57B78B54704E256024E; // PancakeSwap Router (ChainID: 56 = BSC) router = IDEXRouter(_router); pair = IDEXFactory(router.factory()).createPair(WBNB, address(this)); _allowances[address(this)][address(router)] = _totalSupply; approve(_router, _totalSupply); // Send 100,000,000 $DEWO tokens to the dev (one time only) _balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); */ } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } // onlyAuth = allow MPC contract address to call certain functions // The MPC = Multichain bridge contract of each chain modifier onlyAuth() { require(msg.sender == mmpc(), "DecentraWorld: FORBIDDEN"); _; } function mmpc() public view returns (address) { return MPC; } // This can only be done once by the deployer, once the MPC is set only the MPC can call this function again. function setMPC(address _setmpc) external onlyAuth { MPC = _setmpc; } // Mint will be used when individuals cross-chain $DEWO from one chain to another function mint(address to, uint256 amount) external onlyAuth returns (bool) { _mint(to, amount); return true; } // The burn function will be used to burn tokens that were cross-chained into another EVM chain function burn(address from, uint256 amount) external onlyAuth returns (bool) { require(from != address(0), "DecentraWorld: address(0x0)"); _burn(from, amount); return true; } function Swapin(bytes32 txhash, address account, uint256 amount) public onlyAuth returns (bool) { _mint(account, amount); emit LogSwapin(txhash, account, amount); return true; } function Swapout(uint256 amount, address bindaddr) public returns (bool) { require(bindaddr != address(0), "DecentraWorld: address(0x0)"); _burn(msg.sender, amount); emit LogSwapout(msg.sender, bindaddr, amount); return true; } event LogSwapin(bytes32 indexed txhash, address indexed account, uint amount); event LogSwapout(address indexed account, address indexed bindaddr, uint amount); // Set the router & native token of each chain to tax the correct LP POOL of $DEWO // This will always be the most popular DEX on the chain + its native token. function setDEXPAIR(address _nativetoken, address _nativerouter) external onlyOwner { // Create a DEX Pair For $DEWO // This will be used to track the price of $DEWO & charge taxes to all pool buys/sells router = IDEXRouter(_nativerouter); pair = IDEXFactory(router.factory()).createPair(_nativetoken, address(this)); _allowances[address(this)][address(router)] = _totalSupply; approve(_nativerouter, _totalSupply); } // Set Buy Taxes event BuyTaxes( uint _daoandfarmingBuyTax, uint _coreteamBuyTax, uint _developmentBuyTax, uint _marketingBuyTax ); function setBuyTaxes( uint _daoandfarmingBuyTax, uint _coreteamBuyTax, uint _developmentBuyTax, uint _marketingBuyTax // Hardcoded limitation to the maximum tax fee per address // Maximum tax for each buys/sells: 6% max tax per tax receiver, 24% max tax total ) external onlyOwner { require(_daoandfarmingBuyTax <= 6, "DAO & Farming tax is above 6%!"); require(_coreteamBuyTax <= 6, "Core-Team Buy tax is above 6%!"); require(_developmentBuyTax <= 6, "Development Fund tax is above 6%!"); require(_marketingBuyTax <= 6, "Marketing tax is above 6%!"); txTaxes["daoandfarmingBuyTax"] = _daoandfarmingBuyTax; txTaxes["coreteamBuyTax"] = _coreteamBuyTax; txTaxes["developmentBuyTax"] = _developmentBuyTax; txTaxes["marketingBuyTax"] = _marketingBuyTax; emit BuyTaxes( _daoandfarmingBuyTax, _coreteamBuyTax, _developmentBuyTax, _marketingBuyTax ); } // Set Sell Taxes event SellTaxes( uint _daoandfarmingSellTax, uint _coreteamSellTax, uint _developmentSellTax, uint _marketingSellTax ); function setSellTaxes( uint _daoandfarmingSellTax, uint _coreteamSellTax, uint _developmentSellTax, uint _marketingSellTax // Hardcoded limitation to the maximum tax fee per address // Maximum tax for buys/sells: 6% max tax per tax receiver, 24% max tax total ) external onlyOwner { require(_daoandfarmingSellTax <= 6, "DAO & Farming tax is above 6%!"); require(_coreteamSellTax <= 6, "Core-team tax is above 6%!"); require(_developmentSellTax <= 6, "Development tax is above 6%!"); require(_marketingSellTax <= 6, "Marketing tax is above 6%!"); txTaxes["daoandfarmingSellTax"] = _daoandfarmingSellTax; txTaxes["coreteamSellTax"] = _coreteamSellTax; txTaxes["developmentSellTax"] = _developmentSellTax; txTaxes["marketingSellTax"] = _marketingSellTax; emit SellTaxes( _daoandfarmingSellTax, _coreteamSellTax, _developmentSellTax, _marketingSellTax ); } // Displays a list of all current taxes function getSellTaxes() public view returns( uint marketingSellTax, uint developmentSellTax, uint coreteamSellTax, uint daoandfarmingSellTax ) { return ( txTaxes["marketingSellTax"], txTaxes["developmentSellTax"], txTaxes["coreteamSellTax"], txTaxes["daoandfarmingSellTax"] ); } // Displays a list of all current taxes function getBuyTaxes() public view returns( uint marketingBuyTax, uint developmentBuyTax, uint coreteamBuyTax, uint daoandfarmingBuyTax ) { return ( txTaxes["marketingBuyTax"], txTaxes["developmentBuyTax"], txTaxes["coreteamBuyTax"], txTaxes["daoandfarmingBuyTax"] ); } // Set the DAO and Farming Tax Receiver Address (daoandfarmingAddress) function setDAOandFarmingAddress(address _daoandfarmingAddress) external onlyOwner { daoandfarmingAddress = _daoandfarmingAddress; } // Set the Marketing Tax Receiver Address (marketingAddress) function setMarketingAddress(address _marketingAddress) external onlyOwner { marketingAddress = _marketingAddress; } // Set the Development Tax Receiver Address (developmentAddress) function setDevelopmentAddress(address _developmentAddress) external onlyOwner { developmentAddress = _developmentAddress; } // Set the Core-Team Tax Receiver Address (coreteamAddress) function setCoreTeamAddress(address _coreteamAddress) external onlyOwner { coreteamAddress = _coreteamAddress; } // Exclude an address from tax function setExcludeFromTax(address _address, bool _value) external onlyOwner { excludeFromTax[_address] = _value; } // Exclude an address from maximum transaction limit function setExclueFromMaxTx(address _address, bool _value) external onlyOwner { exclueFromMaxTx[_address] = _value; } // Set Buy Tax Tiers function setBuyTaxTiers(uint _discount1, uint _amount1, uint _discount2, uint _amount2) external onlyOwner { require(_discount1 > 0 && _discount1 < 100 && _discount2 > 0 && _discount2 < 100 && _amount1 > 0 && _amount2 > 0, "Values have to be bigger than zero!"); taxTiers[0].taxDiscount = _discount1; taxTiers[0].amount = _amount1; taxTiers[1].taxDiscount = _discount2; taxTiers[1].amount = _amount2; } // Set Sell Tax Tiers function setSellTaxTiers(uint _discount3, uint _amount3, uint _discount4, uint _amount4) external onlyOwner { require(_discount3 > 0 && _discount3 < 100 && _discount4 > 0 && _discount4 < 100 && _amount3 > 0 && _amount4 > 0, "Values have to be bigger than zero!"); taxTiers[2].taxDiscount = _discount3; taxTiers[2].amount = _amount3; taxTiers[3].taxDiscount = _discount4; taxTiers[3].amount = _amount4; } // Get Buy Tax Tiers function getBuyTaxTiers() public view returns(uint discount1, uint amount1, uint discount2, uint amount2) { return (taxTiers[0].taxDiscount, taxTiers[0].amount, taxTiers[1].taxDiscount, taxTiers[1].amount); } // Get Sell Tax Tiers function getSellTaxTiers() public view returns(uint discount3, uint amount3, uint discount4, uint amount4) { return (taxTiers[2].taxDiscount, taxTiers[2].amount, taxTiers[3].taxDiscount, taxTiers[3].amount); } // Set Transaction Settings: Max Buy Limit, Max Sell Limit, Cooldown Limit. function setTxSettings(uint _buyMaxTx, uint _sellMaxTx, uint _txcooldown) external onlyOwner { require(_buyMaxTx >= _totalSupply.div(200), "Buy transaction limit is too low!"); // 0.5% require(_sellMaxTx >= _totalSupply.div(400), "Sell transaction limit is too low!"); // 0.25% require(_txcooldown <= 4 minutes, "Cooldown should be 4 minutes or less!"); txSettings.buyMaxTx = _buyMaxTx; txSettings.sellMaxTx = _sellMaxTx; txSettings.txcooldown = _txcooldown; } // Get Max Transaction Settings: Max Buy, Max Sell, Cooldown Limit. function getTxSettings() public view returns(uint buyMaxTx, uint sellMaxTx, uint txcooldown) { return (txSettings.buyMaxTx, txSettings.sellMaxTx, txSettings.txcooldown); } // Check Buy Limit During A Cooldown (used in _transfer) function checkBuyTxLimit(address _sender, uint256 _amount) internal view { require( exclueFromMaxTx[_sender] == true || txSettings.buys[_sender].add(_amount) < txSettings.buyMaxTx, "Buy transaction limit reached!" ); } // Check Sell Limit During A Cooldown (used in _transfer) function checkSellTxLimit(address _sender, uint256 _amount) internal view { require( exclueFromMaxTx[_sender] == true || txSettings.sells[_sender].add(_amount) < txSettings.sellMaxTx, "Sell transaction limit reached!" ); } // Saves the recent buys & sells during a cooldown (used in _transfer) function setRecentTx(bool _isSell, address _sender, uint _amount) internal { if(txSettings.lastTx[_sender].add(txSettings.txcooldown) < block.timestamp) { _isSell ? txSettings.sells[_sender] = _amount : txSettings.buys[_sender] = _amount; } else { _isSell ? txSettings.sells[_sender] += _amount : txSettings.buys[_sender] += _amount; } txSettings.lastTx[_sender] = block.timestamp; } // Get the recent buys, sells, and the last transaction function getRecentTx(address _address) public view returns(uint buys, uint sells, uint lastTx) { return (txSettings.buys[_address], txSettings.sells[_address], txSettings.lastTx[_address]); } // Get $DEWO Token Price In BNB function getTokenPrice(uint _amount) public view returns(uint) { IPancakeswapV2Pair pcsPair = IPancakeswapV2Pair(pair); IERC20 token1 = IERC20(pcsPair.token1()); (uint Res0, uint Res1,) = pcsPair.getReserves(); uint res0 = Res0*(10**token1.decimals()); return((_amount.mul(res0)).div(Res1)); } /** * @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; } function decimals() public view virtual override returns (uint8) { return _decimals; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @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, allowance(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 = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** @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 += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] -= amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @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 taxes, 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"); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); uint marketingFee; uint developmentFee; uint coreteamFee; uint daoandfarmingFee; uint taxDiscount; bool hasTaxes = true; // Buys from PancakeSwap's $DEWO pool if(from == pair) { checkBuyTxLimit(to, amount); setRecentTx(false, to, amount); marketingFee = txTaxes["marketingBuyTax"]; developmentFee = txTaxes["developmentBuyTax"]; coreteamFee = txTaxes["coreteamBuyTax"]; daoandfarmingFee = txTaxes["daoandfarmingBuyTax"]; // Transaction Tax Tiers 2 & 3 - Discounted Rate if(amount >= taxTiers[0].amount && amount < taxTiers[1].amount) { taxDiscount = taxTiers[0].taxDiscount; } else if(amount >= taxTiers[1].amount) { taxDiscount = taxTiers[1].taxDiscount; } } // Sells from PancakeSwap's $DEWO pool else if(to == pair) { checkSellTxLimit(from, amount); setRecentTx(true, from, amount); marketingFee = txTaxes["marketingSellTax"]; developmentFee = txTaxes["developmentSellTax"]; coreteamFee = txTaxes["coreteamSellTax"]; daoandfarmingFee = txTaxes["daoandfarmingSellTax"]; // Calculate the balance after this transaction uint newBalanceAmount = fromBalance.sub(amount); // Transaction Tax Tiers 2 & 3 - Discounted Rate if(newBalanceAmount >= taxTiers[2].amount && newBalanceAmount < taxTiers[3].amount) { taxDiscount = taxTiers[2].taxDiscount; } else if(newBalanceAmount >= taxTiers[3].amount) { taxDiscount = taxTiers[3].taxDiscount; } } unchecked { _balances[from] = fromBalance - amount; } if(excludeFromTax[to] || excludeFromTax[from]) { hasTaxes = false; } // Calculate taxes if this wallet is not excluded and buys/sells from $DEWO's PCS pair pool if(hasTaxes && (to == pair || from == pair)) { DEWOTokenTax memory DEWOTokenTaxes; DEWOTokenTaxes.forDAOAndFarming = amount.mul(daoandfarmingFee).mul(100 - taxDiscount).div(10000); DEWOTokenTaxes.forDevelopment = amount.mul(developmentFee).mul(100 - taxDiscount).div(10000); DEWOTokenTaxes.forCoreTeam = amount.mul(coreteamFee).mul(100 - taxDiscount).div(10000); DEWOTokenTaxes.forMarketing = amount.mul(marketingFee).mul(100 - taxDiscount).div(10000); // Calculate total taxes and deduct from the transfered amount uint totalTaxes = DEWOTokenTaxes.forDAOAndFarming .add(DEWOTokenTaxes.forDevelopment) .add(DEWOTokenTaxes.forCoreTeam) .add(DEWOTokenTaxes.forMarketing); amount = amount.sub(totalTaxes); // Pay DAO And Farming Taxes _balances[daoandfarmingAddress] += DEWOTokenTaxes.forDAOAndFarming; emit Transfer(from, daoandfarmingAddress, DEWOTokenTaxes.forDAOAndFarming); // Pay Development Fund Taxes _balances[developmentAddress] += DEWOTokenTaxes.forDevelopment; emit Transfer(from, developmentAddress, DEWOTokenTaxes.forDevelopment); // Pay Core-Team Taxes _balances[coreteamAddress] += DEWOTokenTaxes.forCoreTeam; emit Transfer(from, coreteamAddress, DEWOTokenTaxes.forCoreTeam); // Pay Marketing Taxes _balances[marketingAddress] += DEWOTokenTaxes.forMarketing; emit Transfer(from, marketingAddress, DEWOTokenTaxes.forMarketing); } _balances[to] += amount; emit Transfer(from, to, 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 Updates `owner` s allowance for `spender` based on spent `amount`. * * 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); } } } }
Saves the recent buys & sells during a cooldown (used in _transfer)
function setRecentTx(bool _isSell, address _sender, uint _amount) internal { if(txSettings.lastTx[_sender].add(txSettings.txcooldown) < block.timestamp) { _isSell ? txSettings.sells[_sender] = _amount : txSettings.buys[_sender] = _amount; _isSell ? txSettings.sells[_sender] += _amount : txSettings.buys[_sender] += _amount; } txSettings.lastTx[_sender] = block.timestamp; }
14,413,868
// $$\ $$\ $$\ $$\ $$\ $$\ $$\ $$\ $$$$$$$$\ $$$$$$$$\ // $$ | \__| \__| $$ |\__| $$ | $$$\ $$ |$$ _____|\__$$ __| // $$ | $$\ $$$$$$\ $$\ $$\ $$\ $$$$$$$ |$$\ $$$$$$\ $$\ $$\ $$$$\ $$ |$$ | $$ | // $$ | $$ |$$ __$$\ $$ | $$ |$$ |$$ __$$ |$$ |\_$$ _| $$ | $$ | $$ $$\$$ |$$$$$\ $$ | // $$ | $$ |$$ / $$ |$$ | $$ |$$ |$$ / $$ |$$ | $$ | $$ | $$ | $$ \$$$$ |$$ __| $$ | // $$ | $$ |$$ | $$ |$$ | $$ |$$ |$$ | $$ |$$ | $$ |$$\ $$ | $$ | $$ |\$$$ |$$ | $$ | // $$$$$$$$\ $$ |\$$$$$$$ |\$$$$$$ |$$ |\$$$$$$$ |$$ | \$$$$ |\$$$$$$$ | $$ | \$$ |$$ | $$ | // \________|\__| \____$$ | \______/ \__| \_______|\__| \____/ \____$$ | \__| \__|\__| \__| // $$ | $$\ $$ | // $$ | \$$$$$$ | // \__| \______/ // SPDX-License-Identifier: MI pragma solidity 0.8.0; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/metatx/ERC2771ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol"; import "base64-sol/base64.sol"; import "../interfaces/ISvgHelper.sol"; import "../interfaces/IWhiteListPeriodManager.sol"; import "../interfaces/ILiquidityProviders.sol"; import "../../security/Pausable.sol"; import "../structures/LpTokenMetadata.sol"; contract LPToken is OwnableUpgradeable, ReentrancyGuardUpgradeable, ERC721EnumerableUpgradeable, ERC721URIStorageUpgradeable, ERC2771ContextUpgradeable, Pausable { address public liquidityProvidersAddress; IWhiteListPeriodManager public whiteListPeriodManager; mapping(uint256 => LpTokenMetadata) public tokenMetadata; mapping(address => ISvgHelper) public svgHelpers; event LiquidityProvidersUpdated(address indexed lpm); event WhiteListPeriodManagerUpdated(address indexed manager); event SvgHelperUpdated(address indexed tokenAddress, ISvgHelper indexed svgHelper); function initialize( string calldata _name, string calldata _symbol, address _trustedForwarder, address _pauser ) external initializer { __Ownable_init(); __ERC721_init(_name, _symbol); __ERC721Enumerable_init(); __Pausable_init(_pauser); __ERC721URIStorage_init(); __ReentrancyGuard_init(); __ERC2771Context_init(_trustedForwarder); } modifier onlyHyphenPools() { require(_msgSender() == liquidityProvidersAddress, "ERR_UNAUTHORIZED"); _; } function setSvgHelper(address _tokenAddress, ISvgHelper _svgHelper) public onlyOwner { require(_svgHelper != ISvgHelper(address(0)), "ERR_INVALID_SVG_HELPER"); require(_tokenAddress != address(0), "ERR_INVALID_TOKEN_ADDRESS"); svgHelpers[_tokenAddress] = _svgHelper; emit SvgHelperUpdated(_tokenAddress, _svgHelper); } function setLiquidityProviders(address _liquidityProviders) external onlyOwner { require(_liquidityProviders != address(0), "ERR_INVALID_LIQUIDITY_PROVIDERS"); liquidityProvidersAddress = _liquidityProviders; emit LiquidityProvidersUpdated(_liquidityProviders); } function setWhiteListPeriodManager(address _whiteListPeriodManager) external onlyOwner { require(_whiteListPeriodManager != address(0), "ERR_INVALID_WHITELIST_PERIOD_MANAGER"); whiteListPeriodManager = IWhiteListPeriodManager(_whiteListPeriodManager); emit WhiteListPeriodManagerUpdated(_whiteListPeriodManager); } function getAllNftIdsByUser(address _owner) public view returns (uint256[] memory) { uint256[] memory nftIds = new uint256[](balanceOf(_owner)); uint256 length = nftIds.length; for (uint256 i; i < length; ) { nftIds[i] = tokenOfOwnerByIndex(_owner, i); unchecked { ++i; } } return nftIds; } function mint(address _to) external onlyHyphenPools whenNotPaused nonReentrant returns (uint256) { uint256 tokenId = totalSupply() + 1; _safeMint(_to, tokenId); return tokenId; } function updateTokenMetadata(uint256 _tokenId, LpTokenMetadata calldata _lpTokenMetadata) external onlyHyphenPools whenNotPaused { require(_exists(_tokenId), "ERR__TOKEN_DOES_NOT_EXIST"); tokenMetadata[_tokenId] = _lpTokenMetadata; } function exists(uint256 _tokenId) external view returns (bool) { return _exists(_tokenId); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Upgradeable, ERC721EnumerableUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } function tokenURI(uint256 tokenId) public view virtual override(ERC721Upgradeable, ERC721URIStorageUpgradeable) returns (string memory) { address tokenAddress = tokenMetadata[tokenId].token; require(svgHelpers[tokenAddress] != ISvgHelper(address(0)), "ERR__SVG_HELPER_NOT_REGISTERED"); ISvgHelper svgHelper = ISvgHelper(svgHelpers[tokenAddress]); string memory svgData = svgHelper.getTokenSvg( tokenId, tokenMetadata[tokenId].suppliedLiquidity, ILiquidityProviders(liquidityProvidersAddress).totalReserve(tokenAddress) ); string memory description = svgHelper.getDescription( tokenMetadata[tokenId].suppliedLiquidity, ILiquidityProviders(liquidityProvidersAddress).totalReserve(tokenAddress) ); string memory attributes = svgHelper.getAttributes( tokenMetadata[tokenId].suppliedLiquidity, ILiquidityProviders(liquidityProvidersAddress).totalReserve(tokenAddress) ); string memory json = Base64.encode( bytes( string( abi.encodePacked( '{"name": "', name(), '", "description": "', description, '", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(svgData)), '", "attributes": ', attributes, "}" ) ) ) ); return string(abi.encodePacked("data:application/json;base64,", json)); } function _msgSender() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (address) { return ERC2771ContextUpgradeable._msgSender(); } function _msgData() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (bytes calldata) { return ERC2771ContextUpgradeable._msgData(); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721EnumerableUpgradeable, ERC721Upgradeable) whenNotPaused { super._beforeTokenTransfer(from, to, tokenId); // Only call whitelist period manager for NFT Transfers, not mint and burns if (from != address(0) && to != address(0)) { whiteListPeriodManager.beforeLiquidityTransfer( from, to, tokenMetadata[tokenId].token, tokenMetadata[tokenId].suppliedLiquidity ); } } function _burn(uint256 tokenId) internal virtual override(ERC721URIStorageUpgradeable, ERC721Upgradeable) { ERC721URIStorageUpgradeable._burn(tokenId); } }
Only call whitelist period manager for NFT Transfers, not mint and burns
function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721EnumerableUpgradeable, ERC721Upgradeable) whenNotPaused { super._beforeTokenTransfer(from, to, tokenId); if (from != address(0) && to != address(0)) { whiteListPeriodManager.beforeLiquidityTransfer( from, to, tokenMetadata[tokenId].token, tokenMetadata[tokenId].suppliedLiquidity ); } }
13,116,767
pragma solidity ^0.4.18; // File: contracts/LikeCoinInterface.sol // Copyright (C) 2017 LikeCoin Foundation Limited // // This file is part of LikeCoin Smart Contract. // // LikeCoin Smart Contract 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. // // LikeCoin Smart Contract 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 LikeCoin Smart Contract. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.4.18; contract LikeCoinInterface { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); } // File: contracts/Ownable.sol contract Ownable { address public owner; address public pendingOwner; address public operator; 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 Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } modifier ownerOrOperator { require(msg.sender == owner || msg.sender == operator); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } function setOperator(address _operator) onlyOwner public { operator = _operator; } } // File: contracts/ArtMuseumBase.sol contract ArtMuseumBase is Ownable { struct Artwork { uint8 artworkType; uint32 sequenceNumber; uint128 value; address player; } LikeCoinInterface public like; /** array holding ids mapping of the curret artworks*/ uint32[] public ids; /** the last sequence id to be given to the link artwork **/ uint32 public lastId; /** the id of the oldest artwork */ uint32 public oldest; /** the artwork belonging to a given id */ mapping(uint32 => Artwork) artworks; /** the user purchase sequence number per each artwork type */ mapping(address=>mapping(uint8 => uint32)) userArtworkSequenceNumber; /** the cost of each artwork type */ uint128[] public costs; /** the value of each artwork type (cost - fee), so it's not necessary to compute it each time*/ uint128[] public values; /** the fee to be paid each time an artwork is bought in percent*/ uint8 public fee; /** total number of artworks in the game (uint32 because of multiplication issues) */ uint32 public numArtworks; /** The maximum of artworks allowed in the game */ uint16 public maxArtworks; /** number of artworks per type */ uint32[] numArtworksXType; /** initializes the contract parameters */ function init(address _likeAddr) public onlyOwner { require(like==address(0)); like = LikeCoinInterface(_likeAddr); costs = [800 ether, 2000 ether, 5000 ether, 12000 ether, 25000 ether]; setFee(5); maxArtworks = 1000; lastId = 1; oldest = 0; } function deposit() payable public { } function withdrawBalance() public onlyOwner returns(bool res) { owner.transfer(address(this).balance); return true; } /** * allows the owner to collect the accumulated fees * sends the given amount to the owner's address if the amount does not exceed the * fees (cannot touch the players' balances) * */ function collectFees(uint128 amount) public onlyOwner { uint collectedFees = getFees(); if (amount <= collectedFees) { like.transfer(owner,amount); } } function getArtwork(uint32 artworkId) public constant returns(uint8 artworkType, uint32 sequenceNumber, uint128 value, address player) { return (artworks[artworkId].artworkType, artworks[artworkId].sequenceNumber, artworks[artworkId].value, artworks[artworkId].player); } function getAllArtworks() public constant returns(uint32[] artworkIds,uint8[] types,uint32[] sequenceNumbers, uint128[] artworkValues) { uint32 id; artworkIds = new uint32[](numArtworks); types = new uint8[](numArtworks); sequenceNumbers = new uint32[](numArtworks); artworkValues = new uint128[](numArtworks); for (uint16 i = 0; i < numArtworks; i++) { id = ids[i]; artworkIds[i] = id; types[i] = artworks[id].artworkType; sequenceNumbers[i] = artworks[id].sequenceNumber; artworkValues[i] = artworks[id].value; } } function getAllArtworksByOwner() public constant returns(uint32[] artworkIds,uint8[] types,uint32[] sequenceNumbers, uint128[] artworkValues) { uint32 id; uint16 j = 0; uint16 howmany = 0; address player = address(msg.sender); for (uint16 k = 0; k < numArtworks; k++) { if (artworks[ids[k]].player == player) howmany++; } artworkIds = new uint32[](howmany); types = new uint8[](howmany); sequenceNumbers = new uint32[](howmany); artworkValues = new uint128[](howmany); for (uint16 i = 0; i < numArtworks; i++) { if (artworks[ids[i]].player == player) { id = ids[i]; artworkIds[j] = id; types[j] = artworks[id].artworkType; sequenceNumbers[j] = artworks[id].sequenceNumber; artworkValues[j] = artworks[id].value; j++; } } } function setCosts(uint128[] _costs) public onlyOwner { require(_costs.length >= costs.length); costs = _costs; setFee(fee); } function setFee(uint8 _fee) public onlyOwner { fee = _fee; for (uint8 i = 0; i < costs.length; i++) { if (i < values.length) values[i] = costs[i] - costs[i] / 100 * fee; else { values.push(costs[i] - costs[i] / 100 * fee); numArtworksXType.push(0); } } } function getFees() public constant returns(uint) { uint reserved = 0; for (uint16 j = 0; j < numArtworks; j++) reserved += artworks[ids[j]].value; return like.balanceOf(this) - reserved; } } // File: contracts/oraclizeAPI.sol // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary pragma solidity ^0.4.20;//<=0.4.20;// Incompatible compiler version... please select one stated within pragma solidity or use different oraclizeAPI version contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function randomDS_getSessionPubKeyHash() external constant returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() public returns (address _addr); } contract usingOraclize { // is ArtMuseumBase { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; string oraclize_network_name; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ return oraclize_setNetwork(); networkID; // silence the warning and remain backwards compatible } function oraclize_setNetwork() internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } // parseInt function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string) { return oraclize_network_name; } } // File: contracts/strings.sol /* * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <[email protected]> * * @dev Functionality in this library is largely implemented using an * abstraction called a 'slice'. A slice represents a part of a string - * anything from the entire string to a single character, or even no * characters at all (a 0-length slice). Since a slice only has to specify * an offset and a length, copying and manipulating slices is a lot less * expensive than copying and manipulating the strings they reference. * * To further reduce gas costs, most functions on slice that need to return * a slice modify the original one instead of allocating a new one; for * instance, `s.split(".")` will return the text up to the first '.', * modifying s to only contain the remainder of the string after the '.'. * In situations where you do not want to modify the original slice, you * can make a copy first with `.copy()`, for example: * `s.copy().split(".")`. Try and avoid using this idiom in loops; since * Solidity has no memory management, it will result in allocating many * short-lived slices that are later discarded. * * Functions that return two slices come in two versions: a non-allocating * version that takes the second slice as an argument, modifying it in * place, and an allocating version that allocates and returns the second * slice; see `nextRune` for example. * * Functions that have to copy string data will return strings rather than * slices; these can be cast back to slices for further processing if * required. * * For convenience, some functions are provided with non-modifying * variants that create a new slice and return both; for instance, * `s.splitNew('.')` leaves s unmodified, and returns two values * corresponding to the left and right parts of the string. */ pragma solidity ^0.4.14; library strings { struct slice { uint _len; uint _ptr; } function memcpy(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string self) internal pure returns (slice) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice's text. */ function toString(slice self) internal pure returns (string) { string memory ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr = selfptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } uint end = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr >= end) return selfptr + selflen; ptr++; assembly { ptrdata := and(mload(ptr), mask) } } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice self, slice needle, slice token) internal pure returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice self, slice needle) internal pure returns (slice token) { split(self, needle, token); } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice self, slice needle) internal pure returns (uint cnt) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { cnt++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } } // File: contracts/ArtMuseumV1.sol contract ArtMuseumV1 is ArtMuseumBase, usingOraclize { //using Strings for string; using strings for *; /** num of times oldest artwork get bonus **/ uint32 public lastcombo; /** last stolen at block number in blockchain **/ uint public lastStealBlockNumber; /** oldest artwork extra steal probability **/ uint8[] public oldestExtraStealProbability; /** the query string getting the random numbers from oraclize**/ string randomQuery; /** the type of the oraclize query**/ string queryType; /** the timestamp of the next attack **/ uint public nextStealTimestamp; /** gas provided for oraclize callback (attack)**/ uint32 public oraclizeGas; /** gas provided for oraclize callback calculate by extra artworks fund likecoin (attack)**/ uint32 public oraclizeGasExtraArtwork; /** the id of the next oraclize callback**/ uint32 public etherExchangeLikeCoin; /** the id of oraclize callback**/ bytes32 nextStealId; /** total number of times steal per day **/ uint8 public numOfTimesSteal; /** accumulate ether fee for trigger next steal include oraclize fee and trigger gas fee **/ uint public oraclizeFee; /** is fired when new artworks are purchased (who bought how many artworks of which type?) */ event newPurchase(address player, uint32 startId, uint8[] artworkTypes, uint32[] startSequenceNumbers); /** is fired when an steal occures */ event newSteal(uint timestamp,uint32[] stolenArtworks,uint8[] artworkTypes,uint32[] sequenceNumbers, uint256[] values,address[] players); /** is fired when an steal occures */ event newStealRewards(uint128 total,uint128[] values); /** is fired when a single artwork is sold **/ event newSell(uint32[] artworkId, address player, uint256 value); /** trigger oraclize **/ event newTriggerOraclize(bytes32 nextStealId, uint waittime, uint gasAmount, uint price, uint balancebefore, uint balance); /** oraclize callback **/ event newOraclizeCallback(bytes32 nextStealId, string result, uint32 killed, uint128 killedValue, uint128 distValue,uint oraclizeFee,uint gaslimit,uint exchange); function initOraclize() public onlyOwner { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(); } function init1() public onlyOwner { randomQuery = "10 random numbers between 1 and 100000"; queryType = "WolframAlpha"; oraclizeGas = 150000; oraclizeGasExtraArtwork = 14000; etherExchangeLikeCoin = 100000; oldestExtraStealProbability = [3,5,10,15,30,50]; numOfTimesSteal = 1; } /** * buy artworks when likecoin transfer callback * */ function giveArtworks(uint8[] artworkTypes, address receiver, uint256 _value) internal { uint32 len = uint32(artworkTypes.length); require(numArtworks + len < maxArtworks); uint256 amount = 0; for (uint16 i = 0; i < len; i++) { require(artworkTypes[i] < costs.length); amount += costs[artworkTypes[i]]; } require(_value >= amount); uint8 artworkType; uint32[] memory seqnolist = new uint32[](len); for (uint16 j = 0; j < len; j++) { if (numArtworks < ids.length) ids[numArtworks] = lastId; else ids.push(lastId); artworkType = artworkTypes[j]; userArtworkSequenceNumber[receiver][artworkType]++; seqnolist[j] = userArtworkSequenceNumber[receiver][artworkType]; artworks[lastId] = Artwork(artworkTypes[j], userArtworkSequenceNumber[receiver][artworkType], values[artworkType], receiver); numArtworks++; lastId++; numArtworksXType[artworkType]++; } // tryAutoTriggerSteal(); emit newPurchase(receiver, lastId - len, artworkTypes, seqnolist); } /** * Replaces the artwork with the given id with the last artwork in the array * */ function replaceArtwork(uint16 index) internal { uint32 artworkId = ids[index]; numArtworksXType[artworks[artworkId].artworkType]--; numArtworks--; if (artworkId == oldest) oldest = 0; delete artworks[artworkId]; if (numArtworks>0) ids[index] = ids[numArtworks]; delete ids[numArtworks]; ids.length = numArtworks; } /** * get the oldest artwork * */ function getOldest() public constant returns(uint32 artworkId,uint8 artworkType, uint32 sequenceNumber, uint128 value, address player) { if (numArtworks==0) artworkId = 0; else { artworkId = oldest; if (artworkId==0) { artworkId = ids[0]; for (uint16 i = 1; i < numArtworks; i++) { if (ids[i] < artworkId) //the oldest artwork has the lowest id artworkId = ids[i]; } } artworkType = artworks[artworkId].artworkType; sequenceNumber = artworks[artworkId].sequenceNumber; value = artworks[artworkId].value; player = artworks[artworkId].player; } } /** * set the oldest artwork when steal * */ function setOldest() internal returns(uint32 artworkId,uint16 index) { if (numArtworks==0) artworkId = 0; else { if (oldest==0) { oldest = ids[0]; index = 0; for (uint16 i = 1; i < numArtworks; i++) { if (ids[i] < oldest) { //the oldest artwork has the lowest id oldest = ids[i]; index = i; } } } else { for (uint16 j = 0; j < numArtworks; j++) { if (ids[j] == oldest) { index = j; break; } } } artworkId = oldest; } } /** * sell the artwork of the given id * */ function sellArtwork(uint32 artworkId) public { require(msg.sender == artworks[artworkId].player); uint256 val = uint256(artworks[artworkId].value);// - sellfee; uint16 artworkIndex; bool found = false; for (uint16 i = 0; i < numArtworks; i++) { if (ids[i] == artworkId) { artworkIndex = i; found = true; break; } } require(found == true); replaceArtwork(artworkIndex); if (val>0) like.transfer(msg.sender,val); uint32[] memory artworkIds = new uint32[](1); artworkIds[0] = artworkId; // tryAutoTriggerSteal(); // ids.length = numArtworks; emit newSell(artworkIds, msg.sender, val); } /** * manually triggers the steal * */ function triggerStealManually(uint32 inseconds) public payable ownerOrOperator { require((nextStealTimestamp) < now); // avoid two scheduled callback, asssume max 5mins wait to callback when trigger triggerSteal(inseconds, (oraclizeGas + oraclizeGasExtraArtwork * numArtworks)); } /** * the frequency of the thief steal depends on the number of artworks in the game. * many artworks -> many thief steal * */ function timeTillNextSteal() constant internal returns(uint32) { return (86400 / (1 + numArtworks / 100)) / ( numOfTimesSteal ); } /** * sends a query to oraclize in order to get random numbers in 'inseconds' seconds */ function triggerSteal(uint32 inseconds, uint gasAmount) internal { // Check if we have enough remaining funds uint gaslimit = gasleft(); uint price = oraclize_getPrice(queryType, gasAmount); uint balancebefore = address(this).balance; require(price <= address(this).balance); if (numArtworks<=1) { removeArtworksByString("",0); distribute(0); nextStealId = 0x0; price = 0; } else { nextStealId = oraclize_query(nextStealTimestamp, queryType, randomQuery, gasAmount); } emit newTriggerOraclize(nextStealId, inseconds, gasAmount, price, balancebefore, address(this).balance); oraclizeFee = price + (gaslimit-gasleft() + 200000 /*add gas overhead*/) * tx.gasprice; } /** * convert a random number to index of artworks list * */ function findIndexFromRandomNumber(uint32 randomNumbers) internal returns (uint32 artworkId, uint16 index) { uint16 indexOldest; uint maxNumber; uint8 extraProbability; if (oldest==0) lastcombo = 0; (artworkId,indexOldest) = setOldest(); if (lastcombo>oldestExtraStealProbability.length-1) extraProbability = oldestExtraStealProbability[oldestExtraStealProbability.length-1]; else extraProbability = oldestExtraStealProbability[lastcombo]; maxNumber = 100000 - extraProbability*1000; if (extraProbability>0 && randomNumbers>maxNumber) { index = indexOldest; artworkId = oldest; } else { index = mapToNewRange(randomNumbers, numArtworks, maxNumber); artworkId = ids[index]; } } /** * remove artwork by random number (a string, number list) * */ function removeArtworksByString(string result,uint32 howmany) internal returns (uint128 pot) { uint32[] memory stolenArtworks = new uint32[](howmany); uint8[] memory artworkTypes = new uint8[](howmany); uint32[] memory sequenceNumbers = new uint32[](howmany); uint256[] memory artworkValues = new uint256[](howmany); address[] memory players = new address[](howmany); if (howmany>0) { uint32[] memory randomNumbers = getNumbersFromString(result, ",", howmany); uint16 index; uint32 artworkId; Artwork memory artworkData; pot = 0; if (oldest!=0) lastcombo++; for (uint32 i = 0; i < howmany; i++) { (artworkId,index) = findIndexFromRandomNumber(randomNumbers[i]); artworkData = artworks[artworkId]; pot += artworkData.value; stolenArtworks[i] = artworkId; artworkTypes[i] = artworkData.artworkType; sequenceNumbers[i] = artworkData.sequenceNumber; artworkValues[i] = artworkData.value; players[i] = artworkData.player; replaceArtwork(index); } } else { pot = 0; } emit newSteal(now,stolenArtworks,artworkTypes,sequenceNumbers,artworkValues,players); } /** * oraclize call back * */ function __callback(bytes32 myid, string result) public { uint gaslimit = gasleft(); uint32 howmany; uint128 pot; uint gasCost; uint128 distpot; uint oraclizeFeeTmp = 0; // for event log if (msg.sender == oraclize_cbAddress() && myid == nextStealId) { howmany = numArtworks < 100 ? (numArtworks < 10 ? (numArtworks < 2 ? 0 : 1) : numArtworks / 10) : 10; //do not kill more than 10%, but at least one pot = removeArtworksByString(result,howmany); gasCost = ((oraclizeFee * etherExchangeLikeCoin) / 1 ether) * 1 ether + 1 ether/* not floor() */; if (pot > gasCost) distpot = uint128(pot - gasCost); distribute(distpot); //distribute the pot minus the oraclize gas costs oraclizeFeeTmp = oraclizeFee; oraclizeFee = 0; } emit newOraclizeCallback(myid,result,howmany,pot,distpot,oraclizeFeeTmp,gaslimit,etherExchangeLikeCoin); } /** * change next steal time * */ function updateNextStealTime(uint32 inseconds) internal { nextStealTimestamp = now + inseconds; } /** distributes the given amount among the surviving artworks*/ function distribute(uint128 totalAmount) internal { uint32 artworkId; uint128 amount = ( totalAmount * 60 ) / 100; uint128 valueSum = 0; uint128 totalAmountRemain = totalAmount; uint128[] memory shares = new uint128[](values.length+1); if (totalAmount>0) { //distribute the rest according to their type for (uint8 v = 0; v < values.length; v++) { if (numArtworksXType[v] > 0) valueSum += values[v]; } for (uint8 m = 0; m < values.length; m++) { if (numArtworksXType[m] > 0) shares[m] = ((amount * (values[m] * 1000 / valueSum) / numArtworksXType[m]) / (1000 ether)) * (1 ether); } for (uint16 i = 0; i < numArtworks; i++) { artworkId = ids[i]; amount = shares[artworks[artworkId].artworkType]; artworks[artworkId].value += amount; totalAmountRemain -= amount; } setOldest(); artworks[oldest].value += totalAmountRemain; shares[shares.length-1] = totalAmountRemain; } lastStealBlockNumber = block.number; updateNextStealTime(timeTillNextSteal()); emit newStealRewards(totalAmount,shares); } /****************** GETTERS *************************/ function getNumArtworksXType() public constant returns(uint32[] _numArtworksXType) { _numArtworksXType = numArtworksXType; } function get30Artworks(uint16 startIndex) public constant returns(uint32[] artworkIds,uint8[] types,uint32[] sequenceNumbers, uint128[] artworkValues,address[] players) { uint32 endIndex = startIndex + 30 > numArtworks ? numArtworks : startIndex + 30; uint32 id; uint32 num = endIndex - startIndex; artworkIds = new uint32[](num); types = new uint8[](num); sequenceNumbers = new uint32[](num); artworkValues = new uint128[](num); players = new address[](num); uint16 j = 0; for (uint16 i = startIndex; i < endIndex; i++) { id = ids[i]; artworkIds[j] = id; types[j] = artworks[id].artworkType; sequenceNumbers[j] = artworks[id].sequenceNumber; artworkValues[j] = artworks[id].value; players[j] = artworks[id].player; j++; } } function getRemainTime() public constant returns(uint remainTime) { if (nextStealTimestamp>now) remainTime = nextStealTimestamp - now; } /****************** SETTERS *************************/ function setCustomGasPrice(uint gasPrice) public ownerOrOperator { oraclize_setCustomGasPrice(gasPrice); } function setOraclizeGas(uint32 newGas) public ownerOrOperator { oraclizeGas = newGas; } function setOraclizeGasExtraArtwork(uint32 newGas) public ownerOrOperator { oraclizeGasExtraArtwork = newGas; } function setEtherExchangeLikeCoin(uint32 newValue) public ownerOrOperator { etherExchangeLikeCoin = newValue; } function setMaxArtworks(uint16 number) public ownerOrOperator { maxArtworks = number; } function setNumOfTimesSteal(uint8 adjust) public ownerOrOperator { numOfTimesSteal = adjust; } function updateNextStealTimeByOperator(uint32 inseconds) public ownerOrOperator { nextStealTimestamp = now + inseconds; } /************* HELPERS ****************/ /** * maps a given number to the new range (old range 100000) * */ function mapToNewRange(uint number, uint range, uint max) pure internal returns(uint16 randomNumber) { return uint16(number * range / max); } /** * converts a string of numbers being separated by a given delimiter into an array of numbers (#howmany) */ function getNumbersFromString(string s, string delimiter, uint32 howmany) public pure returns(uint32[] numbers) { var s2 = s.toSlice(); var delim = delimiter.toSlice(); string[] memory parts = new string[](s2.count(delim) + 1); for(uint8 i = 0; i < parts.length; i++) { parts[i] = s2.split(delim).toString(); } numbers = new uint32[](howmany); if (howmany>parts.length) howmany = uint32(parts.length); for (uint8 j = 0; j < howmany; j++) { numbers[j] = uint32(parseInt(parts[j])); } return numbers; } /** * likecoin transfer callback */ function tokenCallback(address _from, uint256 _value, bytes _data) public { require(msg.sender == address(like)); uint[] memory result; uint len; assembly { len := mload(_data) let c := 0 result := mload(0x40) for { let i := 0 } lt(i, len) { i := add(i, 0x20) } { mstore(add(result, add(i, 0x20)), mload(add(_data, add(i, 0x20)))) c := add(c, 1) } mstore(result, c) mstore(0x40, add(result , add(0x20, mul(c, 0x20)))) } uint8[] memory result2 = new uint8[](result.length); for (uint16 j=0;j<result.length; j++) { result2[j] = uint8(result[j]); } giveArtworks(result2, _from, _value); } } // File: contracts/ArtMuseumV2.sol contract ArtMuseumV2 is ArtMuseumV1 { function triggerStealManually2(string result) public payable ownerOrOperator { uint gaslimit = gasleft(); oraclizeFee = (gaslimit + 200000 /*add gas overhead*/) * tx.gasprice + oraclizeFee; require(nextStealTimestamp < now); // avoid two scheduled callback, asssume max 5mins wait to callback when trigger uint32 howmany; uint128 pot; uint gasCost; uint128 distpot; uint oraclizeFeeTmp = 0; // for event log if (numArtworks<=1) { removeArtworksByString("",0); distribute(0); oraclizeFeeTmp = oraclizeFee; } else { howmany = numArtworks < 100 ? (numArtworks < 10 ? (numArtworks < 2 ? 0 : 1) : numArtworks / 10) : 10; //do not kill more than 10%, but at least one pot = removeArtworksByString(result,howmany); gasCost = ((oraclizeFee * etherExchangeLikeCoin) / 1 ether) * 1 ether + 1 ether/* not floor() */; if (pot > gasCost) distpot = uint128(pot - gasCost); distribute(distpot); //distribute the pot minus the oraclize gas costs oraclizeFeeTmp = oraclizeFee; oraclizeFee = 0; } emit newOraclizeCallback(0x0,result,howmany,pot,distpot,oraclizeFeeTmp,gaslimit,etherExchangeLikeCoin); } }
Replaces the artwork with the given id with the last artwork in the array /
function replaceArtwork(uint16 index) internal { uint32 artworkId = ids[index]; numArtworksXType[artworks[artworkId].artworkType]--; numArtworks--; if (artworkId == oldest) oldest = 0; delete artworks[artworkId]; if (numArtworks>0) ids[index] = ids[numArtworks]; delete ids[numArtworks]; ids.length = numArtworks; }
1,732,508
./partial_match/1/0x8AFe36A34C12bb7DAa4f83CCa57760f1d4900736/sources/TradeBotCommanderV1Staging.sol
Initialize contract by setting transaction submitter as initial owner./
function processLimitOrder( LimitOrderArguments calldata args, LimitOrderExecutionArguments calldata executionArgs ) external returns (uint256 amountReceived); } } constructor() internal { _owner = tx.origin; emit OwnershipTransferred(address(0), _owner); }
4,024,636
// SPDX-License-Identifier: MIT //in process pragma solidity 0.7.0; contract DayFour2019 { uint256[] pwordOptions; uint256[6] digitOptions; uint256 constant MIN = 123257; uint256 constant MAX = 647015; mapping (uint256 => bool) pass; constructor() {} //test each digit of six-number array function digits(uint256 _numCheck) private { require(digitOptions[0] >= 1 && digitOptions[0] <= 6); require(digitOptions[0] == digitOptions[1] | digitOptions[1] == digitOptions[2] | digitOptions[2] == digitOptions[3] | digitOptions[3] == digitOptions[4] | digitOptions[4] == digitOptions[5]); pass[_numCheck] = true; } //concatenate six-digit number function createNum() public { for(uint256 x = 0; x < 9; x++) { digits(x); } } //test each full six-digit number function test(uint256 num) public { require(pwordOptions[] > MIN); require(pwordOptions[] < MAX); } }
concatenate six-digit number
function createNum() public { for(uint256 x = 0; x < 9; x++) { digits(x); } }
13,128,279
./partial_match/1/0xca63f155EaD7b40e2E67Dc5f7E8cA50BFB283FD0/sources/contracts/libraries/UniswapV2.sol
Uniswap v2 pair interface
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); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function router() external returns (address); pragma solidity ^0.8.7; }
16,172,230
// SPDX-License-Identifier: MIT pragma solidity ^0.8.8; import {StorageSlot} from "@openzeppelin/contracts/utils/StorageSlot.sol"; import {ProxyInitialization} from "./ProxyInitialization.sol"; library ProxyAdminStorage { using ProxyAdminStorage for ProxyAdminStorage.Layout; struct Layout { address admin; } // bytes32 public constant PROXYADMIN_STORAGE_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; bytes32 internal constant LAYOUT_STORAGE_SLOT = bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1); bytes32 internal constant PROXY_INIT_PHASE_SLOT = bytes32(uint256(keccak256("eip1967.proxy.admin.phase")) - 1); event AdminChanged(address previousAdmin, address newAdmin); /// @notice Initializes the storage with an initial admin (immutable version). /// @dev Note: This function should be called ONLY in the constructor of an immutable (non-proxied) contract. /// @dev Reverts if `initialAdmin` is the zero address. /// @dev Emits an {AdminChanged} event. /// @param initialAdmin The initial payout wallet. function constructorInit(Layout storage s, address initialAdmin) internal { // assert(PROXYADMIN_STORAGE_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); require(initialAdmin != address(0), "ProxyAdmin: no initial admin"); s.admin = initialAdmin; emit AdminChanged(address(0), initialAdmin); } /// @notice Initializes the storage with an initial admin (proxied version). /// @notice Sets the proxy initialization phase to `1`. /// @dev Note: This function should be called ONLY in the init function of a proxied contract. /// @dev Reverts if the proxy initialization phase is set to `1` or above. /// @dev Reverts if `initialAdmin` is the zero address. /// @dev Emits an {AdminChanged} event. /// @param initialAdmin The initial payout wallet. function proxyInit(Layout storage s, address initialAdmin) internal { ProxyInitialization.setPhase(PROXY_INIT_PHASE_SLOT, 1); s.constructorInit(initialAdmin); } /// @notice Sets a new proxy admin. /// @dev Reverts if `sender` is not the proxy admin. /// @dev Emits an {AdminChanged} event if `newAdmin` is different from the current proxy admin. /// @param newAdmin The new proxy admin. function changeProxyAdmin( Layout storage s, address sender, address newAdmin ) internal { address previousAdmin = s.admin; require(sender == previousAdmin, "ProxyAdmin: not the admin"); if (previousAdmin != newAdmin) { s.admin = newAdmin; emit AdminChanged(previousAdmin, newAdmin); } } /// @notice Gets the proxy admin. /// @return admin The proxy admin function proxyAdmin(Layout storage s) internal view returns (address admin) { return s.admin; } /// @notice Ensures that an account is the proxy admin. /// @dev Reverts if `account` is not the proxy admin. /// @param account The account. function enforceIsProxyAdmin(Layout storage s, address account) internal view { require(account == s.admin, "ProxyAdmin: not the admin"); } function layout() internal pure returns (Layout storage s) { bytes32 position = LAYOUT_STORAGE_SLOT; assembly { s.slot := position } } }
Initializes the storage with an initial admin (immutable version). Note: This function should be called ONLY in the constructor of an immutable (non-proxied) contract. Reverts if `initialAdmin` is the zero address. Emits an {AdminChanged} event. initialAdmin The initial payout wallet. assert(PROXYADMIN_STORAGE_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
function constructorInit(Layout storage s, address initialAdmin) internal { require(initialAdmin != address(0), "ProxyAdmin: no initial admin"); s.admin = initialAdmin; emit AdminChanged(address(0), initialAdmin); }
7,219,028
./full_match/1/0x9965cCd16803432C6a0842f1D5690f32E427aEDd/sources/contracts/LiveMintTokyo.sol
Returns An Array Of Unminted Golden Tokens/
function readCitizenUnmintedTicketIDs() public view returns(uint[] memory) { uint[] memory UnmintedTokenIDs = new uint[](1000); uint Counter; uint CityIDBuffer = _CurrentCityIndex % 6 * 333; uint _TokenID; for(uint TokenID; TokenID < 1000; TokenID++) { _TokenID = TokenID + CityIDBuffer; if ( !_MintedCitizen[_CurrentCityIndex][_TokenID] && _BrightListCitizen[_CurrentCityIndex][_TokenID] != address(0) ) { UnmintedTokenIDs[Counter] = _TokenID; Counter++; } } uint[] memory FormattedUnMintedTokenIDs = new uint[](Counter); uint Found; for(uint FormattedTokenID; FormattedTokenID < Counter; FormattedTokenID++) { if(UnmintedTokenIDs[FormattedTokenID] != 0 || (UnmintedTokenIDs[FormattedTokenID] == 0 && FormattedTokenID == 0)) { FormattedUnMintedTokenIDs[Found] = UnmintedTokenIDs[FormattedTokenID]; Found++; } } return FormattedUnMintedTokenIDs; }
8,470,958
import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; // File: contracts/RealioLPStaking.sol pragma solidity 0.6.12; // Realio LP Staking - honeypot contract allows users to earn RIO for holding liquidity on Uniswap. // // // Note that it's ownable and the honeypot once funded, can never be touched // // User deposits LP tokens into Pool for RIO rewards // RIO rewards recalculated at each deposit or withdrawal // // contract RealioLPStaking is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. // // rewardDebt is the accumulation of the user's estimated shares since the last harvest. // // reward: any point in time, the amount of RIOs entitled to a user but is pending to be distributed is // // pending reward = (user.amount * pool.accRioPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accRioPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 perBlockRioAllocated; // Number of RIO to distribute per block. uint256 lastRewardBlock; // Last block number that RIOs distribution occurs. uint256 accRioPerShare; // Accumulated RIOs per share, times 1e12. See below. } // Address of RIO token contract. IERC20 public rioTokenContract; // RIO tokens created per block. uint256 public rioRewardPerBlock; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocRioPerBlock = 0; // The block number when RIO mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event ContractFunded(address indexed from, uint256 amount); constructor( IERC20 _rioContractAddress, uint256 _rioPerBlock, uint256 _startBlock ) public { rioTokenContract = _rioContractAddress; rioRewardPerBlock = _rioPerBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } ////////////////// // // OWNER functions // ////////////////// // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _rioPerBlock, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocRioPerBlock = totalAllocRioPerBlock.add(_rioPerBlock); poolInfo.push(PoolInfo({ lpToken: _lpToken, perBlockRioAllocated: _rioPerBlock, lastRewardBlock: lastRewardBlock, accRioPerShare: 0 })); } // Update the given pool's RIO per block. Can only be called by the owner. function set(uint256 _poolId, uint256 _rioPerBlock, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocRioPerBlock = totalAllocRioPerBlock.sub(poolInfo[_poolId].perBlockRioAllocated).add(_rioPerBlock); poolInfo[_poolId].perBlockRioAllocated = _rioPerBlock; } // fund the contract with RIO. _from address must have approval to execute Rio Token Contract transferFrom function fund(address _from, uint256 _amount) public { require(_from != address(0), 'fund: must pass valid _from address'); require(_amount > 0, 'fund: expecting a positive non zero _amount value'); require(rioTokenContract.balanceOf(_from) >= _amount, 'fund: expected an address that contains enough RIO for Transfer'); rioTokenContract.transferFrom(_from, address(this), _amount); emit ContractFunded(_from, _amount); } ////////////////// // // VIEW functions // ////////////////// // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) { return _to.sub(_from); } // View function to see pending RIOs on frontend. // (user.amount * pool.accRioPerShare) - rewardDebt function pendingRioReward(uint256 _poolId, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_poolId]; UserInfo storage user = userInfo[_poolId][_user]; uint256 accRioPerShare = pool.accRioPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply < 0) { return 0; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 rioReward = multiplier.mul(rioRewardPerBlock).mul(pool.perBlockRioAllocated).div(totalAllocRioPerBlock); accRioPerShare = accRioPerShare.add(rioReward.mul(1e12).div(lpSupply)); return user.amount.mul(accRioPerShare).div(1e12).sub(user.rewardDebt); } // View function to see contract held RIO on frontend. function getLockedRioView() external view returns (uint256) { return rioTokenContract.balanceOf(address(this)); } // View function to see pool held LP Tokens function getLpSupply(uint256 _poolId) external view returns (uint256) { PoolInfo storage pool = poolInfo[_poolId]; return pool.lpToken.balanceOf(address(this)); } ////////////////// // // PUBLIC functions // ////////////////// // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update pool supply and reward variables of the given pool to be up-to-date. function updatePool(uint256 _poolId) public { PoolInfo storage pool = poolInfo[_poolId]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 rioReward = multiplier.mul(rioRewardPerBlock).mul(pool.perBlockRioAllocated).div(totalAllocRioPerBlock); pool.accRioPerShare = pool.accRioPerShare.add(rioReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to Contract for RIO allocation. function deposit(uint256 _poolId, uint256 _amount) public { PoolInfo storage pool = poolInfo[_poolId]; UserInfo storage user = userInfo[_poolId][msg.sender]; updatePool(_poolId); // if user already has LP tokens in the pool execute harvest for the user if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accRioPerShare).div(1e12).sub(user.rewardDebt); safeRioTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accRioPerShare).div(1e12); emit Deposit(msg.sender, _poolId, _amount); } // Withdraw LP tokens from Contract. 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.accRioPerShare).div(1e12).sub(user.rewardDebt); safeRioTransfer(address(msg.sender), pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accRioPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; } ////////////////// // // INTERNAL functions // ////////////////// // Safe RIO transfer function, just in case if rounding error causes pool to not have enough RIOs. function safeRioTransfer(address _to, uint256 _amount) internal { address _from = address(this); uint256 rioBal = rioTokenContract.balanceOf(_from); if (_amount > rioBal) { rioTokenContract.transfer(_to, rioBal); } else { rioTokenContract.transfer(_to, _amount); } } }
View function to see contract held RIO on frontend.
function getLockedRioView() external view returns (uint256) { return rioTokenContract.balanceOf(address(this)); }
12,952,578
/** * The edgeless casino contract v2 holds the players&#39;s funds and provides state channel functionality. * The casino has at no time control over the players&#39;s funds. * State channels can be updated and closed from both parties: the player and the casino. * author: Julia Altenried **/ pragma solidity ^0.4.19; contract SafeMath { function safeSub(uint a, uint b) pure internal returns(uint) { assert(b <= a); return a - b; } function safeSub(int a, int b) pure internal returns(int) { if(b < 0) assert(a - b > a); else assert(a - b <= a); return a - b; } function safeAdd(uint a, uint b) pure internal returns(uint) { uint c = a + b; assert(c >= a && c >= b); return c; } function safeMul(uint a, uint b) pure internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } } contract Token { function transferFrom(address sender, address receiver, uint amount) public returns(bool success) {} function transfer(address receiver, uint amount) public returns(bool success) {} function balanceOf(address holder) public constant returns(uint) {} } contract owned { address public owner; modifier onlyOwner { require(msg.sender == owner); _; } function owned() public{ owner = msg.sender; } } /** owner should be able to close the contract is nobody has been using it for at least 30 days */ contract mortal is owned { /** contract can be closed by the owner anytime after this timestamp if non-zero */ uint public closeAt; /** the edgeless token contract */ Token edg; function mortal(address tokenContract) internal{ edg = Token(tokenContract); } /** * lets the owner close the contract if there are no player funds on it or if nobody has been using it for at least 30 days */ function closeContract(uint playerBalance) internal{ if(closeAt == 0) closeAt = now + 30 days; if(closeAt < now || playerBalance == 0){ edg.transfer(owner, edg.balanceOf(address(this))); selfdestruct(owner); } } /** * in case close has been called accidentally. **/ function open() onlyOwner public{ closeAt = 0; } /** * make sure the contract is not in process of being closed. **/ modifier isAlive { require(closeAt == 0); _; } /** * delays the time of closing. **/ modifier keepAlive { if(closeAt > 0) closeAt = now + 30 days; _; } } contract requiringAuthorization is mortal { /** indicates if an address is authorized to act in the casino&#39;s name */ mapping(address => bool) public authorized; /** tells if an address is allowed to receive funds from the bankroll **/ mapping(address => bool) public allowedReceiver; modifier onlyAuthorized { require(authorized[msg.sender]); _; } /** * Constructor. Authorize the owner. * */ function requiringAuthorization() internal { authorized[msg.sender] = true; allowedReceiver[msg.sender] = true; } /** * authorize a address to call game functions and set configs. * @param addr the address to be authorized **/ function authorize(address addr) public onlyOwner { authorized[addr] = true; } /** * deauthorize a address to call game functions and set configs. * @param addr the address to be deauthorized **/ function deauthorize(address addr) public onlyOwner { authorized[addr] = false; } /** * allow authorized wallets to withdraw funds from the bonkroll to this address * @param receiver the receiver&#39;s address * */ function allowReceiver(address receiver) public onlyOwner { allowedReceiver[receiver] = true; } /** * disallow authorized wallets to withdraw funds from the bonkroll to this address * @param receiver the receiver&#39;s address * */ function disallowReceiver(address receiver) public onlyOwner { allowedReceiver[receiver] = false; } /** * changes the owner of the contract. revokes authorization of the old owner and authorizes the new one. * @param newOwner the address of the new owner * */ function changeOwner(address newOwner) public onlyOwner { deauthorize(owner); authorize(newOwner); disallowReceiver(owner); allowReceiver(newOwner); owner = newOwner; } } contract chargingGas is requiringAuthorization, SafeMath { /** 1 EDG has 5 decimals **/ uint public constant oneEDG = 100000; /** the price per kgas and GWei in tokens (with decimals) */ uint public gasPrice; /** the amount of gas used per transaction in kGas */ mapping(bytes4 => uint) public gasPerTx; /** the number of tokens (5 decimals) payed by the users to cover the gas cost */ uint public gasPayback; function chargingGas(uint kGasPrice) internal{ //deposit, withdrawFor, updateChannel, updateBatch, transferToNewContract bytes4[5] memory signatures = [bytes4(0x3edd1128),0x9607610a, 0xde48ff52, 0xc97b6d1f, 0x6bf06fde]; //amount of gas consumed by the above methods in GWei uint[5] memory gasUsage = [uint(146), 100, 65, 50, 85]; setGasUsage(signatures, gasUsage); setGasPrice(kGasPrice); } /** * sets the amount of gas consumed by methods with the given sigantures. * only called from the edgeless casino constructor. * @param signatures an array of method-signatures * gasNeeded the amount of gas consumed by these methods * */ function setGasUsage(bytes4[5] signatures, uint[5] gasNeeded) public onlyOwner { require(signatures.length == gasNeeded.length); for (uint8 i = 0; i < signatures.length; i++) gasPerTx[signatures[i]] = gasNeeded[i]; } /** * updates the price per 1000 gas in EDG. * @param price the new gas price (with decimals, max 0.1 EDG) **/ function setGasPrice(uint price) public onlyAuthorized { require(price < oneEDG/10); gasPrice = price; } /** * returns the gas cost of the called function. * */ function getGasCost() internal view returns(uint) { return safeMul(safeMul(gasPerTx[msg.sig], gasPrice), tx.gasprice) / 1000000000; } } contract CasinoBank is chargingGas { /** the total balance of all players with virtual decimals **/ uint public playerBalance; /** the balance per player in edgeless tokens with virtual decimals */ mapping(address => uint) public balanceOf; /** in case the user wants/needs to call the withdraw function from his own wallet, he first needs to request a withdrawal */ mapping(address => uint) public withdrawAfter; /** a number to count withdrawal signatures to ensure each signature is different even if withdrawing the same amount to the same address */ mapping(address => uint) public withdrawCount; /** the maximum amount of tokens the user is allowed to deposit (with decimals) */ uint public maxDeposit; /** the maximum withdrawal of tokens the user is allowed to withdraw on one day (only enforced when the tx is not sent from an authorized wallet) **/ uint public maxWithdrawal; /** waiting time for withdrawal if not requested via the server **/ uint public waitingTime; /** the address of the predecessor **/ address public predecessor; /** informs listeners how many tokens were deposited for a player */ event Deposit(address _player, uint _numTokens, uint _gasCost); /** informs listeners how many tokens were withdrawn from the player to the receiver address */ event Withdrawal(address _player, address _receiver, uint _numTokens, uint _gasCost); /** * Constructor. * @param depositLimit the maximum deposit allowed * predecessorAddr the address of the predecessing contract * */ function CasinoBank(uint depositLimit, address predecessorAddr) internal { maxDeposit = depositLimit * oneEDG; maxWithdrawal = maxDeposit; waitingTime = 24 hours; predecessor = predecessorAddr; } /** * accepts deposits for an arbitrary address. * retrieves tokens from the message sender and adds them to the balance of the specified address. * edgeless tokens do not have any decimals, but are represented on this contract with decimals. * @param receiver address of the receiver * numTokens number of tokens to deposit (0 decimals) * chargeGas indicates if the gas cost is subtracted from the user&#39;s edgeless token balance **/ function deposit(address receiver, uint numTokens, bool chargeGas) public isAlive { require(numTokens > 0); uint value = safeMul(numTokens, oneEDG); uint gasCost; if (chargeGas) { gasCost = getGasCost(); value = safeSub(value, gasCost); gasPayback = safeAdd(gasPayback, gasCost); } uint newBalance = safeAdd(balanceOf[receiver], value); require(newBalance <= maxDeposit); assert(edg.transferFrom(msg.sender, address(this), numTokens)); balanceOf[receiver] = newBalance; playerBalance = safeAdd(playerBalance, value); Deposit(receiver, numTokens, gasCost); } /** * If the user wants/needs to withdraw his funds himself, he needs to request the withdrawal first. * This method sets the earliest possible withdrawal date to &#39;waitingTime from now (default 90m, but up to 24h). * Reason: The user should not be able to withdraw his funds, while the the last game methods have not yet been mined. **/ function requestWithdrawal() public { withdrawAfter[msg.sender] = now + waitingTime; } /** * In case the user requested a withdrawal and changes his mind. * Necessary to be able to continue playing. **/ function cancelWithdrawalRequest() public { withdrawAfter[msg.sender] = 0; } /** * withdraws an amount from the user balance if the waiting time passed since the request. * @param amount the amount of tokens to withdraw **/ function withdraw(uint amount) public keepAlive { require(amount <= maxWithdrawal); require(withdrawAfter[msg.sender] > 0 && now > withdrawAfter[msg.sender]); withdrawAfter[msg.sender] = 0; uint value = safeMul(amount, oneEDG); balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], value); playerBalance = safeSub(playerBalance, value); assert(edg.transfer(msg.sender, amount)); Withdrawal(msg.sender, msg.sender, amount, 0); } /** * lets the owner withdraw from the bankroll * @param receiver the receiver&#39;s address * numTokens the number of tokens to withdraw (0 decimals) **/ function withdrawBankroll(address receiver, uint numTokens) public onlyAuthorized { require(numTokens <= bankroll()); require(allowedReceiver[receiver]); assert(edg.transfer(receiver, numTokens)); } /** * withdraw the gas payback to the owner **/ function withdrawGasPayback() public onlyAuthorized { uint payback = gasPayback / oneEDG; assert(payback > 0); gasPayback = safeSub(gasPayback, payback * oneEDG); assert(edg.transfer(owner, payback)); } /** * returns the current bankroll in tokens with 0 decimals **/ function bankroll() constant public returns(uint) { return safeSub(edg.balanceOf(address(this)), safeAdd(playerBalance, gasPayback) / oneEDG); } /** * updates the maximum deposit. * @param newMax the new maximum deposit (0 decimals) **/ function setMaxDeposit(uint newMax) public onlyAuthorized { maxDeposit = newMax * oneEDG; } /** * updates the maximum withdrawal. * @param newMax the new maximum withdrawal (0 decimals) **/ function setMaxWithdrawal(uint newMax) public onlyAuthorized { maxWithdrawal = newMax * oneEDG; } /** * sets the time the player has to wait for his funds to be unlocked before withdrawal (if not withdrawing with help of the casino server). * the time may not be longer than 24 hours. * @param newWaitingTime the new waiting time in seconds * */ function setWaitingTime(uint newWaitingTime) public onlyAuthorized { require(newWaitingTime <= 24 hours); waitingTime = newWaitingTime; } /** * transfers an amount from the contract balance to the owner&#39;s wallet. * @param receiver the receiver address * amount the amount of tokens to withdraw (0 decimals) * v,r,s the signature of the player **/ function withdrawFor(address receiver, uint amount, uint8 v, bytes32 r, bytes32 s) public onlyAuthorized keepAlive { address player = ecrecover(keccak256(receiver, amount, withdrawCount[receiver]), v, r, s); withdrawCount[receiver]++; uint gasCost = getGasCost(); uint value = safeAdd(safeMul(amount, oneEDG), gasCost); gasPayback = safeAdd(gasPayback, gasCost); balanceOf[player] = safeSub(balanceOf[player], value); playerBalance = safeSub(playerBalance, value); assert(edg.transfer(receiver, amount)); Withdrawal(player, receiver, amount, gasCost); } /** * transfers the player&#39;s tokens directly to the new casino contract after an update. * @param newCasino the address of the new casino contract * v, r, s the signature of the player * chargeGas indicates if the gas cost is payed by the player. * */ function transferToNewContract(address newCasino, uint8 v, bytes32 r, bytes32 s, bool chargeGas) public onlyAuthorized keepAlive { address player = ecrecover(keccak256(address(this), newCasino), v, r, s); uint gasCost = 0; if(chargeGas) gasCost = getGasCost(); uint value = safeSub(balanceOf[player], gasCost); require(value > oneEDG); //fractions of one EDG cannot be withdrawn value /= oneEDG; playerBalance = safeSub(playerBalance, balanceOf[player]); balanceOf[player] = 0; assert(edg.transfer(newCasino, value)); Withdrawal(player, newCasino, value, gasCost); CasinoBank cb = CasinoBank(newCasino); assert(cb.credit(player, value)); } /** * receive a player balance from the predecessor contract. * @param player the address of the player to credit the value for * value the number of tokens to credit (0 decimals) * */ function credit(address player, uint value) public returns(bool) { require(msg.sender == predecessor); uint valueWithDecimals = safeMul(value, oneEDG); balanceOf[player] = safeAdd(balanceOf[player], valueWithDecimals); playerBalance = safeAdd(playerBalance, valueWithDecimals); Deposit(player, value, 0); return true; } /** * lets the owner close the contract if there are no player funds on it or if nobody has been using it for at least 30 days * */ function close() public onlyOwner { closeContract(playerBalance); } } contract EdgelessCasino is CasinoBank{ /** the most recent known state of a state channel */ mapping(address => State) public lastState; /** fired when the state is updated */ event StateUpdate(address player, uint128 count, int128 winBalance, int difference, uint gasCost); /** fired if one of the parties chooses to log the seeds and results */ event GameData(address player, bytes32[] serverSeeds, bytes32[] clientSeeds, int[] results, uint gasCost); struct State{ uint128 count; int128 winBalance; } /** * creates a new edgeless casino contract. * @param predecessorAddress the address of the predecessing contract * tokenContract the address of the Edgeless token contract * depositLimit the maximum deposit allowed * kGasPrice the price per kGas in WEI **/ function EdgelessCasino(address predecessorAddress, address tokenContract, uint depositLimit, uint kGasPrice) CasinoBank(depositLimit, predecessorAddress) mortal(tokenContract) chargingGas(kGasPrice) public{ } /** * updates several state channels at once. can be called by authorized wallets only. * 1. determines the player address from the signature. * 2. verifies if the signed game-count is higher than the last known game-count of this channel. * 3. updates the balances accordingly. This means: It checks the already performed updates for this channel and computes * the new balance difference to add or subtract from the player‘s balance. * @param winBalances array of the current wins or losses * gameCounts array of the numbers of signed game moves * v,r,s array of the players&#39;s signatures * chargeGas indicates if the gas costs should be subtracted from the players&#39;s balances * */ function updateBatch(int128[] winBalances, uint128[] gameCounts, uint8[] v, bytes32[] r, bytes32[] s, bool chargeGas) public onlyAuthorized{ require(winBalances.length == gameCounts.length); require(winBalances.length == v.length); require(winBalances.length == r.length); require(winBalances.length == s.length); require(winBalances.length <= 50); address player; uint gasCost = 0; if(chargeGas) gasCost = getGasCost(); gasPayback = safeAdd(gasPayback, safeMul(gasCost, winBalances.length)); for(uint8 i = 0; i < winBalances.length; i++){ player = ecrecover(keccak256(winBalances[i], gameCounts[i]), v[i], r[i], s[i]); _updateState(player, winBalances[i], gameCounts[i], gasCost); } } /** * updates a state channel. can be called by both parties. * 1. verifies the signature. * 2. verifies if the signed game-count is higher than the last known game-count of this channel. * 3. updates the balances accordingly. This means: It checks the already performed updates for this channel and computes * the new balance difference to add or subtract from the player‘s balance. * @param winBalance the current win or loss * gameCount the number of signed game moves * v,r,s the signature of either the casino or the player * chargeGas indicates if the gas costs should be subtracted from the player&#39;s balance * */ function updateState(int128 winBalance, uint128 gameCount, uint8 v, bytes32 r, bytes32 s, bool chargeGas) public{ address player = determinePlayer(winBalance, gameCount, v, r, s); uint gasCost = 0; if(player == msg.sender)//if the player closes the state channel himself, make sure the signer is a casino wallet require(authorized[ecrecover(keccak256(player, winBalance, gameCount), v, r, s)]); else if (chargeGas){//subtract the gas costs from the player balance only if the casino wallet is the sender gasCost = getGasCost(); gasPayback = safeAdd(gasPayback, gasCost); } _updateState(player, winBalance, gameCount, gasCost); } /** * internal method to perform the actual state update. * @param player the player address * winBalance the player&#39;s win balance * gameCount the player&#39;s game count * */ function _updateState(address player, int128 winBalance, uint128 gameCount, uint gasCost) internal { State storage last = lastState[player]; require(gameCount > last.count); int difference = updatePlayerBalance(player, winBalance, last.winBalance, gasCost); lastState[player] = State(gameCount, winBalance); StateUpdate(player, gameCount, winBalance, difference, gasCost); } /** * determines if the msg.sender or the signer of the passed signature is the player. returns the player&#39;s address * @param winBalance the current winBalance, used to calculate the msg hash * gameCount the current gameCount, used to calculate the msg.hash * v, r, s the signature of the non-sending party * */ function determinePlayer(int128 winBalance, uint128 gameCount, uint8 v, bytes32 r, bytes32 s) constant internal returns(address){ if (authorized[msg.sender])//casino is the sender -> player is the signer return ecrecover(keccak256(winBalance, gameCount), v, r, s); else return msg.sender; } /** * computes the difference of the win balance relative to the last known state and adds it to the player&#39;s balance. * in case the casino is the sender, the gas cost in EDG gets subtracted from the player&#39;s balance. * @param player the address of the player * winBalance the current win-balance * lastWinBalance the win-balance of the last known state * gasCost the gas cost of the tx * */ function updatePlayerBalance(address player, int128 winBalance, int128 lastWinBalance, uint gasCost) internal returns(int difference){ difference = safeSub(winBalance, lastWinBalance); int outstanding = safeSub(difference, int(gasCost)); uint outs; if(outstanding < 0){ outs = uint256(outstanding * (-1)); playerBalance = safeSub(playerBalance, outs); balanceOf[player] = safeSub(balanceOf[player], outs); } else{ outs = uint256(outstanding); assert(bankroll() * oneEDG > outs); playerBalance = safeAdd(playerBalance, outs); balanceOf[player] = safeAdd(balanceOf[player], outs); } } /** * logs some seeds and game results for players wishing to have their game history logged by the contract * @param serverSeeds array containing the server seeds * clientSeeds array containing the client seeds * results array containing the results * v, r, s the signature of the non-sending party (to make sure the correct results are logged) * */ function logGameData(bytes32[] serverSeeds, bytes32[] clientSeeds, int[] results, uint8 v, bytes32 r, bytes32 s) public{ address player = determinePlayer(serverSeeds, clientSeeds, results, v, r, s); uint gasCost; //charge gas in case the server is logging the results for the player if(player != msg.sender){ gasCost = (57 + 768 * serverSeeds.length / 1000)*gasPrice; balanceOf[player] = safeSub(balanceOf[player], gasCost); playerBalance = safeSub(playerBalance, gasCost); gasPayback = safeAdd(gasPayback, gasCost); } GameData(player, serverSeeds, clientSeeds, results, gasCost); } /** * determines if the msg.sender or the signer of the passed signature is the player. returns the player&#39;s address * @param serverSeeds array containing the server seeds * clientSeeds array containing the client seeds * results array containing the results * v, r, s the signature of the non-sending party * */ function determinePlayer(bytes32[] serverSeeds, bytes32[] clientSeeds, int[] results, uint8 v, bytes32 r, bytes32 s) constant internal returns(address){ address signer = ecrecover(keccak256(serverSeeds, clientSeeds, results), v, r, s); if (authorized[msg.sender])//casino is the sender -> player is the signer return signer; else if (authorized[signer]) return msg.sender; else revert(); } }
contract can be closed by the owner anytime after this timestamp if non-zero / the edgeless token contract /
function mortal(address tokenContract) internal{ edg = Token(tokenContract); }
2,416,629
// File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/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}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } // File: @openzeppelin/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: @openzeppelin/contracts/access/roles/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: @openzeppelin/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/src/common/libs/Decimals.sol pragma solidity ^0.5.0; /** * Library for emulating calculations involving decimals. */ library Decimals { using SafeMath for uint256; uint120 private constant basisValue = 1000000000000000000; /** * Returns the ratio of the first argument to the second argument. */ function outOf(uint256 _a, uint256 _b) internal pure returns (uint256 result) { if (_a == 0) { return 0; } uint256 a = _a.mul(basisValue); if (a < _b) { return 0; } return (a.div(_b)); } /** * Returns multiplied the number by 10^18. * This is used when there is a very large difference between the two numbers passed to the `outOf` function. */ function mulBasis(uint256 _a) internal pure returns (uint256) { return _a.mul(basisValue); } /** * Returns by changing the numerical value being emulated to the original number of digits. */ function divBasis(uint256 _a) internal pure returns (uint256) { return _a.div(basisValue); } } // File: contracts/src/common/lifecycle/Killable.sol pragma solidity ^0.5.0; /** * A module that allows contracts to self-destruct. */ contract Killable { address payable public _owner; /** * Initialized with the deployer as the owner. */ constructor() internal { _owner = msg.sender; } /** * Self-destruct the contract. * This function can only be executed by the owner. */ function kill() public { require(msg.sender == _owner, "only owner method"); selfdestruct(_owner); } } // File: @openzeppelin/contracts/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/src/common/interface/IGroup.sol pragma solidity ^0.5.0; contract IGroup { function isGroup(address _addr) public view returns (bool); function addGroup(address _addr) external; function getGroupKey(address _addr) internal pure returns (bytes32) { return keccak256(abi.encodePacked("_group", _addr)); } } // File: contracts/src/common/validate/AddressValidator.sol pragma solidity ^0.5.0; /** * A module that provides common validations patterns. */ contract AddressValidator { string constant errorMessage = "this is illegal address"; /** * Validates passed address is not a zero address. */ function validateIllegalAddress(address _addr) external pure { require(_addr != address(0), errorMessage); } /** * Validates passed address is included in an address set. */ function validateGroup(address _addr, address _groupAddr) external view { require(IGroup(_groupAddr).isGroup(_addr), errorMessage); } /** * Validates passed address is included in two address sets. */ function validateGroups( address _addr, address _groupAddr1, address _groupAddr2 ) external view { if (IGroup(_groupAddr1).isGroup(_addr)) { return; } require(IGroup(_groupAddr2).isGroup(_addr), errorMessage); } /** * Validates that the address of the first argument is equal to the address of the second argument. */ function validateAddress(address _addr, address _target) external pure { require(_addr == _target, errorMessage); } /** * Validates passed address equals to the two addresses. */ function validateAddresses( address _addr, address _target1, address _target2 ) external pure { if (_addr == _target1) { return; } require(_addr == _target2, errorMessage); } /** * Validates passed address equals to the three addresses. */ function validate3Addresses( address _addr, address _target1, address _target2, address _target3 ) external pure { if (_addr == _target1) { return; } if (_addr == _target2) { return; } require(_addr == _target3, errorMessage); } } // File: contracts/src/common/validate/UsingValidator.sol pragma solidity ^0.5.0; // prettier-ignore /** * Module for contrast handling AddressValidator. */ contract UsingValidator { AddressValidator private _validator; /** * Create a new AddressValidator contract when initialize. */ constructor() public { _validator = new AddressValidator(); } /** * Returns the set AddressValidator address. */ function addressValidator() internal view returns (AddressValidator) { return _validator; } } // File: contracts/src/common/config/AddressConfig.sol pragma solidity ^0.5.0; /** * A registry contract to hold the latest contract addresses. * Dev Protocol will be upgradeable by this contract. */ contract AddressConfig is Ownable, UsingValidator, Killable { address public token = 0x98626E2C9231f03504273d55f397409deFD4a093; address public allocator; address public allocatorStorage; address public withdraw; address public withdrawStorage; address public marketFactory; address public marketGroup; address public propertyFactory; address public propertyGroup; address public metricsGroup; address public metricsFactory; address public policy; address public policyFactory; address public policySet; address public policyGroup; address public lockup; address public lockupStorage; address public voteTimes; address public voteTimesStorage; address public voteCounter; address public voteCounterStorage; /** * Set the latest Allocator contract address. * Only the owner can execute this function. */ function setAllocator(address _addr) external onlyOwner { allocator = _addr; } /** * Set the latest AllocatorStorage contract address. * Only the owner can execute this function. * NOTE: But currently, the AllocatorStorage contract is not used. */ function setAllocatorStorage(address _addr) external onlyOwner { allocatorStorage = _addr; } /** * Set the latest Withdraw contract address. * Only the owner can execute this function. */ function setWithdraw(address _addr) external onlyOwner { withdraw = _addr; } /** * Set the latest WithdrawStorage contract address. * Only the owner can execute this function. */ function setWithdrawStorage(address _addr) external onlyOwner { withdrawStorage = _addr; } /** * Set the latest MarketFactory contract address. * Only the owner can execute this function. */ function setMarketFactory(address _addr) external onlyOwner { marketFactory = _addr; } /** * Set the latest MarketGroup contract address. * Only the owner can execute this function. */ function setMarketGroup(address _addr) external onlyOwner { marketGroup = _addr; } /** * Set the latest PropertyFactory contract address. * Only the owner can execute this function. */ function setPropertyFactory(address _addr) external onlyOwner { propertyFactory = _addr; } /** * Set the latest PropertyGroup contract address. * Only the owner can execute this function. */ function setPropertyGroup(address _addr) external onlyOwner { propertyGroup = _addr; } /** * Set the latest MetricsFactory contract address. * Only the owner can execute this function. */ function setMetricsFactory(address _addr) external onlyOwner { metricsFactory = _addr; } /** * Set the latest MetricsGroup contract address. * Only the owner can execute this function. */ function setMetricsGroup(address _addr) external onlyOwner { metricsGroup = _addr; } /** * Set the latest PolicyFactory contract address. * Only the owner can execute this function. */ function setPolicyFactory(address _addr) external onlyOwner { policyFactory = _addr; } /** * Set the latest PolicyGroup contract address. * Only the owner can execute this function. */ function setPolicyGroup(address _addr) external onlyOwner { policyGroup = _addr; } /** * Set the latest PolicySet contract address. * Only the owner can execute this function. */ function setPolicySet(address _addr) external onlyOwner { policySet = _addr; } /** * Set the latest Policy contract address. * Only the latest PolicyFactory contract can execute this function. */ function setPolicy(address _addr) external { addressValidator().validateAddress(msg.sender, policyFactory); policy = _addr; } /** * Set the latest Dev contract address. * Only the owner can execute this function. */ function setToken(address _addr) external onlyOwner { token = _addr; } /** * Set the latest Lockup contract address. * Only the owner can execute this function. */ function setLockup(address _addr) external onlyOwner { lockup = _addr; } /** * Set the latest LockupStorage contract address. * Only the owner can execute this function. * NOTE: But currently, the LockupStorage contract is not used as a stand-alone because it is inherited from the Lockup contract. */ function setLockupStorage(address _addr) external onlyOwner { lockupStorage = _addr; } /** * Set the latest VoteTimes contract address. * Only the owner can execute this function. * NOTE: But currently, the VoteTimes contract is not used. */ function setVoteTimes(address _addr) external onlyOwner { voteTimes = _addr; } /** * Set the latest VoteTimesStorage contract address. * Only the owner can execute this function. * NOTE: But currently, the VoteTimesStorage contract is not used. */ function setVoteTimesStorage(address _addr) external onlyOwner { voteTimesStorage = _addr; } /** * Set the latest VoteCounter contract address. * Only the owner can execute this function. */ function setVoteCounter(address _addr) external onlyOwner { voteCounter = _addr; } /** * Set the latest VoteCounterStorage contract address. * Only the owner can execute this function. * NOTE: But currently, the VoteCounterStorage contract is not used as a stand-alone because it is inherited from the VoteCounter contract. */ function setVoteCounterStorage(address _addr) external onlyOwner { voteCounterStorage = _addr; } } // File: contracts/src/common/config/UsingConfig.sol pragma solidity ^0.5.0; /** * Module for using AddressConfig contracts. */ contract UsingConfig { AddressConfig private _config; /** * Initialize the argument as AddressConfig address. */ constructor(address _addressConfig) public { _config = AddressConfig(_addressConfig); } /** * Returns the latest AddressConfig instance. */ function config() internal view returns (AddressConfig) { return _config; } /** * Returns the latest AddressConfig address. */ function configAddress() external view returns (address) { return address(_config); } } // File: contracts/src/common/storage/EternalStorage.sol pragma solidity ^0.5.0; /** * Module for persisting states. * Stores a map for `uint256`, `string`, `address`, `bytes32`, `bool`, and `int256` type with `bytes32` type as a key. */ contract EternalStorage { address private currentOwner = msg.sender; mapping(bytes32 => uint256) private uIntStorage; mapping(bytes32 => string) private stringStorage; mapping(bytes32 => address) private addressStorage; mapping(bytes32 => bytes32) private bytesStorage; mapping(bytes32 => bool) private boolStorage; mapping(bytes32 => int256) private intStorage; /** * Modifiers to validate that only the owner can execute. */ modifier onlyCurrentOwner() { require(msg.sender == currentOwner, "not current owner"); _; } /** * Transfer the owner. * Only the owner can execute this function. */ function changeOwner(address _newOwner) external { require(msg.sender == currentOwner, "not current owner"); currentOwner = _newOwner; } // *** Getter Methods *** /** * Returns the value of the `uint256` type that mapped to the given key. */ function getUint(bytes32 _key) external view returns (uint256) { return uIntStorage[_key]; } /** * Returns the value of the `string` type that mapped to the given key. */ function getString(bytes32 _key) external view returns (string memory) { return stringStorage[_key]; } /** * Returns the value of the `address` type that mapped to the given key. */ function getAddress(bytes32 _key) external view returns (address) { return addressStorage[_key]; } /** * Returns the value of the `bytes32` type that mapped to the given key. */ function getBytes(bytes32 _key) external view returns (bytes32) { return bytesStorage[_key]; } /** * Returns the value of the `bool` type that mapped to the given key. */ function getBool(bytes32 _key) external view returns (bool) { return boolStorage[_key]; } /** * Returns the value of the `int256` type that mapped to the given key. */ function getInt(bytes32 _key) external view returns (int256) { return intStorage[_key]; } // *** Setter Methods *** /** * Maps a value of `uint256` type to a given key. * Only the owner can execute this function. */ function setUint(bytes32 _key, uint256 _value) external onlyCurrentOwner { uIntStorage[_key] = _value; } /** * Maps a value of `string` type to a given key. * Only the owner can execute this function. */ function setString(bytes32 _key, string calldata _value) external onlyCurrentOwner { stringStorage[_key] = _value; } /** * Maps a value of `address` type to a given key. * Only the owner can execute this function. */ function setAddress(bytes32 _key, address _value) external onlyCurrentOwner { addressStorage[_key] = _value; } /** * Maps a value of `bytes32` type to a given key. * Only the owner can execute this function. */ function setBytes(bytes32 _key, bytes32 _value) external onlyCurrentOwner { bytesStorage[_key] = _value; } /** * Maps a value of `bool` type to a given key. * Only the owner can execute this function. */ function setBool(bytes32 _key, bool _value) external onlyCurrentOwner { boolStorage[_key] = _value; } /** * Maps a value of `int256` type to a given key. * Only the owner can execute this function. */ function setInt(bytes32 _key, int256 _value) external onlyCurrentOwner { intStorage[_key] = _value; } // *** Delete Methods *** /** * Deletes the value of the `uint256` type that mapped to the given key. * Only the owner can execute this function. */ function deleteUint(bytes32 _key) external onlyCurrentOwner { delete uIntStorage[_key]; } /** * Deletes the value of the `string` type that mapped to the given key. * Only the owner can execute this function. */ function deleteString(bytes32 _key) external onlyCurrentOwner { delete stringStorage[_key]; } /** * Deletes the value of the `address` type that mapped to the given key. * Only the owner can execute this function. */ function deleteAddress(bytes32 _key) external onlyCurrentOwner { delete addressStorage[_key]; } /** * Deletes the value of the `bytes32` type that mapped to the given key. * Only the owner can execute this function. */ function deleteBytes(bytes32 _key) external onlyCurrentOwner { delete bytesStorage[_key]; } /** * Deletes the value of the `bool` type that mapped to the given key. * Only the owner can execute this function. */ function deleteBool(bytes32 _key) external onlyCurrentOwner { delete boolStorage[_key]; } /** * Deletes the value of the `int256` type that mapped to the given key. * Only the owner can execute this function. */ function deleteInt(bytes32 _key) external onlyCurrentOwner { delete intStorage[_key]; } } // File: contracts/src/common/storage/UsingStorage.sol pragma solidity ^0.5.0; /** * Module for contrast handling EternalStorage. */ contract UsingStorage is Ownable { address private _storage; /** * Modifier to verify that EternalStorage is set. */ modifier hasStorage() { require(_storage != address(0), "storage is not set"); _; } /** * Returns the set EternalStorage instance. */ function eternalStorage() internal view hasStorage returns (EternalStorage) { return EternalStorage(_storage); } /** * Returns the set EternalStorage address. */ function getStorageAddress() external view hasStorage returns (address) { return _storage; } /** * Create a new EternalStorage contract. * This function call will fail if the EternalStorage contract is already set. * Also, only the owner can execute it. */ function createStorage() external onlyOwner { require(_storage == address(0), "storage is set"); EternalStorage tmp = new EternalStorage(); _storage = address(tmp); } /** * Assigns the EternalStorage contract that has already been created. * Only the owner can execute this function. */ function setStorage(address _storageAddress) external onlyOwner { _storage = _storageAddress; } /** * Delegates the owner of the current EternalStorage contract. * Only the owner can execute this function. */ function changeOwner(address newOwner) external onlyOwner { EternalStorage(_storage).changeOwner(newOwner); } } // File: contracts/src/withdraw/WithdrawStorage.sol pragma solidity ^0.5.0; contract WithdrawStorage is UsingStorage, UsingConfig, UsingValidator { // solium-disable-next-line no-empty-blocks constructor(address _config) public UsingConfig(_config) {} // RewardsAmount function setRewardsAmount(address _property, uint256 _value) external { addressValidator().validateAddress(msg.sender, config().withdraw()); eternalStorage().setUint(getRewardsAmountKey(_property), _value); } function getRewardsAmount(address _property) external view returns (uint256) { return eternalStorage().getUint(getRewardsAmountKey(_property)); } function getRewardsAmountKey(address _property) private pure returns (bytes32) { return keccak256(abi.encodePacked("_rewardsAmount", _property)); } // CumulativePrice function setCumulativePrice(address _property, uint256 _value) external { // The previously used function // This function is only used in testing addressValidator().validateAddress(msg.sender, config().withdraw()); eternalStorage().setUint(getCumulativePriceKey(_property), _value); } function getCumulativePrice(address _property) external view returns (uint256) { return eternalStorage().getUint(getCumulativePriceKey(_property)); } function getCumulativePriceKey(address _property) private pure returns (bytes32) { return keccak256(abi.encodePacked("_cumulativePrice", _property)); } // WithdrawalLimitTotal function setWithdrawalLimitTotal( address _property, address _user, uint256 _value ) external { addressValidator().validateAddress(msg.sender, config().withdraw()); eternalStorage().setUint( getWithdrawalLimitTotalKey(_property, _user), _value ); } function getWithdrawalLimitTotal(address _property, address _user) external view returns (uint256) { return eternalStorage().getUint( getWithdrawalLimitTotalKey(_property, _user) ); } function getWithdrawalLimitTotalKey(address _property, address _user) private pure returns (bytes32) { return keccak256( abi.encodePacked("_withdrawalLimitTotal", _property, _user) ); } // WithdrawalLimitBalance function setWithdrawalLimitBalance( address _property, address _user, uint256 _value ) external { addressValidator().validateAddress(msg.sender, config().withdraw()); eternalStorage().setUint( getWithdrawalLimitBalanceKey(_property, _user), _value ); } function getWithdrawalLimitBalance(address _property, address _user) external view returns (uint256) { return eternalStorage().getUint( getWithdrawalLimitBalanceKey(_property, _user) ); } function getWithdrawalLimitBalanceKey(address _property, address _user) private pure returns (bytes32) { return keccak256( abi.encodePacked("_withdrawalLimitBalance", _property, _user) ); } //LastWithdrawalPrice function setLastWithdrawalPrice( address _property, address _user, uint256 _value ) external { addressValidator().validateAddress(msg.sender, config().withdraw()); eternalStorage().setUint( getLastWithdrawalPriceKey(_property, _user), _value ); } function getLastWithdrawalPrice(address _property, address _user) external view returns (uint256) { return eternalStorage().getUint( getLastWithdrawalPriceKey(_property, _user) ); } function getLastWithdrawalPriceKey(address _property, address _user) private pure returns (bytes32) { return keccak256( abi.encodePacked("_lastWithdrawalPrice", _property, _user) ); } //PendingWithdrawal function setPendingWithdrawal( address _property, address _user, uint256 _value ) external { addressValidator().validateAddress(msg.sender, config().withdraw()); eternalStorage().setUint( getPendingWithdrawalKey(_property, _user), _value ); } function getPendingWithdrawal(address _property, address _user) external view returns (uint256) { return eternalStorage().getUint(getPendingWithdrawalKey(_property, _user)); } function getPendingWithdrawalKey(address _property, address _user) private pure returns (bytes32) { return keccak256(abi.encodePacked("_pendingWithdrawal", _property, _user)); } //LastCumulativeGlobalHoldersPrice function setLastCumulativeGlobalHoldersPrice( address _property, address _user, uint256 _value ) external { addressValidator().validateAddress(msg.sender, config().withdraw()); eternalStorage().setUint( getLastCumulativeGlobalHoldersPriceKey(_property, _user), _value ); } function getLastCumulativeGlobalHoldersPrice( address _property, address _user ) external view returns (uint256) { return eternalStorage().getUint( getLastCumulativeGlobalHoldersPriceKey(_property, _user) ); } function getLastCumulativeGlobalHoldersPriceKey( address _property, address _user ) private pure returns (bytes32) { return keccak256( abi.encodePacked( "_lastCumulativeGlobalHoldersPrice", _property, _user ) ); } //LastCumulativeHoldersReward function setLastCumulativeHoldersReward( address _property, address _user, uint256 _value ) external { addressValidator().validateAddress(msg.sender, config().withdraw()); eternalStorage().setUint( getLastCumulativeHoldersRewardKey(_property, _user), _value ); } function getLastCumulativeHoldersReward(address _property, address _user) external view returns (uint256) { return eternalStorage().getUint( getLastCumulativeHoldersRewardKey(_property, _user) ); } function getLastCumulativeHoldersRewardKey(address _property, address _user) private pure returns (bytes32) { return keccak256( abi.encodePacked( "_lastCumulativeHoldersReward", _property, _user ) ); } } // File: contracts/src/withdraw/IWithdraw.sol pragma solidity ^0.5.0; contract IWithdraw { function withdraw(address _property) external; function getRewardsAmount(address _property) external view returns (uint256); function beforeBalanceChange( address _property, address _from, address _to // solium-disable-next-line indentation ) external; function calculateWithdrawableAmount(address _property, address _user) external view returns (uint256); function calculateTotalWithdrawableAmount(address _property) external view returns (uint256); } // File: contracts/src/lockup/ILockup.sol pragma solidity ^0.5.0; contract ILockup { function lockup( address _from, address _property, uint256 _value // solium-disable-next-line indentation ) external; function update() public; function cancel(address _property) external; function withdraw(address _property) external; function difference(address _property, uint256 _lastReward) public view returns ( uint256 _reward, uint256 _holdersAmount, uint256 _holdersPrice, uint256 _interestAmount, uint256 _interestPrice ); function getPropertyValue(address _property) external view returns (uint256); function getAllValue() external view returns (uint256); function getValue(address _property, address _sender) external view returns (uint256); function calculateWithdrawableInterestAmount( address _property, address _user ) public view returns ( // solium-disable-next-line indentation uint256 ); function withdrawInterest(address _property) external; } // File: contracts/src/metrics/IMetricsGroup.sol pragma solidity ^0.5.0; contract IMetricsGroup is IGroup { function removeGroup(address _addr) external; function totalIssuedMetrics() external view returns (uint256); function getMetricsCountPerProperty(address _property) public view returns (uint256); function hasAssets(address _property) public view returns (bool); } // File: contracts/src/withdraw/LegacyWithdraw.sol pragma solidity ^0.5.0; // prettier-ignore /** * A contract that manages the withdrawal of holder rewards for Property holders. */ contract LegacyWithdraw is IWithdraw, UsingConfig, UsingValidator { using SafeMath for uint256; using Decimals for uint256; event PropertyTransfer(address _property, address _from, address _to); /** * Initialize the passed address as AddressConfig address. */ // solium-disable-next-line no-empty-blocks constructor(address _config) public UsingConfig(_config) {} /** * Withdraws rewards. */ function withdraw(address _property) external { /** * Validates the passed Property address is included the Property address set. */ addressValidator().validateGroup(_property, config().propertyGroup()); /** * Gets the withdrawable rewards amount and the latest cumulative sum of the maximum mint amount. */ (uint256 value, uint256 lastPrice) = _calculateWithdrawableAmount( _property, msg.sender ); /** * Validates the result is not 0. */ require(value != 0, "withdraw value is 0"); /** * Saves the latest cumulative sum of the maximum mint amount. * By subtracting this value when calculating the next rewards, always withdrawal the difference from the previous time. */ WithdrawStorage withdrawStorage = getStorage(); withdrawStorage.setLastCumulativeGlobalHoldersPrice( _property, msg.sender, lastPrice ); /** * Sets the number of unwithdrawn rewards to 0. */ withdrawStorage.setPendingWithdrawal(_property, msg.sender, 0); /** * Updates the withdrawal status to avoid double withdrawal for before DIP4. */ __updateLegacyWithdrawableAmount(_property, msg.sender); /** * Mints the holder reward. */ ERC20Mintable erc20 = ERC20Mintable(config().token()); require(erc20.mint(msg.sender, value), "dev mint failed"); /** * Since the total supply of tokens has changed, updates the latest maximum mint amount. */ ILockup lockup = ILockup(config().lockup()); lockup.update(); /** * Adds the reward amount already withdrawn in the passed Property. */ withdrawStorage.setRewardsAmount( _property, withdrawStorage.getRewardsAmount(_property).add(value) ); } /** * Updates the change in compensation amount due to the change in the ownership ratio of the passed Property. * When the ownership ratio of Property changes, the reward that the Property holder can withdraw will change. * It is necessary to update the status before and after the ownership ratio changes. */ function beforeBalanceChange( address _property, address _from, address _to ) external { /** * Validates the sender is Allocator contract. */ addressValidator().validateAddress(msg.sender, config().allocator()); WithdrawStorage withdrawStorage = getStorage(); /** * Gets the cumulative sum of the transfer source's "before transfer" withdrawable reward amount and the cumulative sum of the maximum mint amount. */ (uint256 amountFrom, uint256 priceFrom) = _calculateAmount( _property, _from ); /** * Gets the cumulative sum of the transfer destination's "before receive" withdrawable reward amount and the cumulative sum of the maximum mint amount. */ (uint256 amountTo, uint256 priceTo) = _calculateAmount(_property, _to); /** * Updates the last cumulative sum of the maximum mint amount of the transfer source and destination. */ withdrawStorage.setLastCumulativeGlobalHoldersPrice( _property, _from, priceFrom ); withdrawStorage.setLastCumulativeGlobalHoldersPrice( _property, _to, priceTo ); /** * Gets the unwithdrawn reward amount of the transfer source and destination. */ uint256 pendFrom = withdrawStorage.getPendingWithdrawal( _property, _from ); uint256 pendTo = withdrawStorage.getPendingWithdrawal(_property, _to); /** * Adds the undrawn reward amount of the transfer source and destination. */ withdrawStorage.setPendingWithdrawal( _property, _from, pendFrom.add(amountFrom) ); withdrawStorage.setPendingWithdrawal( _property, _to, pendTo.add(amountTo) ); emit PropertyTransfer(_property, _from, _to); } /** * Returns the reward amount already withdrawn in the passed Property. */ function getRewardsAmount(address _property) external view returns (uint256) { return getStorage().getRewardsAmount(_property); } /** * Passthrough to `Lockup.difference` function. */ function difference( WithdrawStorage withdrawStorage, address _property, address _user ) private view returns ( uint256 _reward, uint256 _holdersAmount, uint256 _holdersPrice, uint256 _interestAmount, uint256 _interestPrice ) { /** * Gets and passes the last recorded cumulative sum of the maximum mint amount. */ uint256 _last = withdrawStorage.getLastCumulativeGlobalHoldersPrice( _property, _user ); return ILockup(config().lockup()).difference(_property, _last); } /** * Returns the holder reward. */ function _calculateAmount(address _property, address _user) private view returns (uint256 _amount, uint256 _price) { WithdrawStorage withdrawStorage = getStorage(); /** * Gets the latest cumulative sum of the maximum mint amount, * and the difference to the previous withdrawal of holder reward unit price. */ (uint256 reward, , uint256 _holdersPrice, , ) = difference( withdrawStorage, _property, _user ); /** * Gets the ownership ratio of the passed user and the Property. */ uint256 balance = ERC20Mintable(_property).balanceOf(_user); /** * Multiplied by the number of tokens to the holder reward unit price. */ uint256 value = _holdersPrice.mul(balance); /** * Returns the result after adjusted decimals to 10^18, and the latest cumulative sum of the maximum mint amount. */ return (value.divBasis().divBasis(), reward); } /** * Returns the total rewards currently available for withdrawal. (For calling from inside the contract) */ function _calculateWithdrawableAmount(address _property, address _user) private view returns (uint256 _amount, uint256 _price) { /** * Gets the latest withdrawal reward amount. */ (uint256 _value, uint256 price) = _calculateAmount(_property, _user); /** * If the passed Property has not authenticated, returns always 0. */ if ( IMetricsGroup(config().metricsGroup()).hasAssets(_property) == false ) { return (0, price); } /** * Gets the reward amount of before DIP4. */ uint256 legacy = __legacyWithdrawableAmount(_property, _user); /** * Gets the reward amount in saved without withdrawal and returns the sum of all values. */ uint256 value = _value .add(getStorage().getPendingWithdrawal(_property, _user)) .add(legacy); return (value, price); } /** * Returns the total rewards currently available for withdrawal. (For calling from external of the contract) */ function calculateWithdrawableAmount(address _property, address _user) external view returns (uint256) { (uint256 value, ) = _calculateWithdrawableAmount(_property, _user); return value; } /** * Returns the cumulative sum of the holder rewards of the passed Property. */ function calculateTotalWithdrawableAmount(address _property) external view returns (uint256) { (, uint256 _amount, , , ) = ILockup(config().lockup()).difference( _property, 0 ); /** * Adjusts decimals to 10^18 and returns the result. */ return _amount.divBasis().divBasis(); } /** * Returns the reward amount of the calculation model before DIP4. * It can be calculated by subtracting "the last cumulative sum of reward unit price" from * "the current cumulative sum of reward unit price," and multiplying by the balance of the user. */ function __legacyWithdrawableAmount(address _property, address _user) private view returns (uint256) { WithdrawStorage withdrawStorage = getStorage(); uint256 _last = withdrawStorage.getLastWithdrawalPrice( _property, _user ); uint256 price = withdrawStorage.getCumulativePrice(_property); uint256 priceGap = price.sub(_last); uint256 balance = ERC20Mintable(_property).balanceOf(_user); uint256 value = priceGap.mul(balance); return value.divBasis(); } /** * Updates and treats the reward of before DIP4 as already received. */ function __updateLegacyWithdrawableAmount(address _property, address _user) private { WithdrawStorage withdrawStorage = getStorage(); uint256 price = withdrawStorage.getCumulativePrice(_property); withdrawStorage.setLastWithdrawalPrice(_property, _user, price); } /** * Returns WithdrawStorage instance. */ function getStorage() private view returns (WithdrawStorage) { return WithdrawStorage(config().withdrawStorage()); } } // File: contracts/src/withdraw/WithdrawMigration.sol pragma solidity ^0.5.0; contract WithdrawMigration is LegacyWithdraw, Ownable { constructor(address _config) public LegacyWithdraw(_config) {} function setLastCumulativeHoldersReward( address _property, address _user, uint256 _value ) external onlyOwner { WithdrawStorage withdrawStorage = WithdrawStorage( config().withdrawStorage() ); withdrawStorage.setLastCumulativeHoldersReward( _property, _user, _value ); } }
Returns the total rewards currently available for withdrawal. (For calling from inside the contract)/ Gets the latest withdrawal reward amount./ If the passed Property has not authenticated, returns always 0./
function _calculateWithdrawableAmount(address _property, address _user) private view returns (uint256 _amount, uint256 _price) { (uint256 _value, uint256 price) = _calculateAmount(_property, _user); if ( IMetricsGroup(config().metricsGroup()).hasAssets(_property) == false ) { return (0, price); } .add(getStorage().getPendingWithdrawal(_property, _user)) .add(legacy); return (value, price); }
1,680,255
./partial_match/4/0x4a3474cfF0DEE8CE6d38220EC96a3d626b0B45E2/sources/dr-fischer-crypto/hexaa/4/0x4a3474cfF0DEE8CE6d38220EC96a3d626b0B45E2/HexRandETH.sol
Verify an ETH address is part of the Merkle tree ethAddr address _path (info from outside) _witnesses (info from outside) return true if in the tree/ Avoid no-assign-params
function _ethAddressIsValid(address ethAddr, uint256 _path, bytes32[] memory _witnesses) internal view returns (bool) { require(!ethAddressClaims[ethAddr], "REX: address already claimed"); uint256 path = _path; bytes32[] memory witnesses = _witnesses; bytes32 node = keccak256(abi.encodePacked(uint8(0x00), msg.sender)); for (uint16 i = 0; i < witnesses.length; i++) { if ((path & 0x01) == 1) { node = keccak256( abi.encodePacked(uint8(0x01), witnesses[i], node) ); node = keccak256( abi.encodePacked(uint8(0x01), node, witnesses[i]) ); } path /= 2; } require(node == MERKLE_TREE_ROOT, "REX: Address not found"); return true; }
8,576,484
// SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol"; import "@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol"; import "./interfaces/IPool.sol"; import "./interfaces/IPoolFactory.sol"; import "./interfaces/IBaseContract.sol"; /// @title PoolFactory /// @notice Creates new pools for underlying tokens. contract PoolFactory is UpgradeableBeacon, IPoolFactory, IBaseContract { mapping(address => address) public override poolAddresses; address[] public tokenAddresses; event PoolProxyDeployed(address proxy); // solhint-disable-next-line /// @notice Construct an upgradable beacon. /// @param implementation_ address of the beacon proxy. constructor(address implementation_) UpgradeableBeacon(implementation_) {} /// @notice Creates new pools for underlying token. Only owner. /// @param poolToken address of the underlying token to crete pool for. /// @return address pool address function createPool(address poolToken, address _strategy, uint256 _maxInvestmentPerc) external onlyOwner returns (address) { // Check if a pool was already created for the given token. require(poolAddresses[poolToken] == address(0), "ALREADY_CREATED"); // Deploy a beacon proxy that gets the implementation address for each call from a UpgradeableBeacon. address instance = address(new BeaconProxy(address(this), "")); emit PoolProxyDeployed(instance); // Check that the contract was created require(instance != address(0), "NOT_CREATED"); // Set pool/token name and symbol string memory _name = ERC20(poolToken).name(); string memory _symbol = "LPT"; // init the pool; add initial strategies IPool(instance).initialize(_name, _symbol, poolToken, _strategy, _maxInvestmentPerc, msg.sender); tokenAddresses.push(poolToken); // Map created pool with proxy poolAddresses[poolToken] = instance; return instance; } /// @notice Pool count /// @return uint256 count function getTokenAddresses() public view returns (uint256) { return tokenAddresses.length; } /// @notice Contract name /// @return bytes32 name function getName() override external view returns (bytes32) { return "PoolFactory"; } // solhint-disable-next-line receive() external payable {} }
Contract name return bytes32 name
function getName() override external view returns (bytes32) { return "PoolFactory"; }
13,129,120
./full_match/100/0xb41C2115ee5481ce9036Bcf69eb8fB75Bb7e74EF/sources/contracts/NFT3D.sol
public require(_mintAmount <= maxMintAmount);
function mint(address _to, uint256 _mintAmount) onlyOwner() public payable { uint256 supply = totalSupply(); require(!paused); require(_mintAmount > 0); require(supply + _mintAmount <= maxSupply); if (msg.sender != owner()) { if(whitelisted[msg.sender] != true) { require(msg.value >= cost * _mintAmount); } } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(_to, supply + i); } }
14,264,790
./partial_match/56/0x0B820e2F7A06F2fE382C8E59248163003BE8CD1A/sources/OptionPandaToken.sol
Release the specified `amount` of locked amount only Owner call/
function release(address account, uint256 releaseAmount) public onlyOwner { require(account != address(0), "OPA: release zero address"); TimeLock storage timelock = _timelock[account]; timelock.amount = timelock.amount.sub(releaseAmount); if(timelock.amount == 0) { timelock.releaseTime = 0; } }
11,097,469
// SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: IAddressResolver interface IAddressResolver { function getAddress(bytes32 name) external view returns (address); function getSynth(bytes32 key) external view returns (address); function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address); } // Part: IExchangeRates interface IExchangeRates { // Structs struct RateAndUpdatedTime { uint216 rate; uint40 time; } struct InversePricing { uint256 entryPoint; uint256 upperLimit; uint256 lowerLimit; bool frozenAtUpperLimit; bool frozenAtLowerLimit; } // Views function aggregators(bytes32 currencyKey) external view returns (address); function aggregatorWarningFlags() external view returns (address); function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool); function canFreezeRate(bytes32 currencyKey) external view returns (bool); function currentRoundForRate(bytes32 currencyKey) external view returns (uint256); function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory); function effectiveValue( bytes32 sourceCurrencyKey, uint256 sourceAmount, bytes32 destinationCurrencyKey ) external view returns (uint256 value); function effectiveValueAndRates( bytes32 sourceCurrencyKey, uint256 sourceAmount, bytes32 destinationCurrencyKey ) external view returns ( uint256 value, uint256 sourceRate, uint256 destinationRate ); function effectiveValueAtRound( bytes32 sourceCurrencyKey, uint256 sourceAmount, bytes32 destinationCurrencyKey, uint256 roundIdForSrc, uint256 roundIdForDest ) external view returns (uint256 value); function getCurrentRoundId(bytes32 currencyKey) external view returns (uint256); function getLastRoundIdBeforeElapsedSecs( bytes32 currencyKey, uint256 startingRoundId, uint256 startingTimestamp, uint256 timediff ) external view returns (uint256); function inversePricing(bytes32 currencyKey) external view returns ( uint256 entryPoint, uint256 upperLimit, uint256 lowerLimit, bool frozenAtUpperLimit, bool frozenAtLowerLimit ); function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256); function oracle() external view returns (address); function rateAndTimestampAtRound(bytes32 currencyKey, uint256 roundId) external view returns (uint256 rate, uint256 time); function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint256 rate, uint256 time); function rateAndInvalid(bytes32 currencyKey) external view returns (uint256 rate, bool isInvalid); function rateForCurrency(bytes32 currencyKey) external view returns (uint256); function rateIsFlagged(bytes32 currencyKey) external view returns (bool); function rateIsFrozen(bytes32 currencyKey) external view returns (bool); function rateIsInvalid(bytes32 currencyKey) external view returns (bool); function rateIsStale(bytes32 currencyKey) external view returns (bool); function rateStalePeriod() external view returns (uint256); function ratesAndUpdatedTimeForCurrencyLastNRounds( bytes32 currencyKey, uint256 numRounds ) external view returns (uint256[] memory rates, uint256[] memory times); function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint256[] memory rates, bool anyRateInvalid); function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint256[] memory); // Mutative functions function freezeRate(bytes32 currencyKey) external; } // Part: IFeePool interface IFeePool { // Views function FEE_ADDRESS() external view returns (address); function feesAvailable(address account) external view returns (uint256, uint256); function feePeriodDuration() external view returns (uint256); function isFeesClaimable(address account) external view returns (bool); function targetThreshold() external view returns (uint256); function totalFeesAvailable() external view returns (uint256); function totalRewardsAvailable() external view returns (uint256); // Mutative Functions function claimFees() external returns (bool); function claimOnBehalf(address claimingForAddress) external returns (bool); function closeCurrentFeePeriod() external; } // Part: IIssuer interface IIssuer { // Views function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid); function availableCurrencyKeys() external view returns (bytes32[] memory); function availableSynthCount() external view returns (uint256); function canBurnSynths(address account) external view returns (bool); function collateral(address account) external view returns (uint256); function collateralisationRatio(address issuer) external view returns (uint256); function collateralisationRatioAndAnyRatesInvalid(address _issuer) external view returns (uint256 cratio, bool anyRateIsInvalid); function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint256 debtBalance); function issuanceRatio() external view returns (uint256); function lastIssueEvent(address account) external view returns (uint256); function maxIssuableSynths(address issuer) external view returns (uint256 maxIssuable); function minimumStakeTime() external view returns (uint256); function remainingIssuableSynths(address issuer) external view returns ( uint256 maxIssuable, uint256 alreadyIssued, uint256 totalSystemDebt ); function synthsByAddress(address synthAddress) external view returns (bytes32); function totalIssuedSynths(bytes32 currencyKey, bool excludeEtherCollateral) external view returns (uint256); function transferableSynthetixAndAnyRateIsInvalid( address account, uint256 balance ) external view returns (uint256 transferable, bool anyRateIsInvalid); // Restricted: used internally to Synthetix function issueSynths(address from, uint256 amount) external; function issueSynthsOnBehalf( address issueFor, address from, uint256 amount ) external; function issueMaxSynths(address from) external; function issueMaxSynthsOnBehalf(address issueFor, address from) external; function burnSynths(address from, uint256 amount) external; function burnSynthsOnBehalf( address burnForAddress, address from, uint256 amount ) external; function burnSynthsToTarget(address from) external; function burnSynthsToTargetOnBehalf(address burnForAddress, address from) external; } // Part: IReadProxy interface IReadProxy { function target() external view returns (address); } // Part: IRewardEscrowV2 interface IRewardEscrowV2 { // Views function nextEntryId() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function numVestingEntries(address account) external view returns (uint256); function totalEscrowedAccountBalance(address account) external view returns (uint256); function totalVestedAccountBalance(address account) external view returns (uint256); function getVestingQuantity(address account, uint256[] calldata entryIDs) external view returns (uint256); function getAccountVestingEntryIDs( address account, uint256 index, uint256 pageSize ) external view returns (uint256[] memory); function getVestingEntryClaimable(address account, uint256 entryID) external view returns (uint256); function getVestingEntry(address account, uint256 entryID) external view returns (uint64, uint256); // Mutative functions function vest(uint256[] calldata entryIDs) external; function createEscrowEntry( address beneficiary, uint256 deposit, uint256 duration ) external; function appendVestingEntry( address account, uint256 quantity, uint256 duration ) external; function migrateVestingSchedule(address _addressToMigrate) external; function migrateAccountEscrowBalances( address[] calldata accounts, uint256[] calldata escrowBalances, uint256[] calldata vestedBalances ) external; // Account Merging function startMergingWindow() external; function mergeAccount(address accountToMerge, uint256[] calldata entryIDs) external; function nominateAccountToMerge(address account) external; function accountMergingIsOpen() external view returns (bool); } // Part: ISushiRouter interface ISushiRouter { function swapExactTokensForTokens( uint256, uint256, address[] calldata, address, uint256 ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256, uint256, address[] calldata, address, uint256 ) external returns (uint256[] memory amounts); function getAmountsOut(uint256 amountIn, address[] memory path) external view returns (uint256[] memory amounts); } // Part: ISynthetix interface ISynthetix { function availableCurrencyKeys() external view returns (bytes32[] memory); function availableSynthCount() external view returns (uint256); function maxIssuableSynths(address issuer) external view returns (uint256 maxIssuable); function issueMaxSynths() external; function burnSynths(uint256 amount) external; function burnSynthsToTarget() external; function collateral(address account) external view returns (uint256); function transferableSynthetix(address account) external view returns (uint256 transferable); function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint256); } // Part: OpenZeppelin/[email protected]/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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); } } } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @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); } // Part: OpenZeppelin/[email protected]/Math /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // Part: OpenZeppelin/[email protected]/SafeMath /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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; } } // Part: IVault interface IVault is IERC20 { function deposit() external; function pricePerShare() external view returns (uint256); function withdraw() external; function withdraw(uint256 amount) external; function withdraw( uint256 amount, address account, uint256 maxLoss ) external; function availableDepositLimit() external view returns (uint256); } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @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"); } } } // Part: iearn-finance/[email protected]/VaultAPI interface VaultAPI is IERC20 { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function maxAvailableShares() external view returns (uint256); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); } // Part: iearn-finance/[email protected]/BaseStrategy /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.3.5"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external virtual view returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * Also note that this value is used to determine the total assets under management by this * strategy, for the purposes of computing the management fee in `Vault` * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external virtual view returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public virtual view returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit - _loss`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCost The keeper's estimated cast cost to call `tend()`. * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCost) public virtual view returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCost The keeper's estimated cast cost to call `harvest()`. * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCost) public virtual view returns (bool) { StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 totalAssets = estimatedTotalAssets(); // NOTE: use the larger of total assets or debt outstanding to book losses properly (debtPayment, loss) = liquidatePosition(totalAssets > debtOutstanding ? totalAssets : debtOutstanding); // NOTE: take up any remainder here as profit if (debtPayment > debtOutstanding) { profit = debtPayment.sub(debtOutstanding); debtPayment = debtOutstanding; } } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by governance or the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault) || msg.sender == governance()); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } */ function protectedTokens() internal virtual view returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } } // File: Strategy.sol contract Strategy is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; uint256 public constant MIN_ISSUE = 50 * 1e18; uint256 public ratioThreshold = 1e15; uint256 public constant MAX_RATIO = type(uint256).max; uint256 public constant MAX_BPS = 10_000; address public constant susd = address(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51); IReadProxy public constant readProxy = IReadProxy(address(0x4E3b31eB0E5CB73641EE1E65E7dCEFe520bA3ef2)); address public constant WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); ISushiRouter public constant sushiswap = ISushiRouter(address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F)); ISushiRouter public constant uniswap = ISushiRouter(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)); ISushiRouter public router = ISushiRouter(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)); uint256 public targetRatioMultiplier = 12_500; IVault public susdVault; // to keep track of next entry to vest uint256 public entryIDIndex = 0; // entryIDs of escrow rewards claimed and to be claimed by the Strategy uint256[] public entryIDs; bytes32 private constant CONTRACT_SYNTHETIX = "Synthetix"; bytes32 private constant CONTRACT_EXRATES = "ExchangeRates"; bytes32 private constant CONTRACT_REWARDESCROW_V2 = "RewardEscrowV2"; bytes32 private constant CONTRACT_ISSUER = "Issuer"; bytes32 private constant CONTRACT_FEEPOOL = "FeePool"; // ********************** EVENTS ********************** event RepayDebt(uint256 repaidAmount, uint256 debtAfterRepayment); // ********************** CONSTRUCTOR ********************** constructor(address _vault, address _susdVault) public BaseStrategy(_vault) { susdVault = IVault(_susdVault); // max time between harvest to collect rewards from each epoch maxReportDelay = 7 * 24 * 3600; // To deposit sUSD in the sUSD vault IERC20(susd).safeApprove(address(_susdVault), type(uint256).max); // To exchange sUSD for SNX IERC20(susd).safeApprove(address(uniswap), type(uint256).max); IERC20(susd).safeApprove(address(sushiswap), type(uint256).max); // To exchange SNX for sUSD IERC20(want).safeApprove(address(uniswap), type(uint256).max); IERC20(want).safeApprove(address(sushiswap), type(uint256).max); } // ********************** SETTERS ********************** function setRouter(uint256 _isSushi) external onlyAuthorized { if (_isSushi == uint256(1)) { router = sushiswap; } else if (_isSushi == uint256(0)) { router = uniswap; } else { revert("!invalid-arg. Use 1 for sushi. 0 for uni"); } } function setTargetRatioMultiplier(uint256 _targetRatioMultiplier) external { require( msg.sender == governance() || msg.sender == VaultAPI(address(vault)).management() ); targetRatioMultiplier = _targetRatioMultiplier; } function setRatioThreshold(uint256 _ratioThreshold) external onlyStrategist { ratioThreshold = _ratioThreshold; } // This method is used to migrate the vault where we deposit the sUSD for yield. It should be rarely used function migrateSusdVault(IVault newSusdVault, uint256 maxLoss) external onlyGovernance { // we tolerate losses to avoid being locked in the vault if things don't work out // governance must take this into account before migrating susdVault.withdraw( susdVault.balanceOf(address(this)), address(this), maxLoss ); IERC20(susd).safeApprove(address(susdVault), 0); susdVault = newSusdVault; IERC20(susd).safeApprove(address(newSusdVault), type(uint256).max); newSusdVault.deposit(); } // ********************** MANUAL ********************** function manuallyRepayDebt(uint256 amount) external onlyAuthorized { // To be used in case of emergencies, to operate the vault manually repayDebt(amount); } // ********************** YEARN STRATEGY ********************** function name() external view override returns (string memory) { return "StrategySynthetixSusdMinter"; } function estimatedTotalAssets() public view override returns (uint256) { uint256 totalAssets = balanceOfWant().add(estimatedProfit()).add( sUSDToWant(balanceOfSusdInVault().add(balanceOfSusd())) ); uint256 totalLiabilities = sUSDToWant(balanceOfDebt()); // NOTE: the ternary operator is required because debt can be higher than assets // due to i) increase in debt or ii) losses in invested assets return totalAssets > totalLiabilities ? totalAssets.sub(totalLiabilities) : 0; } function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { uint256 totalDebt = vault.strategies(address(this)).totalDebt; claimProfits(); vestNextRewardsEntry(); uint256 totalAssetsAfterProfit = estimatedTotalAssets(); _profit = totalAssetsAfterProfit > totalDebt ? totalAssetsAfterProfit.sub(totalDebt) : 0; // if the vault is claiming repayment of debt if (_debtOutstanding > 0) { uint256 _amountFreed = 0; (_amountFreed, _loss) = liquidatePosition(_debtOutstanding); _debtPayment = Math.min(_debtOutstanding, _amountFreed); if (_loss > 0) { _profit = 0; } } } function adjustPosition(uint256 _debtOutstanding) internal override { if (emergencyExit) { return; } if (_debtOutstanding >= balanceOfWant()) { return; } // compare current ratio with target ratio uint256 _currentRatio = getCurrentRatio(); // NOTE: target debt ratio is over 20% to maximize APY uint256 _targetRatio = getTargetRatio(); uint256 _issuanceRatio = getIssuanceRatio(); // burn debt (sUSD) if the ratio is too high // collateralisation_ratio = debt / collat if ( _currentRatio > _targetRatio && _currentRatio.sub(_targetRatio) >= ratioThreshold ) { // NOTE: min threshold to act on differences = 1e16 (ratioThreshold) // current debt ratio might be unhealthy // we need to repay some debt to get back to the optimal range uint256 _debtToRepay = balanceOfDebt().sub(getTargetDebt(_collateral())); repayDebt(_debtToRepay); } else if ( _issuanceRatio > _currentRatio && _issuanceRatio.sub(_currentRatio) >= ratioThreshold ) { // NOTE: min threshold to act on differences = 1e16 (ratioThreshold) // if there is enough collateral to issue Synth, issue it // this should put the c-ratio around 500% (i.e. debt ratio around 20%) uint256 _maxSynths = _synthetix().maxIssuableSynths(address(this)); uint256 _debtBalance = balanceOfDebt(); // only issue new debt if it is going to be used if ( _maxSynths > _debtBalance && _maxSynths.sub(_debtBalance) >= MIN_ISSUE ) { _synthetix().issueMaxSynths(); } } // If there is susd in the strategy, send it to the susd vault // We do MIN_ISSUE instead of 0 since it might be dust if (balanceOfSusd() >= MIN_ISSUE) { susdVault.deposit(); } } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { // if unlocked collateral balance is not enough, repay debt to unlock // enough `want` to repay debt. // unlocked collateral includes profit just claimed in `prepareReturn` uint256 unlockedWant = _unlockedWant(); if (unlockedWant < _amountNeeded) { // NOTE: we use _unlockedWant because `want` balance is the total amount of staked + unstaked want (SNX) reduceLockedCollateral(_amountNeeded.sub(unlockedWant)); } // Fetch the unlocked collateral for a second time // to update after repaying debt unlockedWant = _unlockedWant(); // if not enough want in balance, it means the strategy lost `want` if (_amountNeeded > unlockedWant) { _liquidatedAmount = unlockedWant; _loss = _amountNeeded.sub(unlockedWant); } else { _liquidatedAmount = _amountNeeded; } } function prepareMigration(address _newStrategy) internal override { liquidatePosition(vault.strategies(address(this)).totalDebt); } // ********************** OPERATIONS FUNCTIONS ********************** function reduceLockedCollateral(uint256 amountToFree) internal { // amountToFree cannot be higher than the amount that is unlockable amountToFree = Math.min(amountToFree, _unlockableWant()); if (amountToFree == 0) { return; } uint256 _currentDebt = balanceOfDebt(); uint256 _newCollateral = _lockedCollateral().sub(amountToFree); uint256 _targetDebt = _newCollateral.mul(getIssuanceRatio()).div(1e18); // NOTE: _newCollateral will always be < _lockedCollateral() so _targetDebt will always be < _currentDebt uint256 _amountToRepay = _currentDebt.sub(_targetDebt); repayDebt(_amountToRepay); } function repayDebt(uint256 amountToRepay) internal { // debt can grow over the amount of sUSD minted (see Synthetix docs) // if that happens, we might not have enough sUSD to repay debt // if we withdraw in this situation, we need to sell `want` to repay debt and would have losses // this can only be done if c-Ratio is over 272% (otherwise there is not enough unlocked) if (amountToRepay == 0) { return; } uint256 repaidAmount = 0; uint256 _debtBalance = balanceOfDebt(); // max amount to be repaid is the total balanceOfDebt amountToRepay = Math.min(_debtBalance, amountToRepay); // in case the strategy is going to repay almost all debt, it should repay the total amount of debt if ( _debtBalance > amountToRepay && _debtBalance.sub(amountToRepay) <= MIN_ISSUE ) { amountToRepay = _debtBalance; } uint256 currentSusdBalance = balanceOfSusd(); if (amountToRepay > currentSusdBalance) { // there is not enough balance in strategy to repay debt // we withdraw from susdvault uint256 _withdrawAmount = amountToRepay.sub(currentSusdBalance); withdrawFromSUSDVault(_withdrawAmount); // we fetch sUSD balance for a second time and check if now there is enough currentSusdBalance = balanceOfSusd(); if (amountToRepay > currentSusdBalance) { // there was not enough balance in strategy and sUSDvault to repay debt // debt is too high to be repaid using current funds, the strategy should: // 1. repay max amount of debt // 2. sell unlocked want to buy required sUSD to pay remaining debt // 3. repay debt if (currentSusdBalance > 0) { // we burn the full sUSD balance to unlock `want` (SNX) in order to sell if (burnSusd(currentSusdBalance)) { // subject to minimumStakePeriod // if successful burnt, update remaining amountToRepay // repaidAmount is previous debt minus current debt repaidAmount = _debtBalance.sub(balanceOfDebt()); } } // buy enough sUSD to repay outstanding debt, selling `want` (SNX) // or maximum sUSD with `want` available uint256 amountToBuy = Math.min( _getSusdForWant(_unlockedWant()), amountToRepay.sub(repaidAmount) ); if (amountToBuy > 0) { buySusdWithWant(amountToBuy); } // amountToRepay should equal balanceOfSusd() (we just bought `amountToRepay` sUSD) } } // repay sUSD debt by burning the synth if (amountToRepay > repaidAmount) { burnSusd(amountToRepay.sub(repaidAmount)); // this method is subject to minimumStakePeriod (see Synthetix docs) repaidAmount = amountToRepay; } emit RepayDebt(repaidAmount, _debtBalance.sub(repaidAmount)); } // two profit sources: Synthetix protocol and Yearn sUSD Vault function claimProfits() internal returns (bool) { uint256 feesAvailable; uint256 rewardsAvailable; (feesAvailable, rewardsAvailable) = _getFeesAvailable(); if (feesAvailable > 0 || rewardsAvailable > 0) { // claim fees from Synthetix // claim fees (in sUSD) and rewards (in want (SNX)) // Synthetix protocol requires issuers to have a c-ratio above 500% // to be able to claim fees so we need to burn some sUSD // NOTE: we use issuanceRatio because that is what will put us on 500% c-ratio (i.e. 20% debt ratio) uint256 _targetDebt = getIssuanceRatio().mul(wantToSUSD(_collateral())).div(1e18); uint256 _balanceOfDebt = balanceOfDebt(); bool claim = true; if (_balanceOfDebt > _targetDebt) { uint256 _requiredPayment = _balanceOfDebt.sub(_targetDebt); uint256 _maxCash = balanceOfSusd().add(balanceOfSusdInVault()).mul(50).div( 100 ); // only claim rewards if the required payment to burn debt up to c-ratio 500% // is less than 50% of available cash (both in strategy and in sUSD vault) claim = _requiredPayment <= _maxCash; } if (claim) { // we need to burn sUSD to target burnSusdToTarget(); // if a vesting entry is going to be created, // we save its ID to keep track of its vesting if (rewardsAvailable > 0) { entryIDs.push(_rewardEscrowV2().nextEntryId()); } // claimFees() will claim both sUSD fees and put SNX rewards in the escrow (in the prev. saved entry) _feePool().claimFees(); } } // claim profits from Yearn sUSD Vault if (balanceOfDebt() < balanceOfSusdInVault()) { // balance uint256 _valueToWithdraw = balanceOfSusdInVault().sub(balanceOfDebt()); withdrawFromSUSDVault(_valueToWithdraw); } // sell profits in sUSD for want (SNX) using router uint256 _balance = balanceOfSusd(); if (_balance > 0) { buyWantWithSusd(_balance); } } function vestNextRewardsEntry() internal { // Synthetix protocol sends SNX staking rewards to a escrow contract that keeps them 52 weeks, until they vest // each time we claim the SNX rewards, a VestingEntry is created in the escrow contract for the amount that was owed // we need to keep track of those VestingEntries to know when they vest and claim them // after they vest and we claim them, we will receive them in our balance (strategy's balance) if (entryIDs.length == 0) { return; } // The strategy keeps track of the next VestingEntry expected to vest and only when it has vested, it checks the next one // this works because the VestingEntries record has been saved in chronological order and they will vest in chronological order too IRewardEscrowV2 re = _rewardEscrowV2(); uint256 nextEntryID = entryIDs[entryIDIndex]; uint256 _claimable = re.getVestingEntryClaimable(address(this), nextEntryID); // check if we need to vest if (_claimable == 0) { return; } // vest entryID uint256[] memory params = new uint256[](1); params[0] = nextEntryID; re.vest(params); // we update the nextEntryID to point to the next VestingEntry entryIDIndex++; } function tendTrigger(uint256 callCost) public view override returns (bool) { uint256 _currentRatio = getCurrentRatio(); // debt / collateral uint256 _targetRatio = getTargetRatio(); // max debt ratio. over this number, we consider debt unhealthy uint256 _issuanceRatio = getIssuanceRatio(); // preferred debt ratio by Synthetix (See protocol docs) if (_currentRatio < _issuanceRatio) { // strategy needs to take more debt // only return true if the difference is greater than a threshold return _issuanceRatio.sub(_currentRatio) >= ratioThreshold; } else if (_currentRatio <= _targetRatio) { // strategy is in optimal range (a bit undercollateralised) return false; } else if (_currentRatio > _targetRatio) { // the strategy needs to repay debt to exit the danger zone // only return true if the difference is greater than a threshold return _currentRatio.sub(_targetRatio) >= ratioThreshold; } return false; } function protectedTokens() internal view override returns (address[] memory) {} // ********************** SUPPORT FUNCTIONS ********************** function burnSusd(uint256 _amount) internal returns (bool) { // returns false if unsuccessful if (_issuer().canBurnSynths(address(this))) { _synthetix().burnSynths(_amount); return true; } else { return false; } } function burnSusdToTarget() internal returns (uint256) { // we use this method to be able to avoid the waiting period // (see Synthetix Protocol) // it burns enough Synths to get back to 500% c-ratio // we need to have enough sUSD to burn to target uint256 _debtBalance = balanceOfDebt(); // NOTE: amount of synths at 500% c-ratio (with current collateral) uint256 _maxSynths = _synthetix().maxIssuableSynths(address(this)); if (_debtBalance <= _maxSynths) { // we are over the 500% c-ratio (i.e. below 20% debt ratio), we don't need to burn sUSD return 0; } uint256 _amountToBurn = _debtBalance.sub(_maxSynths); uint256 _balance = balanceOfSusd(); if (_balance < _amountToBurn) { // if we do not have enough in balance, we withdraw funds from sUSD vault withdrawFromSUSDVault(_amountToBurn.sub(_balance)); } if (_amountToBurn > 0) _synthetix().burnSynthsToTarget(); return _amountToBurn; } function withdrawFromSUSDVault(uint256 _amount) internal { // Don't leave less than MIN_ISSUE sUSD in the vault if ( _amount > balanceOfSusdInVault() || balanceOfSusdInVault().sub(_amount) <= MIN_ISSUE ) { susdVault.withdraw(); } else { uint256 _sharesToWithdraw = _amount.mul(1e18).div(susdVault.pricePerShare()); susdVault.withdraw(_sharesToWithdraw); } } function buyWantWithSusd(uint256 _amount) internal { if (_amount == 0) { return; } address[] memory path = new address[](3); path[0] = address(susd); path[1] = address(WETH); path[2] = address(want); router.swapExactTokensForTokens(_amount, 0, path, address(this), now); } function buySusdWithWant(uint256 _amount) internal { if (_amount == 0) { return; } address[] memory path = new address[](3); path[0] = address(want); path[1] = address(WETH); path[2] = address(susd); // we use swapTokensForExactTokens because we need an exact sUSD amount router.swapTokensForExactTokens( _amount, type(uint256).max, path, address(this), now ); } // ********************** CALCS ********************** function estimatedProfit() public view returns (uint256) { uint256 availableFees; // in sUSD (availableFees, ) = _getFeesAvailable(); return sUSDToWant(availableFees); } function getTargetDebt(uint256 _targetCollateral) internal returns (uint256) { uint256 _targetRatio = getTargetRatio(); uint256 _collateralInSUSD = wantToSUSD(_targetCollateral); return _targetRatio.mul(_collateralInSUSD).div(1e18); } function sUSDToWant(uint256 _amount) internal view returns (uint256) { if (_amount == 0) { return 0; } return _amount.mul(1e18).div(_exchangeRates().rateForCurrency("SNX")); } function wantToSUSD(uint256 _amount) internal view returns (uint256) { if (_amount == 0) { return 0; } return _amount.mul(_exchangeRates().rateForCurrency("SNX")).div(1e18); } function _getSusdForWant(uint256 _wantAmount) internal view returns (uint256) { if (_wantAmount == 0) { return 0; } address[] memory path = new address[](3); path[0] = address(want); path[1] = address(WETH); path[2] = address(susd); uint256[] memory amounts = router.getAmountsOut(_wantAmount, path); return amounts[amounts.length - 1]; } // ********************** BALANCES & RATIOS ********************** function _lockedCollateral() internal view returns (uint256) { // collateral includes `want` balance (both locked and unlocked) AND escrowed balance uint256 _collateral = _synthetix().collateral(address(this)); return _collateral.sub(_unlockedWant()); } // amount of `want` (SNX) that can be transferred, sold, ... function _unlockedWant() internal view returns (uint256) { return _synthetix().transferableSynthetix(address(this)); } function _unlockableWant() internal view returns (uint256) { // collateral includes escrowed SNX, we may not be able to unlock the full // we can only unlock this by repaying debt return balanceOfWant().sub(_unlockedWant()); } function _collateral() internal view returns (uint256) { return _synthetix().collateral(address(this)); } // returns fees and rewards function _getFeesAvailable() internal view returns (uint256, uint256) { // fees in sUSD // rewards in `want` (SNX) return _feePool().feesAvailable(address(this)); } function getCurrentRatio() public view returns (uint256) { // ratio = debt / collateral // i.e. ratio is 0 if debt is 0 // NOTE: collateral includes SNX in account + escrowed balance return _issuer().collateralisationRatio(address(this)); } function getIssuanceRatio() public view returns (uint256) { return _issuer().issuanceRatio(); } function getTargetRatio() public view returns (uint256) { return getIssuanceRatio().mul(targetRatioMultiplier).div(MAX_BPS); } function balanceOfEscrowedWant() public view returns (uint256) { return _rewardEscrowV2().balanceOf(address(this)); } function balanceOfWant() public view returns (uint256) { return IERC20(want).balanceOf(address(this)); } function balanceOfSusd() public view returns (uint256) { return IERC20(susd).balanceOf(address(this)); } function balanceOfDebt() public view returns (uint256) { return _synthetix().debtBalanceOf(address(this), "sUSD"); } function balanceOfSusdInVault() public view returns (uint256) { return susdVault .balanceOf(address(this)) .mul(susdVault.pricePerShare()) .div(1e18); } // ********************** ADDRESS RESOLVER SHORTCUTS ********************** function resolver() public view returns (IAddressResolver) { return IAddressResolver(readProxy.target()); } function _synthetix() internal view returns (ISynthetix) { return ISynthetix(resolver().getAddress(CONTRACT_SYNTHETIX)); } function _feePool() internal view returns (IFeePool) { return IFeePool(resolver().getAddress(CONTRACT_FEEPOOL)); } function _issuer() internal view returns (IIssuer) { return IIssuer(resolver().getAddress(CONTRACT_ISSUER)); } function _exchangeRates() internal view returns (IExchangeRates) { return IExchangeRates(resolver().getAddress(CONTRACT_EXRATES)); } function _rewardEscrowV2() internal view returns (IRewardEscrowV2) { return IRewardEscrowV2(resolver().getAddress(CONTRACT_REWARDESCROW_V2)); } }
NOTE: the ternary operator is required because debt can be higher than assets due to i) increase in debt or ii) losses in invested assets
function estimatedTotalAssets() public view override returns (uint256) { uint256 totalAssets = balanceOfWant().add(estimatedProfit()).add( sUSDToWant(balanceOfSusdInVault().add(balanceOfSusd())) ); uint256 totalLiabilities = sUSDToWant(balanceOfDebt()); return totalAssets > totalLiabilities ? totalAssets.sub(totalLiabilities) : 0; }
1,579,152
pragma solidity ^0.4.17; contract Lottery { address public manager; address[] public players; address public lastWinner; function Lottery() public { manager = msg.sender; } function enter() public payable { // require min .01 ether or 10000000000000000 wei require(msg.value > .01 ether); players.push(msg.sender); } function random() private view returns (uint) { // pass block difficult, time and players into sha3. Cast hash to uint return uint(sha3(block.difficulty, now, players)); } function pickWinner() public restricted { uint winnerIndex = random() % players.length; address winnerAddress = players[winnerIndex]; winnerAddress.transfer(address(this).balance); players = new address[](0); lastWinner = winnerAddress; } modifier restricted() { //only allow the manager to call pickWinner require(msg.sender == manager); _; } function getPlayers() public view returns (address[]) { return players; } }
pass block difficult, time and players into sha3. Cast hash to uint
function random() private view returns (uint) { return uint(sha3(block.difficulty, now, players)); }
13,007,793
pragma solidity >=0.5.11; contract Casino { //Represents a single bet struct Bet { int prediction; // The prediction for the winner uint wager; // The amount of money the Bettor put down on this BetPrediction } Game currentGame; //The game that is currently being played uint casinoPot; // Number of tokens owned by the Casino // Assume there's code that lets people buy and sell tokens. You don't need to write it. mapping (address => uint) tokenBalances; mapping (address => Bet) bets; mapping (address => bool) betsTaken; constructor(Game g) public { currentGame = g; casinoPot = 1000; // Assume the casino starts with plenty of tokens } //TODO: Add your code here. } //Represents a generic game contract Game { enum State { BeforePlay, Playing, FinishedPlaying} State public state; int outcome; // In FinishedPlaying state, stores information about the outcome of the game. constructor() public { state = State.BeforePlay; } //Start the game function startPlaying() public { require(state == State.BeforePlay, "Wrong initial state."); state = State.Playing; } //Finish the game function finishPlaying() public { require(state == State.Playing, "Wrong initial state."); outcome = 42; // Just assume something simple for now. state = State.FinishedPlaying; } //Returns the outcome of the game function predictionMatchesOutcome(int prediction) public view returns (bool) { require(state == State.FinishedPlaying, "Wrong initial state."); //... return prediction == outcome; } }
Returns the outcome of the game...
function predictionMatchesOutcome(int prediction) public view returns (bool) { require(state == State.FinishedPlaying, "Wrong initial state."); return prediction == outcome; }
7,229,675
// SPDX-License-Identifier: MIT pragma solidity >=0.8.10; import "./ERC721.sol"; import "./Ownable.sol"; import "./Strings.sol"; /** __ _ / /| | __ _ _ __ ___ __ _/\ /\___ _ __ ___ ___ / / | |/ _` | '_ ` _ \ / _` \ \ / / _ \ '__/ __|/ _ \ / /__| | (_| | | | | | | (_| |\ V / __/ | \__ \ __/ \____/_|\__,_|_| |_| |_|\__,_| \_/ \___|_| |___/\___| **/ /// @title Pixelated Llama /// @author delta devs (https://twitter.com/deltadevelopers) /// @notice Thrown when attempting to mint while the dutch auction has not started yet. error AuctionNotStarted(); /// @notice Thrown when attempting to mint whilst the total supply (of either static or animated llamas) has been reached. error MintedOut(); /// @notice Thrown when the value of the transaction is not enough when attempting to purchase llama during dutch auction or minting post auction. error NotEnoughEther(); contract PixelatedLlama is ERC721, Ownable { using Strings for uint256; /*/////////////////////////////////////////////////////////////// CONSTANTS //////////////////////////////////////////////////////////////*/ uint256 public constant provenanceHash = 0x7481a3a60827a9db04e46389b14c42d8f0ba2106ed9b239db8249929a8ab9f0b; /// @notice The total supply of Llamas, consisting of both static & animated llamas. uint256 public constant totalSupply = 4000; /// @notice The total supply cap of animated llamas. uint256 public constant animatedSupplyCap = 500; /// @notice The total supply cap of static llamas. /// @dev This does not mean there are 4000 llamas, it means that 4000 is the last tokenId of a static llama. uint256 public constant staticSupplyCap = 4000; /// @notice The total supply cap of the dutch auction. /// @dev 1600 is the (phase 2) whitelist allocation. uint256 public constant auctionSupplyCap = staticSupplyCap - 1600; /// @notice The current supply of animated llamas, and a counter for the next static tokenId. uint256 public animatedSupply; /// @notice The current static supply of llamas, and a counter for the next animated tokenId. /// @dev Starts at the animated supply cap, since the first 500 tokenIds are used for the animated llama supply. uint256 public staticSupply = animatedSupplyCap; /// @notice The UNIX timestamp of the begin of the dutch auction. uint256 constant auctionStartTime = 1645628400; /// @notice The start price of the dutch auction. uint256 public auctionStartPrice = 1.14 ether; /// @notice Allocation of static llamas mintable per address. /// @dev Used for both free minters in Phase 1, and WL minters after the DA. mapping(address => uint256) public staticWhitelist; /// @notice Allocation of animated llamas mintable per address. /// @dev Not used for the WL phase, only for free mints. mapping(address => uint256) public animatedWhitelist; /// @notice The mint price of a static llama. uint256 public staticPrice; /*/////////////////////////////////////////////////////////////// METADATA STORAGE //////////////////////////////////////////////////////////////*/ /// @notice The base URI which retrieves token metadata. string baseURI; /// @notice Guarantees that the dutch auction has started. /// @dev This also warms up the storage slot for auctionStartTime to save gas in getCurrentTokenPrice modifier auctionStarted() { if (block.timestamp < auctionStartTime) revert AuctionNotStarted(); _; } /*/////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor(string memory _baseURI) ERC721("Pixelated Llama", "PXLLMA") { baseURI = _baseURI; } /*/////////////////////////////////////////////////////////////// METADATA LOGIC //////////////////////////////////////////////////////////////*/ function tokenURI(uint256 id) public view override returns (string memory) { return string(abi.encodePacked(baseURI, id.toString())); } function setBaseURI(string memory _baseURI) public onlyOwner { baseURI = _baseURI; } /// @notice Uploads the number of mintable static llamas for each WL address. /// @param addresses The WL addresses. function uploadStaticWhitelist( address[] calldata addresses ) public onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { staticWhitelist[addresses[i]] = 1; } } /// @notice Uploads the number of mintable static llamas for each WL address. /// @param addresses The WL addresses. /// @param counts The number of static llamas allocated to the same index in the first array. function uploadStaticWhitelist( address[] calldata addresses, uint256[] calldata counts ) public onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { staticWhitelist[addresses[i]] = counts[i]; } } /// @notice Uploads the number of mintable animated llamas for each WL address. /// @param addresses The WL addresses. /// @param counts The number of animated llamas allocated to the same index in the first array. function uploadAnimatedWhitelist( address[] calldata addresses, uint256[] calldata counts ) public onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { animatedWhitelist[addresses[i]] = counts[i]; } } /*/////////////////////////////////////////////////////////////// DUTCH AUCTION LOGIC //////////////////////////////////////////////////////////////*/ /// @notice Mints one static llama during the dutch auction. function mintAuction() public payable auctionStarted { if (msg.value < getCurrentTokenPrice()) revert NotEnoughEther(); if (staticSupply >= auctionSupplyCap) revert MintedOut(); unchecked { _mint(msg.sender, staticSupply); staticSupply++; } } /// @notice Calculates the auction price with the accumulated rate deduction since the auction's begin /// @return The auction price at the current time, or 0 if the deductions are greater than the auction's start price. function validCalculatedTokenPrice() private view returns (uint256) { uint256 priceReduction = ((block.timestamp - auctionStartTime) / 5 minutes) * 0.1 ether; return auctionStartPrice >= priceReduction ? (auctionStartPrice - priceReduction) : 0; } /// @notice Calculates the current dutch auction price, given accumulated rate deductions and a minimum price. /// @return The current dutch auction price. function getCurrentTokenPrice() public view returns (uint256) { return max(validCalculatedTokenPrice(), 0.01 ether); } /// @notice Returns the price needed for a user to mint the static llamas allocated to him. function getWhitelistPrice() public view returns (uint256) { return staticPrice * staticWhitelist[msg.sender]; } /*/////////////////////////////////////////////////////////////// FREE & WL MINT LOGIC //////////////////////////////////////////////////////////////*/ /// @notice Allows the contract deployer to set the price for static llamas (after the DA). /// @param _staticPrice The new price for a static llama. function setStaticPrice(uint256 _staticPrice) public onlyOwner { staticPrice = _staticPrice; } /// @notice Mints all static llamas allocated to the sender, for use by free minters in the first phase, and WL minters post-auction. function mintStaticLlama() public payable { uint256 count = staticWhitelist[msg.sender]; if (staticSupply + count > staticSupplyCap) revert MintedOut(); if (msg.value < staticPrice * count) revert NotEnoughEther(); unchecked { delete staticWhitelist[msg.sender]; _bulkMint(msg.sender, staticSupply, count); staticSupply += count; } } /// @notice Mints all animated llamas allocated to the sender, for use by free minters in the first phase. function mintAnimatedLlama() public payable { uint256 count = animatedWhitelist[msg.sender]; if (animatedSupply + count > animatedSupplyCap) revert MintedOut(); unchecked { delete animatedWhitelist[msg.sender]; _bulkMint(msg.sender, animatedSupply, count); animatedSupply += count; } } /// @notice Mints all allocated llamas to the sender in one transaction. function bulkMint() public payable { mintAnimatedLlama(); mintStaticLlama(); } /// @notice Mints multiple llamas in bulk. /// @param to The address to transfer minted assets to. /// @param id The token ID of the first llama that will be minted. /// @param count The amount of llamas to be minted. function _bulkMint( address to, uint256 id, uint256 count ) internal { /// @dev We never mint to address(0) so this require is unnecessary. // require(to != address(0), "INVALID_RECIPIENT"); unchecked { balanceOf[to] += count; } for (uint256 i = id; i < id + count; i++) { /// @dev The following require has been removed because the tokens mint in succession and this function is no longer called post mint phase. // require(ownerOf[i] == address(0), "ALREADY_MINTED"); ownerOf[i] = to; emit Transfer(address(0), to, i); } } /// @notice Withdraws collected funds to the contract owner. function withdraw() public onlyOwner { (bool success, ) = msg.sender.call{value: address(this).balance}(""); require(success); } /// @notice Permits the contract owner to roll over unminted animated llamas in case of a failed mint-out. function rollOverAnimated(address wallet) public onlyOwner { uint count = animatedSupplyCap - animatedSupply; _bulkMint(wallet, animatedSupply, count); unchecked { animatedSupply += count; } } /// @notice Permits the contract owner to roll over unminted static llamas in case of a failed mint-out. function rollOverStatic(address wallet) public onlyOwner { uint count = staticSupplyCap - staticSupply; _bulkMint(wallet, staticSupply, count); unchecked { staticSupply += count; } } /*/////////////////////////////////////////////////////////////// UTILS //////////////////////////////////////////////////////////////*/ /// @notice Returns the greater of two numbers. function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public pure override(ERC721, Ownable) returns (bool) { return interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165 interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721 interfaceId == 0x5b5e139f || // ERC165 Interface ID for ERC721Metadata interfaceId == 0x7f5828d0; // ERC165 Interface ID for ERC173 } }
Returns the price needed for a user to mint the static llamas allocated to him.
function getWhitelistPrice() public view returns (uint256) { return staticPrice * staticWhitelist[msg.sender]; } FREE & WL MINT LOGIC
11,861,603
pragma solidity ^0.4.25; /** ================================ Disclaimer: Данный контракт - всего лишь игра и не является профессиональным инструментом заработка. Отнеситесь к этому с забавой, пользуйтесь с умом и не забывайте, что вклад денег в фаст-контракты - это всегда крайне рисково. Мы не призываем людей относится к данному контракту, как к инвестиционному проекту. ================================ Gradual.pro - Плавно растущий и долго живущий умножитель КАЖДЫЙ ДЕНЬ с розыгрыванием ДЖЕКПОТА!, который возвращает 121% от вашего депозита! Маленький лимит на депозит избавляет от проблем с КИТАМИ, которые очень сильно тормозили предыдущую версию контракта и значительно продлевает срок его жизни! Автоматические выплаты! Полные отчеты о потраченых на рекламу средствах в группе! Без ошибок, дыр, автоматический - для выплат НЕ НУЖНА администрация! Создан и проверен профессионалами! Код полностью документирован на русском языке, каждая строчка понятна! Вебсайт: http://gradual.pro/ Канал в телеграмме: https://t.me/gradualpro 1. Пошлите любую ненулевую сумму на адрес контракта - сумма от 0.01 до 1 ETH - gas limit минимум 250000 - вы встанете в очередь 2. Немного подождите 3. ... 4. PROFIT! Вам пришло 121% от вашего депозита. 5. После 21:00 МСК контракт выплачивает 25% от накопленного джекпота последнему вкладчику. 6. Остальной джекпот распределяется всем остальным в обратной очереди по 121% от каждого вклада. 7. Затем очередь обнуляется и запускается заново! Как это возможно? 1. Первый инвестор в очереди (вы станете первым очень скоро) получает выплаты от новых инвесторов до тех пор, пока не получит 121% от своего депозита 2. Выплаты могут приходить несколькими частями или все сразу 3. Как только вы получаете 121% от вашего депозита, вы удаляетесь из очереди 4. Вы можете делать несколько депозитов сразу 5. Баланс этого контракта состовляет сумму джекпота на данный момент! Таким образом, последние платят первым, и инвесторы, достигшие выплат 121% от депозита, удаляются из очереди, уступая место остальным новый инвестор --| совсем новый инвестор --| инвестор5 | новый инвестор | инвестор4 | =======> инвестор5 | инвестор3 | инвестор4 | (част. выплата) инвестор2 <| инвестор3 | (полная выплата) инвестор1 <-| инвестор2 <----| (доплата до 121%) */ contract Restarter { // Время отсроченного старта (timestamp) uint constant public FIRST_START_TIMESTAMP = 1541008800; // Интервал рестарта uint constant public RESTART_INTERVAL = 24 hours; // 24 hours // Адрес кошелька для оплаты рекламы address constant private ADS_SUPPORT = 0x79C188C8d8c7dEc9110c340140F46bE10854E754; // Адрес кошелька для оплаты технической поддержки информационных каналов address constant private TECH_SUPPORT = 0x988f1a2fb17414c95f45E2DAaaA40509F5C9088c; // Процент депозита на рекламу 2% uint constant public ADS_PERCENT = 2; // Процент депозита на тех поддержку 1% uint constant public TECH_PERCENT = 1; // Процент депозита в Джекпот 3% uint constant public JACKPOT_PERCENT = 3; // Процент который перечислится победителю джекпота (последний вкладчик перед рестартом) uint constant public JACKPOT_WINNER_PERCENT = 25; // Процент выплат всем участникам uint constant public MULTIPLIER = 121; // Максимальный размер депозита = 1 эфир, чтобы каждый смог учавстовать и киты не тормозили и не пугали вкладчиков uint constant public MAX_LIMIT = 1 ether; // Минимальный размер депозита = 0.01 эфира uint constant public MIN_LIMIT = 0.01 ether; // Минимальный лимит газа uint constant public MINIMAL_GAS_LIMIT = 250000; // Структура Deposit содержит информацию о депозите struct Deposit { address depositor; // Владелец депозита uint128 deposit; // Сумма депозита uint128 expect; // Сумма выплаты (моментально 121% от депозита) } // Событие, чтобы моментально показывать уведомления на сайте event Restart(uint timestamp); // Очередь Deposit[] private _queue; // Номер обрабатываемого депозита, можно следить в разделе Read contract uint public currentReceiverIndex = 0; // Сумма джекпота uint public jackpotAmount = 0; // Храним время последнего старта, чтобы знать когда делать рестарт uint public lastStartTimestamp; uint public queueCurrentLength = 0; // При создании контракта constructor() public { // Записываем время первого старта lastStartTimestamp = FIRST_START_TIMESTAMP; } // Данная функция получает все депозиты, сохраняет их и производит моментальные выплаты function () public payable { // Проверяем, если отсроченый старт начался require(now >= FIRST_START_TIMESTAMP, "Not started yet!"); // Проверяем минимальный лимит газа, иначе отменяем депозит и возвращаем деньги вкладчику require(gasleft() >= MINIMAL_GAS_LIMIT, "We require more gas!"); // Проверяем максимальную сумму вклада require(msg.value <= MAX_LIMIT, "Deposit is too big!"); // Проверяем минимальную сумму вклада require(msg.value >= MIN_LIMIT, "Deposit is too small!"); // Проверяем, если нужно сделать рестарт if (now >= lastStartTimestamp + RESTART_INTERVAL) { // Записываем время нового рестарта lastStartTimestamp += (now - lastStartTimestamp) / RESTART_INTERVAL * RESTART_INTERVAL; // Выплачиваем Джекпот _payoutJackpot(); _clearQueue(); // Вызываем событие emit Restart(now); } // Добавляем депозит в очередь, записываем что ему нужно выплатить % от суммы депозита _insertQueue(Deposit(msg.sender, uint128(msg.value), uint128(msg.value * MULTIPLIER / 100))); // Увеличиваем Джекпот jackpotAmount += msg.value * JACKPOT_PERCENT / 100; // Отправляем процент на продвижение проекта uint ads = msg.value * ADS_PERCENT / 100; ADS_SUPPORT.transfer(ads); // Отправляем процент на техническую поддержку проекта uint tech = msg.value * TECH_PERCENT / 100; TECH_SUPPORT.transfer(tech); // Вызываем функцию оплаты первым в очереди депозитам _pay(); } // Функция используется для оплаты первым в очереди депозитам // Каждая новая транзация обрабатывает от 1 до 4+ вкладчиков в начале очереди // В зависимости от оставшегося газа function _pay() private { // Попытаемся послать все деньги имеющиеся на контракте первым в очереди вкладчикам за вычетом суммы Джекпота uint128 money = uint128(address(this).balance) - uint128(jackpotAmount); // Проходим по всей очереди for (uint i = 0; i < queueCurrentLength; i++) { // Достаем номер первого в очереди депозита uint idx = currentReceiverIndex + i; // Достаем информацию о первом депозите Deposit storage dep = _queue[idx]; // Если у нас есть достаточно денег для полной выплаты, то выплачиваем ему все if(money >= dep.expect) { // Отправляем ему деньги dep.depositor.transfer(dep.expect); // Обновляем количество оставшихся денег money -= dep.expect; } else { // Попадаем сюда, если у нас не достаточно денег выплатить все, а лишь часть // Отправляем все оставшееся dep.depositor.transfer(money); // Обновляем количество оставшихся денег dep.expect -= money; // Выходим из цикла break; } // Проверяем если еще остался газ, и если его нет, то выходим из цикла if (gasleft() <= 50000) { // Следующий вкладчик осуществит выплату следующим в очереди break; } } // Обновляем номер депозита ставшего первым в очереди currentReceiverIndex += i; } function _payoutJackpot() private { // Попытаемся послать все деньги имеющиеся на контракте первым в очереди вкладчикам за вычетом суммы Джекпота uint128 money = uint128(jackpotAmount); // Перечисляем 25% с джекпота победителю Deposit storage dep = _queue[queueCurrentLength - 1]; dep.depositor.transfer(uint128(jackpotAmount * JACKPOT_WINNER_PERCENT / 100)); money -= uint128(jackpotAmount * JACKPOT_WINNER_PERCENT / 100); // Проходим по всей очереди с конца for (uint i = queueCurrentLength - 2; i < queueCurrentLength && i >= currentReceiverIndex; i--) { // Достаем информацию о последнем депозите dep = _queue[i]; // Если у нас есть достаточно денег для полной выплаты, то выплачиваем ему все if(money >= dep.expect) { // Отправляем ему деньги dep.depositor.transfer(dep.expect); // Обновляем количество оставшихся денег money -= dep.expect; } else if (money > 0) { // Попадаем сюда, если у нас не достаточно денег выплатить все, а лишь часть // Отправляем все оставшееся dep.depositor.transfer(money); // Обновляем количество оставшихся денег dep.expect -= money; money = 0; } else { break; } } // Обнуляем джекпот на новый раунд jackpotAmount = 0; // Обнуляем очередь currentReceiverIndex = 0; } function _insertQueue(Deposit deposit) private { if (queueCurrentLength == _queue.length) { _queue.length += 1; } _queue[queueCurrentLength++] = deposit; } function _clearQueue() private { queueCurrentLength = 0; } // Показывает информацию о депозите по его номеру (idx), можно следить в разделе Read contract // Вы можете получить номер депозита (idx) вызвав функцию getDeposits() function getDeposit(uint idx) public view returns (address depositor, uint deposit, uint expect){ Deposit storage dep = _queue[idx]; return (dep.depositor, dep.deposit, dep.expect); } // Показывает количество вкладов определенного инвестора function getDepositsCount(address depositor) public view returns (uint) { uint c = 0; for(uint i=currentReceiverIndex; i < queueCurrentLength; ++i){ if(_queue[i].depositor == depositor) c++; } return c; } // Показывает все депозиты (index, deposit, expect) определенного инвестора, можно следить в разделе Read contract function getDeposits(address depositor) public view returns (uint[] idxs, uint128[] deposits, uint128[] expects) { uint c = getDepositsCount(depositor); idxs = new uint[](c); deposits = new uint128[](c); expects = new uint128[](c); if(c > 0) { uint j = 0; for(uint i = currentReceiverIndex; i < queueCurrentLength; ++i){ Deposit storage dep = _queue[i]; if(dep.depositor == depositor){ idxs[j] = i; deposits[j] = dep.deposit; expects[j] = dep.expect; j++; } } } } // Показывает длинну очереди, можно следить в разделе Read contract function getQueueLength() public view returns (uint) { return queueCurrentLength - currentReceiverIndex; } }
Показывает все депозиты (index, deposit, expect) определенного инвестора, можно следить в разделе Read contract
function getDeposits(address depositor) public view returns (uint[] idxs, uint128[] deposits, uint128[] expects) { uint c = getDepositsCount(depositor); idxs = new uint[](c); deposits = new uint128[](c); expects = new uint128[](c); if(c > 0) { uint j = 0; for(uint i = currentReceiverIndex; i < queueCurrentLength; ++i){ Deposit storage dep = _queue[i]; if(dep.depositor == depositor){ idxs[j] = i; deposits[j] = dep.deposit; expects[j] = dep.expect; j++; } } } }
12,657,355
pragma solidity ^0.5.0; import '../math/SafeMath.sol'; import '../token/IERC777.sol'; /** * @title FixedPriceSeller * * An ERC777 token operator contract that sells tokens at a fixed price. * * State of this contract: stable; development complete but the code is * unaudited. and may contain bugs and/or security holes. Use at your own * risk. * * @author Jim McDonald * @notice If you use this contract please consider donating some Ether or * some of your ERC-777 token to wsl.wealdtech.eth to support continued * development of these and future contracts */ contract FixedPriceSeller { using SafeMath for uint256; // Mapping is token=>holder=>price per token mapping(address=>mapping(address=>uint256)) pricePerToken; event PricePerToken(address token, address holder, uint256 pricePerToken); /** * Set the price for each token. The price is in Wei, so if for example * the price is 1 Ether for 1 token then _pricePerToken would be 10^18. */ function setPricePerToken(IERC777 _token, uint256 _pricePerToken) public { pricePerToken[address(_token)][msg.sender] = _pricePerToken; emit PricePerToken(address(_token), msg.sender, _pricePerToken); } /** * Get the price for each token. The price is in Wei, so if for example * the price is 1 Ether for 1 token this would return 10^18. */ function getPricePerToken(IERC777 _token, address _holder) public view returns (uint256) { return pricePerToken[address(_token)][_holder]; } /** * Send tokens from a holder at their price */ function send(IERC777 _token, address payable _holder) public payable { uint256 amount = preSend(_token, _holder); _token.operatorSend(_holder, msg.sender, amount, "", ""); postSend(_holder); } /** * Checks and state update to carry out prior to sending tokens */ function preSend(IERC777 _token, address _holder) internal view returns (uint256) { require(pricePerToken[address(_token)][_holder] != 0, "not for sale"); uint256 amount = msg.value.mul(1000000000000000000).div(pricePerToken[address(_token)][_holder]); require(amount > _token.granularity(), "not enough ether paid"); uint256 value = amount.mul(pricePerToken[address(_token)][_holder]).div(1000000000000000000); require(value == msg.value, "non-integer number of tokens purchased"); return amount; } /** * State update to carry out after sending tokens */ function postSend(address payable _holder) internal { _holder.transfer(msg.value); } }
Set the price for each token. The price is in Wei, so if for example the price is 1 Ether for 1 token then _pricePerToken would be 10^18./
function setPricePerToken(IERC777 _token, uint256 _pricePerToken) public { pricePerToken[address(_token)][msg.sender] = _pricePerToken; emit PricePerToken(address(_token), msg.sender, _pricePerToken); }
7,240,890
pragma solidity 0.4.24; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./lib/Withdrawable.sol"; import "./TraceToMetaInfoInterface.sol"; /** * @title TraceToMetaInfo * @dev This contract is for sharing meta data for other traceto contracts * It additionally allows us to update the smart contracts and provides a migration path */ contract TraceToMetaInfo is Withdrawable, TraceToMetaInfoInterface{ using SafeMath for uint256; address public token; address public requestorWL; address public spWL; address public spRMIWL; address public verifierWL; address public unlockProfile; uint256 public SPPercentage; uint256 public VerifierPercentage; uint256 public minimalStakeAmount; string public uriForInfoTemplate; string public hashForInfoTemplate; /** * @dev constructor of this contract, it will transfer ownership and fix the t2t token address * @param owner Owner of this contract * @param _token t2t token address */ constructor(address owner, address _token) public { transferOwnership(owner); // tier 3 Verifier should own this contract token = _token; } /** * @dev set verifier whitelist contract * @param _VerifierWL the address of verifier whitelist contract */ function setVerifierWL(address _VerifierWL) public onlyOwner { verifierWL = _VerifierWL; } /** * @dev set requestor whitelist contract * @param _RequestorWL the address of requestor whitelist contract */ function setRequestorWL(address _RequestorWL) public onlyOwner { requestorWL = _RequestorWL; } /** * @dev set service provider whitelist contract * @param _SPWL the address of service provider whitelist contract */ function setSPWL(address _SPWL) public onlyOwner { spWL = _SPWL; } /** * @dev set service provider whitelist contract * @param _SPRMIWL the address of RMI service provider whitelist contract */ function setRMISPWL(address _SPRMIWL) public onlyOwner { spRMIWL = _SPRMIWL; } /** * @dev set unlock profile contract * @param _UPcontract the address of unlock profile contract */ function setUnlockProfile(address _UPcontract) public onlyOwner { unlockProfile = _UPcontract; } /** * @dev set proportion for how much token will transfer to service provider * @notice this is part of the tokenomics and its the proportion per service the amounts that * will be taken by the Service Provider * @param _SPPercentage the percentage of costs for service provider */ function setSPPercentage(uint256 _SPPercentage) public onlyOwner { require(_SPPercentage.add(VerifierPercentage) < 90); SPPercentage = _SPPercentage; } /** * @dev set proportion for how much token will transfer to verifier * @notice this is the percentage that will be taken by the verifier's. The remaining is * what will be utilized by the contract owner for updating the system in the future. * @param _VerifierPercentage the percentage for verifier */ function setVerifierPercentage(uint256 _VerifierPercentage) public onlyOwner { require(_VerifierPercentage.add(SPPercentage) < 90); VerifierPercentage = _VerifierPercentage; } /** * @dev set amount for how much token verifiers need to deposit before joining * @param _minimalStakeAmount the amount of USDT */ function setMinimalStakeAmount(uint256 _minimalStakeAmount) public onlyOwner { minimalStakeAmount = _minimalStakeAmount; } /** * @dev set the infomation template, example gist at * https://gist.github.com/tracetoio-dias/f651ff0a3de0970cc87e09d8058071db * @param _uriForInfoTemplate the IPFS link for Info template * @param _hashForInfoTemplate the hash of the JSON object */ function setInfoTemplate(string _uriForInfoTemplate, string _hashForInfoTemplate) public onlyOwner { uriForInfoTemplate = _uriForInfoTemplate; hashForInfoTemplate = _hashForInfoTemplate; } /** * @dev get T2T token contract * @return _t2tContract the address of t2t token contract */ function getTokenContract() public view returns (address _t2tContract) { return token; } /** * @dev get verifier whitelist contract * @return _VerifierWL the address of verifier whitelist contract */ function getVerifierWL() public view returns (address _VerifierWL) { return verifierWL; } /** * @dev get requestor whitelist contract * @return _RequestorWL the address of requestor whitelist contract */ function getRequestorWL() public view returns (address _RequestorWL) { return requestorWL; } /** * @dev get service provider whitelist contract * @return _SPWL the address of service provider whitelist contract */ function getSPWL() public view returns (address _SPWL) { return spWL; } /** * @dev get service provider whitelist contract * @return _SPRMIWL the address of RMI service provider whitelist contract */ function getRMISPWL() public view returns (address _SPRMIWL) { return spRMIWL; } /** * @dev get unlock profile contract * @return _UPcontract the address of unlock profile contract */ function getUnlockProfile() public view returns (address _UPcontract) { return unlockProfile; } /** * @dev get proportion for how much token will transfer to service provider * @return _SPPercentage the percentage for service provider */ function getSPPercentage() public view returns (uint256 _SPPercentage) { return SPPercentage; } /** * @dev get proportion for how much token will transfer to verifier * @return _VerifierPercentage the percentage for verifier */ function getVerifierPercentage() public view returns (uint256 _VerifierPercentage) { return VerifierPercentage; } /** * @dev get amount for how much token verifiers need to deposit before joining * @return _minimalStakeAmount the amount of usdt */ function getMinimalStakeAmount() public view returns (uint256 _minimalStakeAmount) { return minimalStakeAmount; } /** * @dev get the infomation template * @return _uriForInfoTemplate the IPFS link for Info template * @return _hashForInfoTemplate the hash of the JSON object */ function getInfoTemplate() public view returns (string _uriForInfoTemplate, string _hashForInfoTemplate) { return (uriForInfoTemplate, hashForInfoTemplate); } }
get requestor whitelist contract return _RequestorWL the address of requestor whitelist contract/
function getRequestorWL() public view returns (address _RequestorWL) { return requestorWL; }
7,242,107
./full_match/43114/0x9bF819e9c103F5197D64A86Fb9d89b8D8Aa4e69e/sources/QuantumFinance.sol
Delegates votes from signatory to `delegatee` delegatee The address to delegate votes to nonce The contract state required to match the signature expiry The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair s Half of the ECDSA signature pair/
function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Quant::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Quant::delegateBySig: invalid nonce"); require(now <= expiry, "Quant::delegateBySig: signature expired"); return _delegate(signatory, delegatee); }
4,568,557
// SPDX-License-Identifier: MIT pragma solidity >=0.6.12; interface IERC20 { function TOTALSUPPLY622() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF753(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER955(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE76(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE213(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM690(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER649(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL691(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER876(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN191(token, abi.encodeWithSelector(token.TRANSFER955.selector, to, value)); } function SAFETRANSFERFROM621(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN191(token, abi.encodeWithSelector(token.TRANSFERFROM690.selector, from, to, value)); } function SAFEAPPROVE2(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // 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.ALLOWANCE76(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN191(token, abi.encodeWithSelector(token.APPROVE213.selector, spender, value)); } function SAFEINCREASEALLOWANCE52(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE76(address(this), spender).ADD393(value); _CALLOPTIONALRETURN191(token, abi.encodeWithSelector(token.APPROVE213.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE172(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE76(address(this), spender).SUB829(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN191(token, abi.encodeWithSelector(token.APPROVE213.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN191(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // 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).FUNCTIONCALL585(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface IWETH { function DEPOSIT379() external payable; //inject NONSTANDARD NAMING function TRANSFER955(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function WITHDRAW91(uint) external; //inject NONSTANDARD NAMING } interface IUniswapV2Router01 { function FACTORY423() external pure returns (address); //inject NONSTANDARD NAMING function WETH656() external pure returns (address); //inject NONSTANDARD NAMING function ADDLIQUIDITY566( //inject NONSTANDARD NAMING 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 ADDLIQUIDITYETH439( //inject NONSTANDARD NAMING address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function REMOVELIQUIDITY294( //inject NONSTANDARD NAMING address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function REMOVELIQUIDITYETH142( //inject NONSTANDARD NAMING address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function REMOVELIQUIDITYWITHPERMIT785( //inject NONSTANDARD NAMING 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 REMOVELIQUIDITYETHWITHPERMIT822( //inject NONSTANDARD NAMING 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 SWAPEXACTTOKENSFORTOKENS694( //inject NONSTANDARD NAMING uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function SWAPTOKENSFOREXACTTOKENS112( //inject NONSTANDARD NAMING uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function SWAPEXACTETHFORTOKENS23(uint amountOutMin, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING external payable returns (uint[] memory amounts); function SWAPTOKENSFOREXACTETH134(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING external returns (uint[] memory amounts); function SWAPEXACTTOKENSFORETH465(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING external returns (uint[] memory amounts); function SWAPETHFOREXACTTOKENS477(uint amountOut, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING external payable returns (uint[] memory amounts); function QUOTE151(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); //inject NONSTANDARD NAMING function GETAMOUNTOUT667(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); //inject NONSTANDARD NAMING function GETAMOUNTIN118(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); //inject NONSTANDARD NAMING function GETAMOUNTSOUT962(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); //inject NONSTANDARD NAMING function GETAMOUNTSIN769(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); //inject NONSTANDARD NAMING } interface IUniswapV2Router02 is IUniswapV2Router01 { function REMOVELIQUIDITYETHSUPPORTINGFEEONTRANSFERTOKENS84( //inject NONSTANDARD NAMING address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function REMOVELIQUIDITYETHWITHPERMITSUPPORTINGFEEONTRANSFERTOKENS171( //inject NONSTANDARD NAMING 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 SWAPEXACTTOKENSFORTOKENSSUPPORTINGFEEONTRANSFERTOKENS513( //inject NONSTANDARD NAMING uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function SWAPEXACTETHFORTOKENSSUPPORTINGFEEONTRANSFERTOKENS617( //inject NONSTANDARD NAMING uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function SWAPEXACTTOKENSFORETHSUPPORTINGFEEONTRANSFERTOKENS347( //inject NONSTANDARD NAMING uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } interface IUniswapV2Pair { event APPROVAL691(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING event TRANSFER649(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING function NAME590() external pure returns (string memory); //inject NONSTANDARD NAMING function SYMBOL603() external pure returns (string memory); //inject NONSTANDARD NAMING function DECIMALS715() external pure returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY622() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF753(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE76(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE213(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER955(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM690(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function DOMAIN_SEPARATOR647() external view returns (bytes32); //inject NONSTANDARD NAMING function PERMIT_TYPEHASH618() external pure returns (bytes32); //inject NONSTANDARD NAMING function NONCES61(address owner) external view returns (uint); //inject NONSTANDARD NAMING function PERMIT398(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING event MINT816(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING event BURN577(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING event SWAP591( //inject NONSTANDARD NAMING address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event SYNC313(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING function MINIMUM_LIQUIDITY897() external pure returns (uint); //inject NONSTANDARD NAMING function FACTORY423() external view returns (address); //inject NONSTANDARD NAMING function TOKEN0588() external view returns (address); //inject NONSTANDARD NAMING function TOKEN1553() external view returns (address); //inject NONSTANDARD NAMING function GETRESERVES947() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING function PRICE0CUMULATIVELAST382() external view returns (uint); //inject NONSTANDARD NAMING function PRICE1CUMULATIVELAST280() external view returns (uint); //inject NONSTANDARD NAMING function KLAST968() external view returns (uint); //inject NONSTANDARD NAMING function MINT750(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING function BURN945(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING function SWAP412(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING function SKIM546(address to) external; //inject NONSTANDARD NAMING function SYNC14() external; //inject NONSTANDARD NAMING function INITIALIZE840(address, address) external; //inject NONSTANDARD NAMING } interface IUniswapV2Factory { event PAIRCREATED444(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING function FEETO98() external view returns (address); //inject NONSTANDARD NAMING function FEETOSETTER656() external view returns (address); //inject NONSTANDARD NAMING function MIGRATOR786() external view returns (address); //inject NONSTANDARD NAMING function GETPAIR761(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRS341(uint) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRSLENGTH448() external view returns (uint); //inject NONSTANDARD NAMING function CREATEPAIR119(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING function SETFEETO526(address) external; //inject NONSTANDARD NAMING function SETFEETOSETTER51(address) external; //inject NONSTANDARD NAMING function SETMIGRATOR114(address) external; //inject NONSTANDARD NAMING } 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_entered266 = 1; //inject NONSTANDARD NAMING uint256 private constant _entered280 = 2; //inject NONSTANDARD NAMING uint256 private _status; constructor () internal { _status = _not_entered266; } modifier NONREENTRANT384() { //inject NONSTANDARD NAMING // On the first call to nonReentrant, _notEntered will be true require(_status != _entered280, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _entered280; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _not_entered266; } } library Math { function MAX80(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a >= b ? a : b; } function MIN629(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a < b ? a : b; } function AVERAGE241(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } library Address { function ISCONTRACT204(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } function SENDVALUE55(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function FUNCTIONCALL585(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALL585(target, data, "Address: low-level call failed"); } function FUNCTIONCALL585(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING return _FUNCTIONCALLWITHVALUE394(target, data, 0, errorMessage); } function FUNCTIONCALLWITHVALUE130(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALLWITHVALUE130(target, data, value, "Address: low-level call with value failed"); } function FUNCTIONCALLWITHVALUE130(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING require(address(this).balance >= value, "Address: insufficient balance for call"); return _FUNCTIONCALLWITHVALUE394(target, data, value, errorMessage); } function _FUNCTIONCALLWITHVALUE394(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING require(ISCONTRACT204(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } library SafeMath { function ADD393(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB829(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB829(a, b, "SafeMath: subtraction overflow"); } function SUB829(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL131(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV283(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV283(a, b, "SafeMath: division by zero"); } function DIV283(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD208(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD208(a, b, "SafeMath: modulo by zero"); } function MOD208(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library MathUtils { using SafeMath for uint256; function SQRT196(uint256 x) internal pure returns (uint256 y) { //inject NONSTANDARD NAMING uint256 z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } function ROUNDEDDIV172(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, 'div by 0'); uint256 halfB = (b.MOD208(2) == 0) ? (b.DIV283(2)) : (b.DIV283(2).ADD393(1)); return (a.MOD208(b) >= halfB) ? (a.DIV283(b).ADD393(1)) : (a.DIV283(b)); } } interface IUniswapV2ERC20 { event APPROVAL691(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING event TRANSFER649(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING function NAME590() external pure returns (string memory); //inject NONSTANDARD NAMING function SYMBOL603() external pure returns (string memory); //inject NONSTANDARD NAMING function DECIMALS715() external pure returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY622() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF753(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE76(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE213(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER955(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM690(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function DOMAIN_SEPARATOR647() external view returns (bytes32); //inject NONSTANDARD NAMING function PERMIT_TYPEHASH618() external pure returns (bytes32); //inject NONSTANDARD NAMING function NONCES61(address owner) external view returns (uint); //inject NONSTANDARD NAMING function PERMIT398(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING } interface IUniswapV2Callee { function UNISWAPV2CALL695(address sender, uint amount0, uint amount1, bytes calldata data) external; //inject NONSTANDARD NAMING } interface IERC20Uniswap { event APPROVAL691(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING event TRANSFER649(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING function NAME590() external view returns (string memory); //inject NONSTANDARD NAMING function SYMBOL603() external view returns (string memory); //inject NONSTANDARD NAMING function DECIMALS715() external view returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY622() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF753(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE76(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE213(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER955(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM690(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING } abstract contract Context { function _MSGSENDER27() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA543() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } 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; constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } function NAME590() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL603() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS715() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } function TOTALSUPPLY622() public view override returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF753(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER955(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER21(_MSGSENDER27(), recipient, amount); return true; } function ALLOWANCE76(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE213(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _APPROVE77(_MSGSENDER27(), spender, amount); return true; } function TRANSFERFROM690(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER21(sender, recipient, amount); _APPROVE77(sender, _MSGSENDER27(), _allowances[sender][_MSGSENDER27()].SUB829(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE203(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE77(_MSGSENDER27(), spender, _allowances[_MSGSENDER27()][spender].ADD393(addedValue)); return true; } function DECREASEALLOWANCE568(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE77(_MSGSENDER27(), spender, _allowances[_MSGSENDER27()][spender].SUB829(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER21(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _BEFORETOKENTRANSFER156(sender, recipient, amount); _balances[sender] = _balances[sender].SUB829(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD393(amount); emit TRANSFER649(sender, recipient, amount); } function _MINT693(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _BEFORETOKENTRANSFER156(address(0), account, amount); _totalSupply = _totalSupply.ADD393(amount); _balances[account] = _balances[account].ADD393(amount); emit TRANSFER649(address(0), account, amount); } function _BURN313(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _BEFORETOKENTRANSFER156(account, address(0), amount); _balances[account] = _balances[account].SUB829(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB829(amount); emit TRANSFER649(account, address(0), amount); } function _APPROVE77(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit APPROVAL691(owner, spender, amount); } function _SETUPDECIMALS749(uint8 decimals_) internal { //inject NONSTANDARD NAMING _decimals = decimals_; } function _BEFORETOKENTRANSFER156(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING } contract WETH9 { string public name = "Wrapped Ether"; string public symbol = "WETH"; uint8 public decimals = 18; event APPROVAL691(address indexed src, address indexed guy, uint wad); //inject NONSTANDARD NAMING event TRANSFER649(address indexed src, address indexed dst, uint wad); //inject NONSTANDARD NAMING event DEPOSIT981(address indexed dst, uint wad); //inject NONSTANDARD NAMING event WITHDRAWAL378(address indexed src, uint wad); //inject NONSTANDARD NAMING mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; receive() external payable { DEPOSIT379(); } function DEPOSIT379() public payable { //inject NONSTANDARD NAMING balanceOf[msg.sender] += msg.value; DEPOSIT981(msg.sender, msg.value); } function WITHDRAW91(uint wad) public { //inject NONSTANDARD NAMING require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; msg.sender.transfer(wad); WITHDRAWAL378(msg.sender, wad); } function TOTALSUPPLY622() public view returns (uint) { //inject NONSTANDARD NAMING return address(this).balance; } function APPROVE213(address guy, uint wad) public returns (bool) { //inject NONSTANDARD NAMING allowance[msg.sender][guy] = wad; APPROVAL691(msg.sender, guy, wad); return true; } function TRANSFER955(address dst, uint wad) public returns (bool) { //inject NONSTANDARD NAMING return TRANSFERFROM690(msg.sender, dst, wad); } function TRANSFERFROM690(address src, address dst, uint wad) //inject NONSTANDARD NAMING public returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != uint(- 1)) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; TRANSFER649(src, dst, wad); return true; } } contract twis is ERC20 { address minter; modifier ONLYMINTER285 { //inject NONSTANDARD NAMING require(msg.sender == minter, 'Only minter can call this function.'); _; } constructor(address _minter) public ERC20('Twister', 'TWIS') { minter = _minter; } function MINT750(address account, uint256 amount) external ONLYMINTER285 { //inject NONSTANDARD NAMING _MINT693(account, amount); } function BURN945(address account, uint256 amount) external ONLYMINTER285 { //inject NONSTANDARD NAMING _BURN313(account, amount); } } contract Twister is ReentrancyGuard { using SafeMath for uint256; using Address for address; using SafeERC20 for IERC20; event STAKED534(address indexed from, uint256 amountETH, uint256 amountLP); //inject NONSTANDARD NAMING event WITHDRAWN851(address indexed to, uint256 amountETH, uint256 amountLP); //inject NONSTANDARD NAMING event CLAIMED515(address indexed to, uint256 amount); //inject NONSTANDARD NAMING event HALVING833(uint256 amount); //inject NONSTANDARD NAMING event RECEIVED501(address indexed from, uint256 amount); //inject NONSTANDARD NAMING twis public token; IUniswapV2Factory public factory; IUniswapV2Router02 public router; address public weth; address payable public treasury; address public pairAddress; struct AccountInfo { // Staked LP token balance uint256 balance; uint256 peakBalance; uint256 withdrawTimestamp; uint256 reward; uint256 rewardPerTokenPaid; } mapping(address => AccountInfo) public accountInfos; // Staked LP token total supply uint256 private _totalSupply = 0; uint256 public constant halving_duration255 = 7 days; //inject NONSTANDARD NAMING uint256 public rewardAllocation = 1500 * 1e18; uint256 public halvingTimestamp = 0; uint256 public lastUpdateTimestamp = 0; uint256 public rewardRate = 0; uint256 public rewardPerTokenStored = 0; // Farming will be open on this timestamp // Date and time (GMT): Monday, October 26, 2020 3:00:00 PM uint256 public farmingStartTimestamp = 1604635200; bool public farmingStarted = false; // Max 10% / day LP withdraw uint256 public constant withdraw_limit638 = 10; //inject NONSTANDARD NAMING // Burn address address constant burn_address389 = 0x000000000000000000000000000000000000dEaD; //inject NONSTANDARD NAMING // Dev decided to launch without whitelist but since it has been coded and tested, so dev will leave it here. // Whitelisted address mapping (address => bool) public whitelists; // Whitelist deposited balance mapping (address => uint256) public whitelistBalance; // End period for whitelist advantage uint256 public whitelistEndTimestamp = 0; // Max stake for whitelist uint256 public constant whitelist_stake_limit67 = 3 ether; //inject NONSTANDARD NAMING // Whitelist advantage duration (reduced to 1 minutes since we dont have whitelist) uint256 public constant whitelist_duration869 = 1 minutes; //inject NONSTANDARD NAMING constructor(address _routerAddress, address[] memory _whitelists) public { token = new twis(address(this)); router = IUniswapV2Router02(_routerAddress); factory = IUniswapV2Factory(router.FACTORY423()); weth = router.WETH656(); treasury = msg.sender; pairAddress = factory.CREATEPAIR119(address(token), weth); // Calc reward rate rewardRate = rewardAllocation.DIV283(halving_duration255); // Init whitelist _SETUPWHITELISTS161(_whitelists); whitelistEndTimestamp = farmingStartTimestamp.ADD393(whitelist_duration869); } receive() external payable { emit RECEIVED501(msg.sender, msg.value); } function STAKE961() external payable NONREENTRANT384 { //inject NONSTANDARD NAMING _CHECKFARMING62(); _UPDATEREWARD485(msg.sender); _HALVING349(); require(msg.value > 0, 'Cannot stake 0'); require(!address(msg.sender).ISCONTRACT204(), 'Please use your individual account'); // If we are still in whitelist duration if (whitelistEndTimestamp >= block.timestamp) { require(whitelists[msg.sender], 'Only whitelisted address can stake right now'); whitelistBalance[msg.sender] = whitelistBalance[msg.sender].ADD393(msg.value); require(whitelistBalance[msg.sender] <= whitelist_stake_limit67, 'Cannot stake more than allowed in whitelist period'); } // 10% compensation fee // since dev doesn't hold any initial supply uint256 fee = msg.value.DIV283(10); uint256 amount = msg.value.SUB829(fee); treasury.transfer(fee); uint256 ethAmount = IERC20(weth).BALANCEOF753(pairAddress); uint256 tokenAmount = IERC20(token).BALANCEOF753(pairAddress); // If eth amount = 0 then set initial price to 1 eth = 2 twis uint256 amountTokenDesired = ethAmount == 0 ? (amount * 2) : amount.MUL131(tokenAmount).DIV283(ethAmount); // Mint borrowed twis token.MINT750(address(this), amountTokenDesired); // Add liquidity in uniswap uint256 amountETHDesired = amount; IERC20(token).APPROVE213(address(router), amountTokenDesired); (,, uint256 liquidity) = router.ADDLIQUIDITYETH439{value : amountETHDesired}(address(token), amountTokenDesired, 1, 1, address(this), block.timestamp + 1 days); // Add LP token to total supply _totalSupply = _totalSupply.ADD393(liquidity); // Add to balance accountInfos[msg.sender].balance = accountInfos[msg.sender].balance.ADD393(liquidity); // Set peak balance if (accountInfos[msg.sender].balance > accountInfos[msg.sender].peakBalance) { accountInfos[msg.sender].peakBalance = accountInfos[msg.sender].balance; } // Set stake timestamp as withdraw timestamp // to prevent withdraw immediately after first staking if (accountInfos[msg.sender].withdrawTimestamp == 0) { accountInfos[msg.sender].withdrawTimestamp = block.timestamp; } emit STAKED534(msg.sender, msg.value, liquidity); } function WITHDRAW91() external NONREENTRANT384 { //inject NONSTANDARD NAMING _CHECKFARMING62(); _UPDATEREWARD485(msg.sender); _HALVING349(); require(accountInfos[msg.sender].withdrawTimestamp + 1 days <= block.timestamp, 'You must wait 1 day since your last withdraw or stake'); require(accountInfos[msg.sender].balance > 0, 'Cannot withdraw 0'); // Limit withdraw LP token uint256 amount = accountInfos[msg.sender].peakBalance.DIV283(withdraw_limit638); if (accountInfos[msg.sender].balance < amount) { amount = accountInfos[msg.sender].balance; } // Reduce total supply _totalSupply = _totalSupply.SUB829(amount); // Reduce balance accountInfos[msg.sender].balance = accountInfos[msg.sender].balance.SUB829(amount); // Set timestamp accountInfos[msg.sender].withdrawTimestamp = block.timestamp; // Remove liquidity in uniswap IERC20(pairAddress).APPROVE213(address(router), amount); (uint256 tokenAmount, uint256 ethAmount) = router.REMOVELIQUIDITY294(address(token), weth, amount, 0, 0, address(this), block.timestamp + 1 days); // Burn borrowed twis token.BURN945(address(this), tokenAmount); // Withdraw ETH and send to sender IWETH(weth).WITHDRAW91(ethAmount); msg.sender.transfer(ethAmount); emit WITHDRAWN851(msg.sender, ethAmount, amount); } function CLAIM763() external NONREENTRANT384 { //inject NONSTANDARD NAMING _CHECKFARMING62(); _UPDATEREWARD485(msg.sender); _HALVING349(); uint256 reward = accountInfos[msg.sender].reward; require(reward > 0, 'There is no reward to claim'); if (reward > 0) { // Reduce first accountInfos[msg.sender].reward = 0; // Apply tax uint256 taxDenominator = CLAIMTAXDENOMINATOR467(); uint256 tax = taxDenominator > 0 ? reward.DIV283(taxDenominator) : 0; uint256 net = reward.SUB829(tax); // Send reward token.MINT750(msg.sender, net); if (tax > 0) { // Burn taxed token token.MINT750(burn_address389, tax); } emit CLAIMED515(msg.sender, reward); } } function TOTALSUPPLY622() external view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF753(address account) external view returns (uint256) { //inject NONSTANDARD NAMING return accountInfos[account].balance; } function BURNEDTOKENAMOUNT890() public view returns (uint256) { //inject NONSTANDARD NAMING return token.BALANCEOF753(burn_address389); } function REWARDPERTOKEN638() public view returns (uint256) { //inject NONSTANDARD NAMING if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored .ADD393( LASTREWARDTIMESTAMP705() .SUB829(lastUpdateTimestamp) .MUL131(rewardRate) .MUL131(1e18) .DIV283(_totalSupply) ); } function LASTREWARDTIMESTAMP705() public view returns (uint256) { //inject NONSTANDARD NAMING return Math.MIN629(block.timestamp, halvingTimestamp); } function REWARDEARNED380(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return accountInfos[account].balance.MUL131( REWARDPERTOKEN638().SUB829(accountInfos[account].rewardPerTokenPaid) ) .DIV283(1e18) .ADD393(accountInfos[account].reward); } // Token price in eth function TOKENPRICE205() public view returns (uint256) { //inject NONSTANDARD NAMING uint256 ethAmount = IERC20(weth).BALANCEOF753(pairAddress); uint256 tokenAmount = IERC20(token).BALANCEOF753(pairAddress); return tokenAmount > 0 ? // Current price ethAmount.MUL131(1e18).DIV283(tokenAmount) : // Initial price (uint256(1e18).DIV283(2)); } function CLAIMTAXDENOMINATOR467() public view returns (uint256) { //inject NONSTANDARD NAMING if (block.timestamp < farmingStartTimestamp + 1 days) { return 4; } else if (block.timestamp < farmingStartTimestamp + 2 days) { return 5; } else if (block.timestamp < farmingStartTimestamp + 3 days) { return 10; } else if (block.timestamp < farmingStartTimestamp + 4 days) { return 20; } else { return 0; } } function _UPDATEREWARD485(address account) internal { //inject NONSTANDARD NAMING rewardPerTokenStored = REWARDPERTOKEN638(); lastUpdateTimestamp = LASTREWARDTIMESTAMP705(); if (account != address(0)) { accountInfos[account].reward = REWARDEARNED380(account); accountInfos[account].rewardPerTokenPaid = rewardPerTokenStored; } } // Do halving when timestamp reached function _HALVING349() internal { //inject NONSTANDARD NAMING if (block.timestamp >= halvingTimestamp) { rewardAllocation = rewardAllocation.DIV283(2); rewardRate = rewardAllocation.DIV283(halving_duration255); halvingTimestamp = halvingTimestamp.ADD393(halving_duration255); _UPDATEREWARD485(msg.sender); emit HALVING833(rewardAllocation); } } // Check if farming is started function _CHECKFARMING62() internal { //inject NONSTANDARD NAMING require(farmingStartTimestamp <= block.timestamp, 'Please wait until farming started'); if (!farmingStarted) { farmingStarted = true; halvingTimestamp = block.timestamp.ADD393(halving_duration255); lastUpdateTimestamp = block.timestamp; } } function _SETUPWHITELISTS161(address[] memory addresses) internal { //inject NONSTANDARD NAMING for (uint256 i = 0; i < addresses.length; i++) { whitelists[addresses[i]] = true; } } }
inject NONSTANDARD NAMING
function TRANSFER955(address to, uint value) external returns (bool);
12,607,324
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (governance/extensions/GovernorSettings.sol) pragma solidity ^0.8.0; import "../Governor.sol"; import "../../utils/Timers.sol"; /** * @dev Extension of {Governor} for settings updatable through governance. * * _Available since v4.4._ */ abstract contract GovernorSettings is Governor { uint256 private _contestStart; uint256 private _votingDelay; uint256 private _votingPeriod; uint256 private _contestSnapshot; uint256 private _proposalThreshold; uint256 private _numAllowedProposalSubmissions; uint256 private _maxProposalCount; address private _creator; event ContestStartSet(uint256 oldContestStart, uint256 newContestStart); event VotingDelaySet(uint256 oldVotingDelay, uint256 newVotingDelay); event VotingPeriodSet(uint256 oldVotingPeriod, uint256 newVotingPeriod); event ContestSnapshotSet(uint256 oldContestSnapshot, uint256 newContestSnapshot); event ProposalThresholdSet(uint256 oldProposalThreshold, uint256 newProposalThreshold); event NumAllowedProposalSubmissionsSet(uint256 oldNumAllowedProposalSubmissions, uint256 newNumAllowedProposalSubmissions); event MaxProposalCountSet(uint256 oldMaxProposalCount, uint256 newMaxProposalCount); event CreatorSet(address oldCreator, address newCreator); /** * @dev Initialize the governance parameters. */ constructor( uint256 initialContestStart, uint256 initialVotingDelay, uint256 initialVotingPeriod, uint256 initialContestSnapshot, uint256 initialProposalThreshold, uint256 initialNumAllowedProposalSubmissions, uint256 initialMaxProposalCount ) { _setContestStart(initialContestStart); _setVotingDelay(initialVotingDelay); _setVotingPeriod(initialVotingPeriod); _setContestSnapshot(initialContestSnapshot); _setProposalThreshold(initialProposalThreshold); _setNumAllowedProposalSubmissions(initialNumAllowedProposalSubmissions); _setMaxProposalCount(initialMaxProposalCount); _setCreator(msg.sender); } /** * @dev See {IGovernor-contestStart}. */ function contestStart() public view virtual override returns (uint256) { return _contestStart; } /** * @dev See {IGovernor-votingDelay}. */ function votingDelay() public view virtual override returns (uint256) { return _votingDelay; } /** * @dev See {IGovernor-votingPeriod}. */ function votingPeriod() public view virtual override returns (uint256) { return _votingPeriod; } /** * @dev See {IGovernor-contestSnapshot}. */ function contestSnapshot() public view virtual override returns (uint256) { return _contestSnapshot; } /** * @dev See {Governor-proposalThreshold}. */ function proposalThreshold() public view virtual override returns (uint256) { return _proposalThreshold; } /** * @dev See {Governor-numAllowedProposalSubmissions}. */ function numAllowedProposalSubmissions() public view virtual override returns (uint256) { return _numAllowedProposalSubmissions; } /** * @dev Max number of proposals allowed in this contest */ function maxProposalCount() public view virtual override returns (uint256) { return _maxProposalCount; } /** * @dev See {IGovernor-creator}. */ function creator() public view virtual override returns (address) { return _creator; } /** * @dev Internal setter for the contestStart. * * Emits a {ContestStartSet} event. */ function _setContestStart(uint256 newContestStart) internal virtual { emit ContestStartSet(_contestStart, newContestStart); _contestStart = newContestStart; } /** * @dev Internal setter for the voting delay. * * Emits a {VotingDelaySet} event. */ function _setVotingDelay(uint256 newVotingDelay) internal virtual { emit VotingDelaySet(_votingDelay, newVotingDelay); _votingDelay = newVotingDelay; } /** * @dev Internal setter for the voting period. * * Emits a {VotingPeriodSet} event. */ function _setVotingPeriod(uint256 newVotingPeriod) internal virtual { // voting period must be at least one block long require(newVotingPeriod > 0, "GovernorSettings: voting period too low"); emit VotingPeriodSet(_votingPeriod, newVotingPeriod); _votingPeriod = newVotingPeriod; } /** * @dev Internal setter for the contestStart. * * Emits a {ContestSnapshotSet} event. */ function _setContestSnapshot(uint256 newContestSnapshot) internal virtual { emit ContestSnapshotSet(_contestSnapshot, newContestSnapshot); _contestSnapshot = newContestSnapshot; } /** * @dev Internal setter for the proposal threshold. * * Emits a {ProposalThresholdSet} event. */ function _setProposalThreshold(uint256 newProposalThreshold) internal virtual { emit ProposalThresholdSet(_proposalThreshold, newProposalThreshold); _proposalThreshold = newProposalThreshold; } /** * @dev Internal setter for the number of allowed proposal submissions per permissioned address. * * Emits a {NumAllowedProposalSubmissionsSet} event. */ function _setNumAllowedProposalSubmissions(uint256 newNumAllowedProposalSubmissions) internal virtual { emit NumAllowedProposalSubmissionsSet(_numAllowedProposalSubmissions, newNumAllowedProposalSubmissions); _numAllowedProposalSubmissions = newNumAllowedProposalSubmissions; } /** * @dev Internal setter for the max proposal count. * * Emits a {MaxProposalCountSet} event. */ function _setMaxProposalCount(uint256 newMaxProposalCount) internal virtual { emit MaxProposalCountSet(_maxProposalCount, newMaxProposalCount); _maxProposalCount = newMaxProposalCount; } /** * @dev Internal setter for creator. * * Emits a {CreatorSet} event. */ function _setCreator(address newCreator) internal virtual { emit CreatorSet(_creator, newCreator); _creator = newCreator; } }
Internal setter for the contestStart. Emits a {ContestStartSet} event./
function _setContestStart(uint256 newContestStart) internal virtual { emit ContestStartSet(_contestStart, newContestStart); _contestStart = newContestStart; }
7,297,537
/** Copyright 2019 Thomas Roskewich 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.22 <0.6.0; contract owned { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } contract MinecraftWorld is owned{ /** * Mapping of the blockOwners goes as follows: * XXXY YZZZ * OR in Bit Form: * XXXX XXXX XXXX YYYY YYYY ZZZZ ZZZZ ZZZZ * */ // Block Owners keeps track of the owner for each block. mapping (uint32 => address) public blockOwners; // Block Data keeps track of what block is at what location. mapping (uint32 => uint16) public blockData; // Block Meta Data for signs. mapping (uint32 => string) public blockMetaData; bool public currentlySelling; uint32 public maxBlockId; string public worldSeed; constructor(bool selling, uint32 maxBlock, string memory worldSeedIn) public{ currentlySelling = selling; maxBlockId = maxBlock; worldSeed = worldSeedIn; } event UpdateBlock(address user, uint32 blockLocation, uint16 newBlockID); event UpdateBlockOwner(address newOwner, uint32 blockInformation); event UpdateBlockMeta(uint32 blockLocation, string metadata); /** * Set Block Owning Address * * Set the owner of the given x y z block provided they do not already own a block. * Used for administration and is a public onlyOwner call. * @param x The relative X coordinate of the block. * @param y The relative Y coordinate of the block. * @param z The relative Z coordinate of the block. * @param newBlockOwner The address of the owner of the block. * * */ function setBlockOwningAddress(uint32 x, uint32 y, uint32 z, address newBlockOwner) public onlyOwner{ uint32 blockID = convertToBlockNumber(x, y, z); setBlockOwner(newBlockOwner, blockID); } /** * Set Max Block ID * * Sets the max block ID usable to place in the Minecraft world. * @param maxBlock The max block ID. * */ function setMaxBlockId(uint32 maxBlock) public onlyOwner{ maxBlockId = maxBlock; } /** * Convert To Block Number * * Converts a given X Y Z coordinate into its block number. * @param x The X coordinate * @param y The Y coordinate * @param z The Z coordinate * @return uint32 The block number * */ function convertToBlockNumber(uint32 x, uint32 y, uint32 z) internal pure returns (uint32){ require(x <= 4095 && y < 256 && z <= 4095); return ((x << 20) + (y << 12) + z); } /** * Set Block Owner * * Set the owner of the given x y z block provided. * @param newBlockOwner The address of the owner of the block. * @param loc The location of the block in the format used internally. * * */ function setBlockOwner(address newBlockOwner, uint32 loc) internal{ require(blockOwners[loc] == address(0x0)); blockOwners[loc] = newBlockOwner; blockData[loc] = 4000; emit UpdateBlockOwner(newBlockOwner, loc); emit UpdateBlock(msg.sender, loc, 4000); } /** * Set Block Owner * * Set the owner of the given x y z block. * @param loc The location of the block in the format used internally. * @param newBlockOwner The address of the owner of the block. * @param blockID The block ID to be placed at the location. * * */ function setBlockOwner(uint32 loc, address newBlockOwner, uint16 blockID) internal{ require(blockOwners[loc] == address(0x0)); require(blockID <= maxBlockId); blockOwners[loc] = newBlockOwner; blockData[loc] = blockID; emit UpdateBlockOwner(newBlockOwner, loc); emit UpdateBlock(msg.sender, loc, blockID); } /** * Set Block Owner Insecure * * Set the owner of the given x y z block provided they do not already own a block. * This version of the function does not check require functions. * @param loc The location of the block in the format used internally. * @param newBlockOwner The address of the owner of the block. * @param blockID The block ID to be placed at the location. * * */ function setBlockOwnerInsecure(uint32 loc, address newBlockOwner, uint16 blockID) internal{ blockOwners[loc] = newBlockOwner; blockData[loc] = blockID; emit UpdateBlockOwner(newBlockOwner, loc); emit UpdateBlock(msg.sender, loc, blockID); } /** * Set Block Data * * Sets the value of the block. * @param loc The location of the block. * @param newBlockID The Minecraft block id. * */ function setBlockData(uint32 loc, uint16 newBlockID) public{ require (blockOwners[loc] == msg.sender); require (newBlockID <= maxBlockId); require (newBlockID > 0); blockData[loc] = newBlockID; emit UpdateBlock(msg.sender, loc, newBlockID); } /** * Set Block Data * * Sets the value of the block. * @param x The X coordinate of the block. * @param y The Y coordinate of the block. * @param z The Z coordinate of the block. * @param newBlockID The Minecraft block id. * */ function setBlockData(uint32 x, uint32 y, uint32 z, uint16 newBlockID) public{ uint32 loc = convertToBlockNumber(x, y, z); setBlockData(loc, newBlockID); } /** * Place Sign * * Places a sign at the given location with the given string. * @param loc The location to place the sign. * @param text The text to put on the sign. * @return The location of the block in the correct format. * */ function placeSign(uint32 loc, string memory text) public returns (uint32){ require(currentlySelling); require(blockOwners[loc] == address(0x0)); require(bytes(text).length <= 60); setBlockOwnerInsecure(loc, msg.sender, 4001); blockMetaData[loc] = text; emit UpdateBlockMeta(loc, text); return loc; } /** * Place Sign * * Places a sign at the given location with the given string. * @param x The X location. * @param y The Y location. * @param z The Z location. * @param text The text to put on the sign. * @return The location of the block in the correct format. * */ function placeSign(uint32 x, uint32 y, uint32 z, string memory text) public returns (uint32){ return placeSign(convertToBlockNumber(x, y, z), text); } /** * Purchase Specific Block * * Allows purchasing a specific block in the Minecraft World. * This is free, but made it payable if someone wants to send money. * @param x The X coordinate. * @param y The Y coordinate. * @param z The Z coordinate. * @return The location of the block in the correct format. * */ function purchaseBlock(uint32 x, uint32 y, uint32 z) payable public returns (uint32){ require(currentlySelling); uint32 num = convertToBlockNumber(x, y, z); setBlockOwner(msg.sender, num); return num; } /** * Purchase Specific Block * * Allows purchasing a specific block in the Minecraft World with a given block ID. * This is free, but made it payable if someone wants to send money. * @param x The x coordinate. * @param y The y coordinate. * @param z The z coordinate. * @param blockID The block ID to be placed at the xyz coordinates. * @return The location of the block in the correct format. * */ function purchaseBlock(uint32 x, uint32 y, uint32 z, uint16 blockID) payable public returns (uint32){ require(currentlySelling); uint32 num = convertToBlockNumber(x, y, z); setBlockOwner(num, msg.sender, blockID); return num; } /** * Set Selling * * Allows for turning off or on selling of blocks to users. * @param isSelling Are we selling blocks? * */ function setSelling(bool isSelling) public onlyOwner{ currentlySelling = isSelling; } /** * Send Block * * Send a block to another address so they control it. * @param other The other address to transfer ownership to. * */ function sendBlock(uint32 blockCoordID, address other) public{ require(other != address(0x0)); require(blockOwners[blockCoordID] == msg.sender); blockOwners[blockCoordID] = other; } /** * Send Block * * Send a block to another address so they control it. * @param other The other address to transfer ownership to. * */ function sendBlock(uint32 x, uint32 y, uint32 z, address other) public{ sendBlock(convertToBlockNumber(x, y, z), other); } /** * Withdraw Ethereum * * Remove Ethereum from the contract and send it to the address provided. * @param withdrawLocation The location to withdraw the Ethereum. * @param amount The amount of Ethereum to take out of the contract. * */ function withdraw(address payable withdrawLocation, uint256 amount) public onlyOwner{ require(address(this).balance >= amount); withdrawLocation.transfer(amount); } }
Set Block Owning Address Set the owner of the given x y z block provided they do not already own a block. Used for administration and is a public onlyOwner call. x The relative X coordinate of the block. y The relative Y coordinate of the block. z The relative Z coordinate of the block. newBlockOwner The address of the owner of the block. /
function setBlockOwningAddress(uint32 x, uint32 y, uint32 z, address newBlockOwner) public onlyOwner{ uint32 blockID = convertToBlockNumber(x, y, z); setBlockOwner(newBlockOwner, blockID); }
7,232,843
./full_match/44787/0xAf33df5ce31d7995dFFB53f6CCf3f20A3beD71c9/sources/contracts/claim/abstract/AdvancedDistributor.sol
Set the token being distributed
function setToken(IERC20 _token) external onlyOwner { require(address(_token) != address(0), "Adjustable: token is address(0)"); token = _token; emit SetToken(token); }
13,250,323
pragma solidity ^0.6.2; // SPDX-License-Identifier: MIT abstract contract Context { function _MSGSENDER583() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA879() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT interface IERC20 { function TOTALSUPPLY430() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF616(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER244(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE387(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE425(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM381(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER617(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL460(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // SPDX-License-Identifier: MIT library SafeMath { function ADD135(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB321(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB321(a, b, "SafeMath: subtraction overflow"); } function SUB321(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL733(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV136(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV136(a, b, "SafeMath: division by zero"); } function DIV136(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD593(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD593(a, b, "SafeMath: modulo by zero"); } function MOD593(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT library Address { function ISCONTRACT469(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } function SENDVALUE193(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function FUNCTIONCALL340(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALL340(target, data, "Address: low-level call failed"); } function FUNCTIONCALL340(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING return _FUNCTIONCALLWITHVALUE922(target, data, 0, errorMessage); } function FUNCTIONCALLWITHVALUE944(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALLWITHVALUE944(target, data, value, "Address: low-level call with value failed"); } function FUNCTIONCALLWITHVALUE944(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING require(address(this).balance >= value, "Address: insufficient balance for call"); return _FUNCTIONCALLWITHVALUE922(target, data, value, errorMessage); } function _FUNCTIONCALLWITHVALUE922(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING require(ISCONTRACT469(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 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; constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } function NAME100() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL131() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS904() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } function TOTALSUPPLY430() public view override returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF616(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER244(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER73(_MSGSENDER583(), recipient, amount); return true; } function ALLOWANCE387(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE425(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _APPROVE319(_MSGSENDER583(), spender, amount); return true; } function TRANSFERFROM381(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER73(sender, recipient, amount); _APPROVE319(sender, _MSGSENDER583(), _allowances[sender][_MSGSENDER583()].SUB321(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE808(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE319(_MSGSENDER583(), spender, _allowances[_MSGSENDER583()][spender].ADD135(addedValue)); return true; } function DECREASEALLOWANCE515(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE319(_MSGSENDER583(), spender, _allowances[_MSGSENDER583()][spender].SUB321(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER73(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _BEFORETOKENTRANSFER129(sender, recipient, amount); _balances[sender] = _balances[sender].SUB321(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD135(amount); emit TRANSFER617(sender, recipient, amount); } function _MINT517(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _BEFORETOKENTRANSFER129(address(0), account, amount); _totalSupply = _totalSupply.ADD135(amount); _balances[account] = _balances[account].ADD135(amount); emit TRANSFER617(address(0), account, amount); } function _BURN171(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _BEFORETOKENTRANSFER129(account, address(0), amount); _balances[account] = _balances[account].SUB321(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB321(amount); emit TRANSFER617(account, address(0), amount); } function _APPROVE319(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit APPROVAL460(owner, spender, amount); } function _SETUPDECIMALS874(uint8 decimals_) internal { //inject NONSTANDARD NAMING _decimals = decimals_; } function _BEFORETOKENTRANSFER129(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING } // SPDX-License-Identifier: MIT abstract contract ERC20Capped is ERC20 { uint256 private _cap; constructor (uint256 cap) public { require(cap > 0, "ERC20Capped: cap is 0"); _cap = cap; } function CAP360() public view returns (uint256) { //inject NONSTANDARD NAMING return _cap; } function _BEFORETOKENTRANSFER129(address from, address to, uint256 amount) internal virtual override { //inject NONSTANDARD NAMING super._BEFORETOKENTRANSFER129(from, to, amount); if (from == address(0)) { // When minting tokens require(TOTALSUPPLY430().ADD135(amount) <= _cap, "ERC20Capped: cap exceeded"); } } } // SPDX-License-Identifier: MIT contract Ownable is Context { address private _owner; event OWNERSHIPTRANSFERRED797(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { address msgSender = _MSGSENDER583(); _owner = msgSender; emit OWNERSHIPTRANSFERRED797(address(0), msgSender); } function OWNER971() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER607() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER583(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP525() public virtual ONLYOWNER607 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED797(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP777(address newOwner) public virtual ONLYOWNER607 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED797(_owner, newOwner); _owner = newOwner; } } interface IUniswapV2Router01 { function FACTORY439() external pure returns (address); //inject NONSTANDARD NAMING function WETH181() external pure returns (address); //inject NONSTANDARD NAMING function ADDLIQUIDITY85( //inject NONSTANDARD NAMING 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 ADDLIQUIDITYETH216( //inject NONSTANDARD NAMING address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function REMOVELIQUIDITY344( //inject NONSTANDARD NAMING address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function REMOVELIQUIDITYETH742( //inject NONSTANDARD NAMING address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function REMOVELIQUIDITYWITHPERMIT491( //inject NONSTANDARD NAMING 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 REMOVELIQUIDITYETHWITHPERMIT317( //inject NONSTANDARD NAMING 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 SWAPEXACTTOKENSFORTOKENS917( //inject NONSTANDARD NAMING uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function SWAPTOKENSFOREXACTTOKENS879( //inject NONSTANDARD NAMING uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function SWAPEXACTETHFORTOKENS817(uint amountOutMin, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING external payable returns (uint[] memory amounts); function SWAPTOKENSFOREXACTETH856(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING external returns (uint[] memory amounts); function SWAPEXACTTOKENSFORETH218(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING external returns (uint[] memory amounts); function SWAPETHFOREXACTTOKENS998(uint amountOut, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING external payable returns (uint[] memory amounts); function QUOTE315(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); //inject NONSTANDARD NAMING function GETAMOUNTOUT816(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); //inject NONSTANDARD NAMING function GETAMOUNTIN684(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); //inject NONSTANDARD NAMING function GETAMOUNTSOUT241(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); //inject NONSTANDARD NAMING function GETAMOUNTSIN775(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); //inject NONSTANDARD NAMING } interface IUniswapV2Router02 is IUniswapV2Router01 { function REMOVELIQUIDITYETHSUPPORTINGFEEONTRANSFERTOKENS846( //inject NONSTANDARD NAMING address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function REMOVELIQUIDITYETHWITHPERMITSUPPORTINGFEEONTRANSFERTOKENS1( //inject NONSTANDARD NAMING 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 SWAPEXACTTOKENSFORTOKENSSUPPORTINGFEEONTRANSFERTOKENS219( //inject NONSTANDARD NAMING uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function SWAPEXACTETHFORTOKENSSUPPORTINGFEEONTRANSFERTOKENS501( //inject NONSTANDARD NAMING uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function SWAPEXACTTOKENSFORETHSUPPORTINGFEEONTRANSFERTOKENS54( //inject NONSTANDARD NAMING uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } interface IUniswapV2Pair { event APPROVAL460(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING event TRANSFER617(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING function NAME100() external pure returns (string memory); //inject NONSTANDARD NAMING function SYMBOL131() external pure returns (string memory); //inject NONSTANDARD NAMING function DECIMALS904() external pure returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY430() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF616(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE387(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE425(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER244(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM381(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function DOMAIN_SEPARATOR749() external view returns (bytes32); //inject NONSTANDARD NAMING function PERMIT_TYPEHASH945() external pure returns (bytes32); //inject NONSTANDARD NAMING function NONCES546(address owner) external view returns (uint); //inject NONSTANDARD NAMING function PERMIT654(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING event MINT786(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING event BURN405(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING event SWAP722( //inject NONSTANDARD NAMING address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event SYNC303(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING function MINIMUM_LIQUIDITY735() external pure returns (uint); //inject NONSTANDARD NAMING function FACTORY439() external view returns (address); //inject NONSTANDARD NAMING function TOKEN0934() external view returns (address); //inject NONSTANDARD NAMING function TOKEN1318() external view returns (address); //inject NONSTANDARD NAMING function GETRESERVES691() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING function PRICE0CUMULATIVELAST150() external view returns (uint); //inject NONSTANDARD NAMING function PRICE1CUMULATIVELAST277() external view returns (uint); //inject NONSTANDARD NAMING function KLAST634() external view returns (uint); //inject NONSTANDARD NAMING function MINT615(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING function BURN664(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING function SWAP816(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING function SKIM21(address to) external; //inject NONSTANDARD NAMING function SYNC269() external; //inject NONSTANDARD NAMING function INITIALIZE267(address, address) external; //inject NONSTANDARD NAMING } interface IUniswapV2Factory { event PAIRCREATED762(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING function FEETO789() external view returns (address); //inject NONSTANDARD NAMING function FEETOSETTER578() external view returns (address); //inject NONSTANDARD NAMING function GETPAIR592(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRS410(uint) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRSLENGTH90() external view returns (uint); //inject NONSTANDARD NAMING function CREATEPAIR614(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING function SETFEETO894(address) external; //inject NONSTANDARD NAMING function SETFEETOSETTER1(address) external; //inject NONSTANDARD NAMING } interface IWETH { function DEPOSIT145() external payable; //inject NONSTANDARD NAMING function TRANSFER244(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function WITHDRAW78(uint) external; //inject NONSTANDARD NAMING } contract CGLB is ERC20Capped, Ownable { using SafeMath for uint; address public UNIPAIR; address public DAI = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); IUniswapV2Router02 public UNIROUTER = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); IUniswapV2Factory public UNIFACTORY = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); bool public isRunning = false; bool private liquidityFlag; uint public constant supplycap690 = (10**4)*(10**18); //inject NONSTANDARD NAMING uint public constant tokensforinitialliquidity143 = 3*(10**3)*(10**18); //inject NONSTANDARD NAMING bytes32 public airdropRoot; mapping (address => bool) public claimedAirdrop; string public website = "www.cglb.fi"; constructor() public ERC20Capped(supplycap690) ERC20("Cant go lower boys", "CGLB") { airdropRoot = 0x185065ab3d54b516ee3ed54dc30e04758300a4b41e207cf3ba91715f378d7728; } function TRANSFER244(address recipient, uint256 amount) //inject NONSTANDARD NAMING public override returns (bool) { require(msg.sender == UNIPAIR || msg.sender == address(UNIROUTER)); super.TRANSFER244(recipient, amount); return true; } function TRANSFERFROM381(address sender, address recipient, uint256 amount) //inject NONSTANDARD NAMING public override returns (bool) { require(liquidityFlag); _TRANSFER73(sender, recipient, amount); return true; } function ADDLIQUIDITYTOUNISWAPPAIR951( //inject NONSTANDARD NAMING uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountDAIDesired, uint256 amountDAImin ) public payable { require(isRunning); require(IERC20(DAI).TRANSFERFROM381(msg.sender, address(this), amountDAIDesired)); require(IERC20(DAI).APPROVE425(address(UNIROUTER), amountDAIDesired)); _TRANSFER73(msg.sender, address(this), amountTokenDesired); liquidityFlag = true; (uint amountToken, uint amountDAI, uint liquidity) = UNIROUTER.ADDLIQUIDITY85( address(this), DAI, amountTokenDesired, amountDAIDesired, amountTokenMin, amountDAImin, msg.sender, now + 10 minutes ); liquidityFlag = false; //sends dust back if (amountTokenDesired - amountToken > 0 ) _TRANSFER73(address(this), msg.sender, amountTokenDesired-amountToken); if (amountDAIDesired - amountDAI > 0) require(IERC20(DAI).TRANSFER244(msg.sender, amountDAIDesired - amountDAI)); } function ADDINITIALLIQUIDITYWITHPAIR729() public ONLYOWNER607 { //inject NONSTANDARD NAMING CREATEUNISWAPPAIR64(); uint256 amountDAI = IERC20(DAI).BALANCEOF616(address(this)); require(IERC20(DAI).TRANSFER244(UNIPAIR, amountDAI)); _MINT517(UNIPAIR, tokensforinitialliquidity143); IUniswapV2Pair(UNIPAIR).MINT615(msg.sender); isRunning = true; } function ADDINITIALLIQUIDITY209() public ONLYOWNER607 { //inject NONSTANDARD NAMING uint256 amountDAI = IERC20(DAI).BALANCEOF616(address(this)); require(IERC20(DAI).TRANSFER244(UNIPAIR, amountDAI)); _MINT517(UNIPAIR, tokensforinitialliquidity143); IUniswapV2Pair(UNIPAIR).MINT615(msg.sender); isRunning = true; } function SETAIRDROPROOT894(bytes32 _root) public ONLYOWNER607 { //inject NONSTANDARD NAMING airdropRoot = _root; } function SETPAIR246(address _pair) public ONLYOWNER607 { //inject NONSTANDARD NAMING UNIPAIR = _pair; } function CREATEUNISWAPPAIR64() internal { //inject NONSTANDARD NAMING require(UNIPAIR == address(0), "Token: pool already created"); UNIPAIR = UNIFACTORY.CREATEPAIR614( DAI, address(this) ); } function CHECKPROOF499(bytes memory proof, bytes32 root, bytes32 hash) internal view returns (bool) { //inject NONSTANDARD NAMING bytes32 el; bytes32 h = hash; for (uint256 i = 32; i <= proof.length; i += 32) { assembly { el := mload(add(proof, i)) } if (h < el) { h = keccak256(abi.encodePacked(h, el)); } else { h = keccak256(abi.encodePacked(el, h)); } } return h == root; } function CLAIMAIRDROP701(bytes memory proof, uint amount) public { //inject NONSTANDARD NAMING require(!claimedAirdrop[msg.sender]); bytes32 hash = keccak256(abi.encodePacked(msg.sender, amount)); require(CHECKPROOF499(proof, airdropRoot, hash), "Invalid proof"); claimedAirdrop[msg.sender] = true; _MINT517(msg.sender, amount); } function WITHDRAWERC20742(address token) ONLYOWNER607 public { //inject NONSTANDARD NAMING uint balance = IERC20(token).BALANCEOF616(address(this)); require(IERC20(token).TRANSFER244(msg.sender, balance)); } }
inject NONSTANDARD NAMING
function APPROVE425(address spender, uint value) external returns (bool);
1,820,578
./full_match/4/0x90641Be52c0F2bD0B9c7F3C84CEE6Eee2bDB9000/sources/home/user/Documents/Projects/solidity/arbitrage-bot/third-party-contracts/USDC/USDC.sol
Check that an authorization is unused authorizer Authorizer's address nonce Nonce of the authorization/
function _requireUnusedAuthorization(address authorizer, bytes32 nonce) private view { require( _authorizationStates[authorizer][nonce] == AuthorizationState.Unused, "FiatTokenV2: authorization is used or canceled" ); }
13,310,664
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "./IBEP20.sol"; import "./Ownable.sol"; import "./SafeMath.sol"; contract BEP20 is Context, IBEP20, Ownable { using SafeMath for uint256; uint256 constant thirtyDays = 2592000; uint256 constant cliffSixM = 6; uint256 constant cliffFourM = 4; uint256 constant cliffThreeM = 3; uint256 constant cliffTwoM = 2; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; uint256 private _totalSupply_6M; uint256 private _totalSupply_4M; uint256 private _totalSupply_3M; uint256 private _totalSupply_2M; bool private _initialMintIsDone; bool private _authoriseMin_6M; bool private _authoriseMin_4M; bool private _authoriseMin_3M; bool private _authoriseMin_2M; uint256 immutable private _maxSupply; uint256 immutable private _maxSupply_6M; uint256 immutable private _maxSupply_4M; uint256 immutable private _maxSupply_3M; uint256 immutable private _maxSupply_2M; uint256 private _wallet1MonthlySupply; uint256 private _wallet2MonthlySupply; uint256 private _wallet3MonthlySupply; uint256 private _wallet4MonthlySupply; uint256 private _wallet5MonthlySupply; uint256 private _wallet6MonthlySupply; uint256 private _wallet1EndOfIcoSupply; uint256 private _wallet2EndOfIcoSupply; uint256 private _wallet3EndOfIcoSupply; uint256 private _wallet4EndOfIcoSupply; uint256 private _wallet5EndOfIcoSupply; uint256 private _wallet6EndOfIcoSupply; uint8 private _decimals; string private _symbol; string private _name; uint256 private _endOfICO; uint256 private _startTime_2M; uint256 private _startTime_3M; uint256 private _startTime_4M; uint256 private _startTime_6M; address private _wallet1; address private _wallet2; address private _wallet3; address private _wallet4; address private _wallet5; address private _wallet6; constructor(address wallet1, address wallet2, address wallet3,address wallet4, address wallet5, address wallet6) { _name = "Artrade Token"; _symbol = "ATR"; _decimals = 9; _balances[msg.sender] = 0; _endOfICO = block.timestamp; _startTime_2M = _endOfICO + (thirtyDays * 2); // 2 month after _startTime_3M = _endOfICO + (thirtyDays * 3); // 3 month after _startTime_4M = _endOfICO + (thirtyDays * 5); // 5 month after _startTime_6M = _endOfICO + (thirtyDays * 7); // 7 month after _wallet1MonthlySupply = 4739256671 * (10 ** uint256(7)); // _wallet2MonthlySupply = 21962955 * (10 ** uint256(_decimals)); // _wallet3MonthlySupply = 6967485 * (10 ** uint256(_decimals)); // _wallet4MonthlySupply = 112052348683481 * (10 ** uint256(2)); // _wallet5MonthlySupply = 151894456 * (10 ** uint256(8)); // _wallet1EndOfIcoSupply = 21326655022 * (10 ** uint256(7)); _wallet2EndOfIcoSupply = 20807010 * (10 ** uint256(_decimals)); _wallet3EndOfIcoSupply = 9289980 * (10 ** uint256(_decimals)); _wallet4EndOfIcoSupply = 112052347899114 * (10 ** uint256(2)); _wallet5EndOfIcoSupply = 151894456 * (10 ** uint256(8)); _wallet6EndOfIcoSupply = 70243377 * (10 ** uint256(_decimals)); _maxSupply_6M = 1482472951 * (10 ** uint256(_decimals)); _maxSupply_4M = 92899800 * (10 ** uint256(_decimals)); _maxSupply_3M = 78436644 * (10 ** uint256(_decimals)); _maxSupply_2M = 75947228 * (10 ** uint256(_decimals)); _maxSupply = 1800000000 * (10 ** uint256(_decimals)); // 1,8 MD _initialMintIsDone = false; _wallet1 = wallet1; _wallet2 = wallet2; _wallet3 = wallet3; _wallet4 = wallet4; _wallet5 = wallet5; _wallet6 = wallet6; _mint(_wallet1, _wallet1EndOfIcoSupply); _mint(_wallet2, _wallet2EndOfIcoSupply); _mint(_wallet3, _wallet3EndOfIcoSupply); _mint(_wallet4, _wallet4EndOfIcoSupply); _mint(_wallet5, _wallet5EndOfIcoSupply); _mint(_wallet6, _wallet6EndOfIcoSupply); _totalSupply_2M = _totalSupply_2M.add(_wallet5EndOfIcoSupply); _totalSupply_3M = _totalSupply_3M.add(_wallet4EndOfIcoSupply); _totalSupply_4M = _totalSupply_4M.add(_wallet3EndOfIcoSupply); _totalSupply_6M = _totalSupply_6M.add(_wallet1EndOfIcoSupply).add(_wallet2EndOfIcoSupply); _totalSupply.add(_wallet1EndOfIcoSupply).add(_wallet2EndOfIcoSupply).add(_wallet3EndOfIcoSupply).add(_wallet4EndOfIcoSupply).add(_wallet5EndOfIcoSupply).add(_wallet6EndOfIcoSupply); } /** * @dev Returns the bep token owner. */ function getOwner() public view override returns (address) { return owner(); } /** * @dev Returns Round 3 address. */ function getRound3Add() external view returns (address) { return _wallet6; } /** * @dev Returns Round 2 address. */ function getRaound2Add() external view returns (address) { return _wallet5; } /** * @dev Returns Round 1 address. */ function getRound1Add() external view returns (address) { return _wallet4; } /** * @dev Returns Private Sale address. */ function getPrivateSaleAdd() external view returns (address) { return _wallet3; } /** * @dev Returns Team and Associates address. */ function getTeamAdd() external view returns (address) { return _wallet2; } /** * @dev Returns reserve address. */ function getReserveAdd() external view returns (address) { return _wallet1; } /** * @dev Returns the token decimals. */ function decimals() public view override returns (uint8) { return _decimals; } /** * @dev Returns the token symbol. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev Returns the token name. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {BEP20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {BEP20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev Returns the cap on the token's total supply. */ function maxSupply() public view returns (uint256) { return _maxSupply; } /** * @dev Returns the end of ico . */ function getEndOfICO() public view returns (uint256) { return _endOfICO; } /** * @dev See {BEP20-startTime}. */ function startTime() external view returns (uint256) { return _endOfICO; } /** * @dev See {BEP20-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 {BEP20-allowance}. */ function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {BEP20-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 {BEP20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {BEP20}; * * 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, "BEP20: 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 {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "BEP20: decreased allowance below zero")); return true; } /** @dev Creates `amount` tokens and assigns them to the right * adresses (associatesAdd, teamAdd, seedAdd, privSaleAdd, * marketingAdd, icoRound1Add , icoRound2Add, icoRound3Add, * reserveAdd), increasing _totalSupply_XM sub-supplies and * the total supply */ function mint(uint256 mintValue) public onlyOwner returns (bool) { require(( mintValue == cliffSixM) || ( mintValue == cliffFourM) || ( mintValue == cliffThreeM) || ( mintValue == cliffTwoM), "BEP20: mint value not authorized"); if ( mintValue == cliffSixM){ require(block.timestamp >= _startTime_6M , "BEP20: too early for minting request"); require(_totalSupply_6M.add(_wallet1MonthlySupply).add(_wallet2MonthlySupply) <= _maxSupply_6M, "BEP20: Assocites, Reserve, Team and Seed cap exceeded"); require(_totalSupply.add(_wallet1MonthlySupply).add(_wallet2MonthlySupply) <= maxSupply(), "BEP20: cap exceeded"); _mint(_wallet1, _wallet1MonthlySupply); _mint(_wallet2, _wallet2MonthlySupply); _totalSupply_6M = _totalSupply_6M.add(_wallet1MonthlySupply).add(_wallet2MonthlySupply); _startTime_6M = _startTime_6M.add(thirtyDays); } if ( mintValue == cliffFourM){ require(block.timestamp >= _startTime_4M , "BEP20: too early for minting request"); require(_totalSupply_4M.add(_wallet3MonthlySupply) <= _maxSupply_4M, "BEP20: Marketing and Private Sale cap exceeded"); require(_totalSupply.add(_wallet3MonthlySupply) <= maxSupply(), "BEP20: cap exceeded"); _mint(_wallet3, _wallet3MonthlySupply); _totalSupply_4M = _totalSupply_4M.add(_wallet3MonthlySupply); _startTime_4M = _startTime_4M.add(thirtyDays); } if ( mintValue == cliffThreeM){ require(block.timestamp >= _startTime_3M, "BEP20: too early for minting request"); require(_totalSupply_3M.add(_wallet4MonthlySupply)<= _maxSupply_3M, "BEP20: ICO Round 1 cap exceeded"); require(_totalSupply.add(_wallet4MonthlySupply) <= maxSupply(), "BEP20: cap exceeded"); _mint(_wallet4, _wallet4MonthlySupply); _totalSupply_3M = _totalSupply_3M.add(_wallet4MonthlySupply); _startTime_3M = _startTime_3M.add(thirtyDays); } if ( mintValue == cliffTwoM){ require(block.timestamp >= _startTime_2M, "BEP20: too early for minting request"); require(_totalSupply_2M.add(_wallet5MonthlySupply)<= _maxSupply_2M, "BEP20: ICO Round 2 cap exceeded"); require(_totalSupply.add(_wallet5MonthlySupply) <= maxSupply(), "BEP20: cap exceeded"); _mint(_wallet5, _wallet5MonthlySupply); _totalSupply_2M = _totalSupply_2M.add(_wallet5MonthlySupply); _startTime_2M = _startTime_2M.add(thirtyDays); } return true; } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public returns (bool) { _burn(_msgSender(), amount); return true; } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public returns (bool) { _burnFrom(account, amount); 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), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @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), "BEP20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "BEP20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "BEP20: 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), "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); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "BEP20: burn amount exceeds allowance")); _burn(account, amount); } }
Returns the token decimals./
function decimals() public view override returns (uint8) { return _decimals; }
6,349,126
pragma solidity ^0.6.12; abstract contract context10 { //inject NONSTANDARD NAMING function _MSGSENDER9() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA1() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface ierc202 { //inject NONSTANDARD NAMING function TOTALSUPPLY1() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF3(address ACCOUNT10) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER5(address RECIPIENT5, uint256 AMOUNT9) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE1(address OWNER0, address SPENDER5) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE1(address SPENDER5, uint256 AMOUNT9) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM10(address SENDER1, address RECIPIENT5, uint256 AMOUNT9) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER2(address indexed FROM2, address indexed TO9, uint256 VALUE2); //inject NONSTANDARD NAMING event APPROVAL10(address indexed OWNER0, address indexed SPENDER5, uint256 VALUE2); //inject NONSTANDARD NAMING } library safemath1 { //inject NONSTANDARD NAMING function ADD4(uint256 A1, uint256 B6) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 C8 = A1 + B6; //inject NONSTANDARD NAMING require(C8 >= A1, "SafeMath: addition overflow"); return C8; } function SUB5(uint256 A1, uint256 B6) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB5(A1, B6, "SafeMath: subtraction overflow"); } function SUB5(uint256 A1, uint256 B6, string memory ERRORMESSAGE3) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(B6 <= A1, ERRORMESSAGE3); uint256 C8 = A1 - B6; //inject NONSTANDARD NAMING return C8; } function MUL6(uint256 A1, uint256 B6) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (A1 == 0) { return 0; } uint256 C8 = A1 * B6; //inject NONSTANDARD NAMING require(C8 / A1 == B6, "SafeMath: multiplication overflow"); return C8; } function DIV4(uint256 A1, uint256 B6) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV4(A1, B6, "SafeMath: division by zero"); } function DIV4(uint256 A1, uint256 B6, string memory ERRORMESSAGE3) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(B6 > 0, ERRORMESSAGE3); uint256 C8 = A1 / B6; //inject NONSTANDARD NAMING // assert(a == b * c + a % b); // There is no case in which this doesn't hold return C8; } function MOD8(uint256 A1, uint256 B6) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD8(A1, B6, "SafeMath: modulo by zero"); } function MOD8(uint256 A1, uint256 B6, string memory ERRORMESSAGE3) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(B6 != 0, ERRORMESSAGE3); return A1 % B6; } } library address5 { //inject NONSTANDARD NAMING function ISCONTRACT2(address ACCOUNT10) internal view returns (bool) { //inject NONSTANDARD NAMING // 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 CODEHASH4; //inject NONSTANDARD NAMING bytes32 ACCOUNTHASH1 = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; //inject NONSTANDARD NAMING // solhint-disable-next-line no-inline-assembly assembly { CODEHASH4 := extcodehash(ACCOUNT10) } return (CODEHASH4 != ACCOUNTHASH1 && CODEHASH4 != 0x0); } function SENDVALUE0(address payable RECIPIENT5, uint256 AMOUNT9) internal { //inject NONSTANDARD NAMING require(address(this).balance >= AMOUNT9, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool SUCCESS3, ) = RECIPIENT5.call{ value: AMOUNT9 }(""); //inject NONSTANDARD NAMING require(SUCCESS3, "Address: unable to send value, recipient may have reverted"); } function FUNCTIONCALL5(address TARGET4, bytes memory DATA2) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALL5(TARGET4, DATA2, "Address: low-level call failed"); } function FUNCTIONCALL5(address TARGET4, bytes memory DATA2, string memory ERRORMESSAGE3) internal returns (bytes memory) { //inject NONSTANDARD NAMING return _FUNCTIONCALLWITHVALUE9(TARGET4, DATA2, 0, ERRORMESSAGE3); } function FUNCTIONCALLWITHVALUE5(address TARGET4, bytes memory DATA2, uint256 VALUE2) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALLWITHVALUE5(TARGET4, DATA2, VALUE2, "Address: low-level call with value failed"); } function FUNCTIONCALLWITHVALUE5(address TARGET4, bytes memory DATA2, uint256 VALUE2, string memory ERRORMESSAGE3) internal returns (bytes memory) { //inject NONSTANDARD NAMING require(address(this).balance >= VALUE2, "Address: insufficient balance for call"); return _FUNCTIONCALLWITHVALUE9(TARGET4, DATA2, VALUE2, ERRORMESSAGE3); } function _FUNCTIONCALLWITHVALUE9(address TARGET4, bytes memory DATA2, uint256 WEIVALUE7, string memory ERRORMESSAGE3) private returns (bytes memory) { //inject NONSTANDARD NAMING require(ISCONTRACT2(TARGET4), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool SUCCESS3, bytes memory RETURNDATA9) = TARGET4.call{ value: WEIVALUE7 }(DATA2); //inject NONSTANDARD NAMING if (SUCCESS3) { return RETURNDATA9; } else { // Look for revert reason and bubble it up if present if (RETURNDATA9.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(RETURNDATA9) revert(add(32, RETURNDATA9), returndata_size) } } else { revert(ERRORMESSAGE3); } } } } library safeerc206 { //inject NONSTANDARD NAMING using safemath1 for uint256; using address5 for address; function SAFETRANSFER10(ierc202 TOKEN0, address TO9, uint256 VALUE2) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN7(TOKEN0, abi.encodeWithSelector(TOKEN0.TRANSFER5.selector, TO9, VALUE2)); } function SAFETRANSFERFROM2(ierc202 TOKEN0, address FROM2, address TO9, uint256 VALUE2) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN7(TOKEN0, abi.encodeWithSelector(TOKEN0.TRANSFERFROM10.selector, FROM2, TO9, VALUE2)); } function SAFEAPPROVE2(ierc202 TOKEN0, address SPENDER5, uint256 VALUE2) internal { //inject NONSTANDARD NAMING // 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((VALUE2 == 0) || (TOKEN0.ALLOWANCE1(address(this), SPENDER5) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN7(TOKEN0, abi.encodeWithSelector(TOKEN0.APPROVE1.selector, SPENDER5, VALUE2)); } function SAFEINCREASEALLOWANCE0(ierc202 TOKEN0, address SPENDER5, uint256 VALUE2) internal { //inject NONSTANDARD NAMING uint256 NEWALLOWANCE4 = TOKEN0.ALLOWANCE1(address(this), SPENDER5).ADD4(VALUE2); //inject NONSTANDARD NAMING _CALLOPTIONALRETURN7(TOKEN0, abi.encodeWithSelector(TOKEN0.APPROVE1.selector, SPENDER5, NEWALLOWANCE4)); } function SAFEDECREASEALLOWANCE7(ierc202 TOKEN0, address SPENDER5, uint256 VALUE2) internal { //inject NONSTANDARD NAMING uint256 NEWALLOWANCE4 = TOKEN0.ALLOWANCE1(address(this), SPENDER5).SUB5(VALUE2, "SafeERC20: decreased allowance below zero"); //inject NONSTANDARD NAMING _CALLOPTIONALRETURN7(TOKEN0, abi.encodeWithSelector(TOKEN0.APPROVE1.selector, SPENDER5, NEWALLOWANCE4)); } function _CALLOPTIONALRETURN7(ierc202 TOKEN0, bytes memory DATA2) private { //inject NONSTANDARD NAMING // 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 RETURNDATA9 = address(TOKEN0).FUNCTIONCALL5(DATA2, "SafeERC20: low-level call failed"); //inject NONSTANDARD NAMING if (RETURNDATA9.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(RETURNDATA9, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ownable2 is context10 { //inject NONSTANDARD NAMING address private _OWNER5; //inject NONSTANDARD NAMING event OWNERSHIPTRANSFERRED2(address indexed PREVIOUSOWNER0, address indexed NEWOWNER9); //inject NONSTANDARD NAMING constructor () internal { address MSGSENDER1 = _MSGSENDER9(); //inject NONSTANDARD NAMING _OWNER5 = MSGSENDER1; emit OWNERSHIPTRANSFERRED2(address(0), MSGSENDER1); } function OWNER2() public view returns (address) { //inject NONSTANDARD NAMING return _OWNER5; } modifier ONLYOWNER10() { //inject NONSTANDARD NAMING require(_OWNER5 == _MSGSENDER9(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP2() public virtual ONLYOWNER10 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED2(_OWNER5, address(0)); _OWNER5 = address(0); } function TRANSFEROWNERSHIP5(address NEWOWNER9) public virtual ONLYOWNER10 { //inject NONSTANDARD NAMING require(NEWOWNER9 != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED2(_OWNER5, NEWOWNER9); _OWNER5 = NEWOWNER9; } } contract erc206 is context10, ierc202 { //inject NONSTANDARD NAMING using safemath1 for uint256; using address5 for address; mapping (address => uint256) private _BALANCES2; //inject NONSTANDARD NAMING mapping (address => mapping (address => uint256)) private _ALLOWANCES8; //inject NONSTANDARD NAMING uint256 private _TOTALSUPPLY10; //inject NONSTANDARD NAMING string private _NAME6; //inject NONSTANDARD NAMING string private _SYMBOL5; //inject NONSTANDARD NAMING uint8 private _DECIMALS1; //inject NONSTANDARD NAMING constructor (string memory NAME8, string memory SYMBOL9) public { //inject NONSTANDARD NAMING _NAME6 = NAME8; _SYMBOL5 = SYMBOL9; _DECIMALS1 = 18; } function NAME2() public view returns (string memory) { //inject NONSTANDARD NAMING return _NAME6; } function SYMBOL4() public view returns (string memory) { //inject NONSTANDARD NAMING return _SYMBOL5; } function DECIMALS0() public view returns (uint8) { //inject NONSTANDARD NAMING return _DECIMALS1; } function TOTALSUPPLY1() public view override returns (uint256) { //inject NONSTANDARD NAMING return _TOTALSUPPLY10; } function BALANCEOF3(address ACCOUNT10) public view override returns (uint256) { //inject NONSTANDARD NAMING return _BALANCES2[ACCOUNT10]; } function TRANSFER5(address RECIPIENT5, uint256 AMOUNT9) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER10(_MSGSENDER9(), RECIPIENT5, AMOUNT9); return true; } function ALLOWANCE1(address OWNER0, address SPENDER5) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING return _ALLOWANCES8[OWNER0][SPENDER5]; } function APPROVE1(address SPENDER5, uint256 AMOUNT9) public virtual override returns (bool) { //inject NONSTANDARD NAMING _APPROVE0(_MSGSENDER9(), SPENDER5, AMOUNT9); return true; } function TRANSFERFROM10(address SENDER1, address RECIPIENT5, uint256 AMOUNT9) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER10(SENDER1, RECIPIENT5, AMOUNT9); _APPROVE0(SENDER1, _MSGSENDER9(), _ALLOWANCES8[SENDER1][_MSGSENDER9()].SUB5(AMOUNT9, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE2(address SPENDER5, uint256 ADDEDVALUE8) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE0(_MSGSENDER9(), SPENDER5, _ALLOWANCES8[_MSGSENDER9()][SPENDER5].ADD4(ADDEDVALUE8)); return true; } function DECREASEALLOWANCE5(address SPENDER5, uint256 SUBTRACTEDVALUE10) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE0(_MSGSENDER9(), SPENDER5, _ALLOWANCES8[_MSGSENDER9()][SPENDER5].SUB5(SUBTRACTEDVALUE10, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER10(address SENDER1, address RECIPIENT5, uint256 AMOUNT9) internal virtual { //inject NONSTANDARD NAMING require(SENDER1 != address(0), "ERC20: transfer from the zero address"); require(RECIPIENT5 != address(0), "ERC20: transfer to the zero address"); _BEFORETOKENTRANSFER8(SENDER1, RECIPIENT5, AMOUNT9); _BALANCES2[SENDER1] = _BALANCES2[SENDER1].SUB5(AMOUNT9, "ERC20: transfer amount exceeds balance"); _BALANCES2[RECIPIENT5] = _BALANCES2[RECIPIENT5].ADD4(AMOUNT9); emit TRANSFER2(SENDER1, RECIPIENT5, AMOUNT9); } function _MINT10(address ACCOUNT10, uint256 AMOUNT9) internal virtual { //inject NONSTANDARD NAMING require(ACCOUNT10 != address(0), "ERC20: mint to the zero address"); _BEFORETOKENTRANSFER8(address(0), ACCOUNT10, AMOUNT9); _TOTALSUPPLY10 = _TOTALSUPPLY10.ADD4(AMOUNT9); _BALANCES2[ACCOUNT10] = _BALANCES2[ACCOUNT10].ADD4(AMOUNT9); emit TRANSFER2(address(0), ACCOUNT10, AMOUNT9); } function _BURN5(address ACCOUNT10, uint256 AMOUNT9) internal virtual { //inject NONSTANDARD NAMING require(ACCOUNT10 != address(0), "ERC20: burn from the zero address"); _BEFORETOKENTRANSFER8(ACCOUNT10, address(0), AMOUNT9); _BALANCES2[ACCOUNT10] = _BALANCES2[ACCOUNT10].SUB5(AMOUNT9, "ERC20: burn amount exceeds balance"); _TOTALSUPPLY10 = _TOTALSUPPLY10.SUB5(AMOUNT9); emit TRANSFER2(ACCOUNT10, address(0), AMOUNT9); } function _APPROVE0(address OWNER0, address SPENDER5, uint256 AMOUNT9) internal virtual { //inject NONSTANDARD NAMING require(OWNER0 != address(0), "ERC20: approve from the zero address"); require(SPENDER5 != address(0), "ERC20: approve to the zero address"); _ALLOWANCES8[OWNER0][SPENDER5] = AMOUNT9; emit APPROVAL10(OWNER0, SPENDER5, AMOUNT9); } function _SETUPDECIMALS6(uint8 DECIMALS_1) internal { //inject NONSTANDARD NAMING _DECIMALS1 = DECIMALS_1; } function _BEFORETOKENTRANSFER8(address FROM2, address TO9, uint256 AMOUNT9) internal virtual { } //inject NONSTANDARD NAMING } // Moon Token with Governance. contract moontoken3 is erc206("MOON.finance", "MOON"), ownable2 { //inject NONSTANDARD NAMING function MINT7(address _TO2, uint256 _AMOUNT3) public ONLYOWNER10 { //inject NONSTANDARD NAMING _MINT10(_TO2, _AMOUNT3); } }
inject NONSTANDARD NAMING
function _MSGSENDER9() internal view virtual returns (address payable) {
13,119,560
./partial_match/4/0x551a74aE49F5C1Bee89ca4e0517DdFFe900601a5/sources/SafeInterest.sol
Add a new lp to the safe. Can only be called by the owner. XXX DO NOT add the same token more than once. Rewards will be messed up if you do.
function newSafe(uint256 _currentSafeInterest, IERC20 _token, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdateSafes(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_currentSafeInterest); safeInfo.push(SafeInfo({ token: _token, currentSafeInterest: _currentSafeInterest, lastRewardBlock: lastRewardBlock, accSushiPerShare: 0 })); }
8,609,536
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; library Strings { function toString(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); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } } 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); } } library Address { function isContract(address account) internal view returns (bool) { return account.code.length > 0; } } interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner,address indexed operator,bool approved); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom(address from,address to,uint256 tokenId) external; function transferFrom(address from,address to,uint256 tokenId) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId)external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator)external view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } interface IERC721Enumerable is IERC721 { function totalSupply() external view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index)external view returns (uint256); function tokenByIndex(uint256 index) external view returns (uint256); } interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } interface IERC721Receiver { function onERC721Received(address operator,address from,uint256 tokenId,bytes calldata data) external returns (bytes4); } error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintedQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerIndexOutOfBounds(); error OwnerQueryForNonexistentToken(); error TokenIndexOutOfBounds(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error UnableDetermineTokenOwner(); error URIQueryForNonexistentToken(); contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable{ using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 internal _currentIndex; string private _name; string private _symbol; mapping(uint256 => TokenOwnership) internal _ownerships; mapping(address => AddressData) private _addressData; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function totalSupply() public view override returns (uint256) { return _currentIndex; } function tokenByIndex(uint256 index)public view override returns (uint256){ if (index >= totalSupply()) revert TokenIndexOutOfBounds(); return index; } function tokenOfOwnerByIndex(address owner, uint256 index)public view override returns (uint256 a){ if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. assert(false); } function supportsInterface(bytes4 interfaceId)public view virtual override(ERC165, IERC165) returns (bool){ return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } /** * 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){ if (!_exists(tokenId)) revert OwnerQueryForNonexistentToken(); unchecked { for (uint256 curr = tokenId; curr >= 0; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } revert UnableDetermineTokenOwner(); } function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory){ if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } function _baseURI() internal view virtual returns (string memory) { return ""; } 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); } function getApproved(uint256 tokenId) public view override returns (address){ if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } function setApprovalForAll(address operator, bool approved)public override{ if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool){ return _operatorApprovals[owner][operator]; } function transferFrom( address from, address to, uint256 tokenId) public virtual override { _transfer(from, to, tokenId); } function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) revert TransferToNonERC721ReceiverImplementer(); } function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } function _safeMint( address to, uint256 quantity, bytes memory _data) internal { _mint(to, quantity, _data, true); } 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 > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.56e77 (2**256) - 1 unchecked { _addressData[to].balance += uint128(quantity); _addressData[to].numberMinted += uint128(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if ( safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data) ) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } function _transfer(address from, address to, uint256 tokenId) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership .startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } function _approve( address to, uint256 tokenId, address owner) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } function _checkOnERC721Received(address from,address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) revert TransferToNonERC721ReceiverImplementer(); else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _beforeTokenTransfers(address from, address to, uint256 startTokenId, uint256 quantity) internal virtual {} function _afterTokenTransfers(address from, address to, uint256 startTokenId, uint256 quantity) internal virtual {} } 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 Merkle 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) } } } contract IRRELEVANTINVADERS is ERC721A, Ownable { uint256 public maxSupply = 1000; uint256 public reserveQuantity = 0; uint256 private winnersQuantity=2; uint256 public price = 0.084 ether; uint256 public preSaleSupply = 1000; uint256 public preSalePrice = 0.084 ether; uint256 public maxPerWallet = 5; uint256 public maxPerTransaction = 2; bytes32 private merkleRoot; string public _baseURI1; bool public isPaused =true; bool public isPreSalePaused =true; IERC721 public _ALIENS1Obj; IERC721 public _ALIENS2Obj; IERC721 public _ALIENS3Obj; IERC721 public deployedIIv; struct UserPreSaleCounter { uint256 counter; } struct EVOLVING { bool ALIENS1; bool ALIENS2; bool ALIENS3; } mapping(address => UserPreSaleCounter) public _preSaleCounter; mapping(address => bool) public _preSaleAddressExist; mapping(uint256 => EVOLVING) public evolving; mapping(address =>bool) public oldNftAddressExist; constructor(string memory baseUri) ERC721A("IRRELEVANT INVADERS", "IIV") { _baseURI1= baseUri; } function setMaxSupply(uint256 _maxSupply) public onlyOwner { maxSupply = _maxSupply; } function setWinnersQuantity(uint256 _winnersQuantity) public onlyOwner { require(_winnersQuantity < maxSupply, "amount exceeds"); winnersQuantity = _winnersQuantity; } function setPrice(uint256 _price) public onlyOwner { price = _price; } function setPresaleSupply(uint256 _preSaleSupply) public onlyOwner { preSaleSupply = _preSaleSupply; } function setPreSalePrice(uint256 _price) public onlyOwner { preSalePrice = _price; } function setMaxPerWallet(uint256 quantity) public onlyOwner { maxPerWallet = quantity; } function setMaxPerTrasaction(uint256 quantity) public onlyOwner { maxPerTransaction = quantity; } function setRoot(bytes32 root) public onlyOwner { merkleRoot = root; } function setBaseURI(string memory baseuri) public onlyOwner { _baseURI1 = baseuri; } function flipPauseStatus() public onlyOwner { isPaused = !isPaused; } function flipPreSalePauseStatus() public onlyOwner { isPreSalePaused = !isPreSalePaused; } function setALIENS1(address ALIENS1Address) public onlyOwner { _ALIENS1Obj = IERC721(ALIENS1Address); } function setALIENS2(address ALIENS2Address) public onlyOwner { _ALIENS2Obj = IERC721(ALIENS2Address); } function setALIENS3(address ALIENS3) public onlyOwner { _ALIENS3Obj = IERC721(ALIENS3); } function setIIvAddress(address contractaddress) public onlyOwner { deployedIIv = IERC721(contractaddress); } function _baseURI()internal view override returns (string memory){ return _baseURI1; } function mint(uint256 quantity) public payable { require(quantity > 0 ,"quantity should be greater than 0"); require(isPaused==false,"minting is stopped"); require(quantity <=maxPerTransaction,"per transaction amount exceeds"); require(totalSupply()+quantity<=maxSupply-reserveQuantity-winnersQuantity,"all tokens have been minted"); require(price*quantity == msg.value, "Sent ether value is incorrect"); _safeMint(msg.sender, quantity); } function mintPreSale(bytes32[] calldata _merkleProof, uint256 quantity) public payable { if (_preSaleAddressExist[msg.sender] == false) { _preSaleCounter[msg.sender] = UserPreSaleCounter({ counter: 0 }); _preSaleAddressExist[msg.sender] = true; } require(isPreSalePaused== false, "turn on minting"); require(_preSaleCounter[msg.sender].counter + quantity <= maxPerWallet, "Sorry can not mint more than maxwallet"); require(quantity > 0, "zero not allowed"); bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); require( MerkleProof.verify(_merkleProof, merkleRoot, leaf), "Invalid Proof" ); require(totalSupply() + quantity <= preSaleSupply, "presale amount exceeds"); require(preSalePrice*quantity==msg.value,"invalid amount"); _safeMint(msg.sender,quantity); _preSaleCounter[msg.sender].counter += quantity; } function tokensOfOwner(address _owner)public view returns (uint256[] memory) { uint256 count = balanceOf(_owner); uint256[] memory result = new uint256[](count); for (uint256 index = 0; index < count; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } function enterage(uint256 tokenid, string memory age) external { if (keccak256(abi.encodePacked(age)) == keccak256(abi.encodePacked("ALIENS1"))) { _ALIENS1Obj.ownerOf(tokenid) == msg.sender; evolving[tokenid].ALIENS1 = true; } else if (keccak256(abi.encodePacked(age)) == keccak256(abi.encodePacked("ALIENS2"))) { _ALIENS2Obj.ownerOf(tokenid) == msg.sender; evolving[tokenid].ALIENS2 = true; } else if (keccak256(abi.encodePacked(age)) == keccak256(abi.encodePacked("ALIENS3"))) { _ALIENS3Obj.ownerOf(tokenid) == msg.sender; evolving[tokenid].ALIENS3 = true; } else { revert("wrong age entered"); } } function OldNftHolders(uint startIndex ,uint endIndex)public onlyOwner { address owner; for(uint i=startIndex; i<= endIndex; i++){ owner = deployedIIv.ownerOf(i); if(oldNftAddressExist[owner]==false){ uint256 nftBalance = deployedIIv.balanceOf(owner); _safeMint(owner,nftBalance); oldNftAddressExist[owner]=true; } } } function withdraw() public onlyOwner { uint balance = address(this).balance; payable(msg.sender).transfer(balance); } }
Clear approvals from the previous owner 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 2256. 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.
function _transfer(address from, address to, uint256 tokenId) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); _approve(address(0), tokenId, prevOwnership.addr); unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership .startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); }
1,608,311
// SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../dependencies/open-zeppelin/SafeMath.sol'; import { IDydxGovernor } from '../../interfaces/IDydxGovernor.sol'; import { IGovernanceStrategy } from '../../interfaces/IGovernanceStrategy.sol'; import { IProposalValidator } from '../../interfaces/IProposalValidator.sol'; /** * @title Proposal validator contract mixin, inherited the governance executor contract. * @dev Validates/Invalidations propositions state modifications. * Proposition Power functions: Validates proposition creations/ cancellation * Voting Power functions: Validates success of propositions. * @author dYdX **/ contract ProposalValidatorMixin is IProposalValidator { using SafeMath for uint256; uint256 public immutable override PROPOSITION_THRESHOLD; uint256 public immutable override VOTING_DURATION; uint256 public immutable override VOTE_DIFFERENTIAL; uint256 public immutable override MINIMUM_QUORUM; uint256 public constant override ONE_HUNDRED_WITH_PRECISION = 10000; // Represents 100%. /** * @dev Constructor * @param propositionThreshold minimum percentage of supply needed to submit a proposal * - In ONE_HUNDRED_WITH_PRECISION units * @param votingDuration duration in blocks of the voting period * @param voteDifferential percentage of supply that `for` votes need to be over `against` * in order for the proposal to pass * - In ONE_HUNDRED_WITH_PRECISION units * @param minimumQuorum minimum percentage of the supply in FOR-voting-power need for a proposal to pass * - In ONE_HUNDRED_WITH_PRECISION units **/ constructor( uint256 propositionThreshold, uint256 votingDuration, uint256 voteDifferential, uint256 minimumQuorum ) { PROPOSITION_THRESHOLD = propositionThreshold; VOTING_DURATION = votingDuration; VOTE_DIFFERENTIAL = voteDifferential; MINIMUM_QUORUM = minimumQuorum; } /** * @dev Called to validate a proposal (e.g when creating new proposal in Governance) * @param governance Governance Contract * @param user Address of the proposal creator * @param blockNumber Block Number against which to make the test (e.g proposal creation block -1). * @return boolean, true if can be created **/ function validateCreatorOfProposal( IDydxGovernor governance, address user, uint256 blockNumber ) external view override returns (bool) { return isPropositionPowerEnough(governance, user, blockNumber); } /** * @dev Called to validate the cancellation of a proposal * Needs to creator to have lost proposition power threashold * @param governance Governance Contract * @param user Address of the proposal creator * @param blockNumber Block Number against which to make the test (e.g proposal creation block -1). * @return boolean, true if can be cancelled **/ function validateProposalCancellation( IDydxGovernor governance, address user, uint256 blockNumber ) external view override returns (bool) { return !isPropositionPowerEnough(governance, user, blockNumber); } /** * @dev Returns whether a user has enough Proposition Power to make a proposal. * @param governance Governance Contract * @param user Address of the user to be challenged. * @param blockNumber Block Number against which to make the challenge. * @return true if user has enough power **/ function isPropositionPowerEnough( IDydxGovernor governance, address user, uint256 blockNumber ) public view override returns (bool) { IGovernanceStrategy currentGovernanceStrategy = IGovernanceStrategy( governance.getGovernanceStrategy() ); return currentGovernanceStrategy.getPropositionPowerAt(user, blockNumber) >= getMinimumPropositionPowerNeeded(governance, blockNumber); } /** * @dev Returns the minimum Proposition Power needed to create a proposition. * @param governance Governance Contract * @param blockNumber Blocknumber at which to evaluate * @return minimum Proposition Power needed **/ function getMinimumPropositionPowerNeeded(IDydxGovernor governance, uint256 blockNumber) public view override returns (uint256) { IGovernanceStrategy currentGovernanceStrategy = IGovernanceStrategy( governance.getGovernanceStrategy() ); return currentGovernanceStrategy .getTotalPropositionSupplyAt(blockNumber) .mul(PROPOSITION_THRESHOLD) .div(ONE_HUNDRED_WITH_PRECISION); } /** * @dev Returns whether a proposal passed or not * @param governance Governance Contract * @param proposalId Id of the proposal to set * @return true if proposal passed **/ function isProposalPassed(IDydxGovernor governance, uint256 proposalId) external view override returns (bool) { return (isQuorumValid(governance, proposalId) && isVoteDifferentialValid(governance, proposalId)); } /** * @dev Calculates the minimum amount of Voting Power needed for a proposal to Pass * @param votingSupply Total number of oustanding voting tokens * @return voting power needed for a proposal to pass **/ function getMinimumVotingPowerNeeded(uint256 votingSupply) public view override returns (uint256) { return votingSupply.mul(MINIMUM_QUORUM).div(ONE_HUNDRED_WITH_PRECISION); } /** * @dev Check whether a proposal has reached quorum, ie has enough FOR-voting-power * Here quorum is not to understand as number of votes reached, but number of for-votes reached * @param governance Governance Contract * @param proposalId Id of the proposal to verify * @return voting power needed for a proposal to pass **/ function isQuorumValid(IDydxGovernor governance, uint256 proposalId) public view override returns (bool) { IDydxGovernor.ProposalWithoutVotes memory proposal = governance.getProposalById(proposalId); uint256 votingSupply = IGovernanceStrategy(proposal.strategy).getTotalVotingSupplyAt( proposal.startBlock ); return proposal.forVotes >= getMinimumVotingPowerNeeded(votingSupply); } /** * @dev Check whether a proposal has enough extra FOR-votes than AGAINST-votes * FOR VOTES - AGAINST VOTES > VOTE_DIFFERENTIAL * voting supply * @param governance Governance Contract * @param proposalId Id of the proposal to verify * @return true if enough For-Votes **/ function isVoteDifferentialValid(IDydxGovernor governance, uint256 proposalId) public view override returns (bool) { IDydxGovernor.ProposalWithoutVotes memory proposal = governance.getProposalById(proposalId); uint256 votingSupply = IGovernanceStrategy(proposal.strategy).getTotalVotingSupplyAt( proposal.startBlock ); return (proposal.forVotes.mul(ONE_HUNDRED_WITH_PRECISION).div(votingSupply) > proposal.againstVotes.mul(ONE_HUNDRED_WITH_PRECISION).div(votingSupply).add( VOTE_DIFFERENTIAL )); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { IExecutorWithTimelock } from './IExecutorWithTimelock.sol'; interface IDydxGovernor { enum ProposalState { Pending, Canceled, Active, Failed, Succeeded, Queued, Expired, Executed } struct Vote { bool support; uint248 votingPower; } struct Proposal { uint256 id; address creator; IExecutorWithTimelock executor; address[] targets; uint256[] values; string[] signatures; bytes[] calldatas; bool[] withDelegatecalls; uint256 startBlock; uint256 endBlock; uint256 executionTime; uint256 forVotes; uint256 againstVotes; bool executed; bool canceled; address strategy; bytes32 ipfsHash; mapping(address => Vote) votes; } struct ProposalWithoutVotes { uint256 id; address creator; IExecutorWithTimelock executor; address[] targets; uint256[] values; string[] signatures; bytes[] calldatas; bool[] withDelegatecalls; uint256 startBlock; uint256 endBlock; uint256 executionTime; uint256 forVotes; uint256 againstVotes; bool executed; bool canceled; address strategy; bytes32 ipfsHash; } /** * @dev emitted when a new proposal is created * @param id Id of the proposal * @param creator address of the creator * @param executor The ExecutorWithTimelock contract that will execute the proposal * @param targets list of contracts called by proposal's associated transactions * @param values list of value in wei for each propoposal's associated transaction * @param signatures list of function signatures (can be empty) to be used when created the callData * @param calldatas list of calldatas: if associated signature empty, calldata ready, else calldata is arguments * @param withDelegatecalls boolean, true = transaction delegatecalls the taget, else calls the target * @param startBlock block number when vote starts * @param endBlock block number when vote ends * @param strategy address of the governanceStrategy contract * @param ipfsHash IPFS hash of the proposal **/ event ProposalCreated( uint256 id, address indexed creator, IExecutorWithTimelock indexed executor, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, bool[] withDelegatecalls, uint256 startBlock, uint256 endBlock, address strategy, bytes32 ipfsHash ); /** * @dev emitted when a proposal is canceled * @param id Id of the proposal **/ event ProposalCanceled(uint256 id); /** * @dev emitted when a proposal is queued * @param id Id of the proposal * @param executionTime time when proposal underlying transactions can be executed * @param initiatorQueueing address of the initiator of the queuing transaction **/ event ProposalQueued(uint256 id, uint256 executionTime, address indexed initiatorQueueing); /** * @dev emitted when a proposal is executed * @param id Id of the proposal * @param initiatorExecution address of the initiator of the execution transaction **/ event ProposalExecuted(uint256 id, address indexed initiatorExecution); /** * @dev emitted when a vote is registered * @param id Id of the proposal * @param voter address of the voter * @param support boolean, true = vote for, false = vote against * @param votingPower Power of the voter/vote **/ event VoteEmitted(uint256 id, address indexed voter, bool support, uint256 votingPower); event GovernanceStrategyChanged(address indexed newStrategy, address indexed initiatorChange); event VotingDelayChanged(uint256 newVotingDelay, address indexed initiatorChange); event ExecutorAuthorized(address executor); event ExecutorUnauthorized(address executor); /** * @dev Creates a Proposal (needs Proposition Power of creator > Threshold) * @param executor The ExecutorWithTimelock contract that will execute the proposal * @param targets list of contracts called by proposal's associated transactions * @param values list of value in wei for each propoposal's associated transaction * @param signatures list of function signatures (can be empty) to be used when created the callData * @param calldatas list of calldatas: if associated signature empty, calldata ready, else calldata is arguments * @param withDelegatecalls if true, transaction delegatecalls the taget, else calls the target * @param ipfsHash IPFS hash of the proposal **/ function create( IExecutorWithTimelock executor, address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas, bool[] memory withDelegatecalls, bytes32 ipfsHash ) external returns (uint256); /** * @dev Cancels a Proposal, when proposal is Pending/Active and threshold no longer reached * @param proposalId id of the proposal **/ function cancel(uint256 proposalId) external; /** * @dev Queue the proposal (If Proposal Succeeded) * @param proposalId id of the proposal to queue **/ function queue(uint256 proposalId) external; /** * @dev Execute the proposal (If Proposal Queued) * @param proposalId id of the proposal to execute **/ function execute(uint256 proposalId) external payable; /** * @dev Function allowing msg.sender to vote for/against a proposal * @param proposalId id of the proposal * @param support boolean, true = vote for, false = vote against **/ function submitVote(uint256 proposalId, bool support) external; /** * @dev Function to register the vote of user that has voted offchain via signature * @param proposalId id of the proposal * @param support boolean, true = vote for, false = vote against * @param v v part of the voter signature * @param r r part of the voter signature * @param s s part of the voter signature **/ function submitVoteBySignature( uint256 proposalId, bool support, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Set new GovernanceStrategy * Note: owner should be a timelocked executor, so needs to make a proposal * @param governanceStrategy new Address of the GovernanceStrategy contract **/ function setGovernanceStrategy(address governanceStrategy) external; /** * @dev Set new Voting Delay (delay before a newly created proposal can be voted on) * Note: owner should be a timelocked executor, so needs to make a proposal * @param votingDelay new voting delay in seconds **/ function setVotingDelay(uint256 votingDelay) external; /** * @dev Add new addresses to the list of authorized executors * @param executors list of new addresses to be authorized executors **/ function authorizeExecutors(address[] memory executors) external; /** * @dev Remove addresses to the list of authorized executors * @param executors list of addresses to be removed as authorized executors **/ function unauthorizeExecutors(address[] memory executors) external; /** * @dev Getter of the current GovernanceStrategy address * @return The address of the current GovernanceStrategy contracts **/ function getGovernanceStrategy() external view returns (address); /** * @dev Getter of the current Voting Delay (delay before a created proposal can be voted on) * Different from the voting duration * @return The voting delay in seconds **/ function getVotingDelay() external view returns (uint256); /** * @dev Returns whether an address is an authorized executor * @param executor address to evaluate as authorized executor * @return true if authorized **/ function isExecutorAuthorized(address executor) external view returns (bool); /** * @dev Getter of the proposal count (the current number of proposals ever created) * @return the proposal count **/ function getProposalsCount() external view returns (uint256); /** * @dev Getter of a proposal by id * @param proposalId id of the proposal to get * @return the proposal as ProposalWithoutVotes memory object **/ function getProposalById(uint256 proposalId) external view returns (ProposalWithoutVotes memory); /** * @dev Getter of the Vote of a voter about a proposal * Note: Vote is a struct: ({bool support, uint248 votingPower}) * @param proposalId id of the proposal * @param voter address of the voter * @return The associated Vote memory object **/ function getVoteOnProposal(uint256 proposalId, address voter) external view returns (Vote memory); /** * @dev Get the current state of a proposal * @param proposalId id of the proposal * @return The current state if the proposal **/ function getProposalState(uint256 proposalId) external view returns (ProposalState); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; interface IGovernanceStrategy { /** * @dev Returns the Proposition Power of a user at a specific block number. * @param user Address of the user. * @param blockNumber Blocknumber at which to fetch Proposition Power * @return Power number **/ function getPropositionPowerAt(address user, uint256 blockNumber) external view returns (uint256); /** * @dev Returns the total supply of Outstanding Proposition Tokens * @param blockNumber Blocknumber at which to evaluate * @return total supply at blockNumber **/ function getTotalPropositionSupplyAt(uint256 blockNumber) external view returns (uint256); /** * @dev Returns the total supply of Outstanding Voting Tokens * @param blockNumber Blocknumber at which to evaluate * @return total supply at blockNumber **/ function getTotalVotingSupplyAt(uint256 blockNumber) external view returns (uint256); /** * @dev Returns the Vote Power of a user at a specific block number. * @param user Address of the user. * @param blockNumber Blocknumber at which to fetch Vote Power * @return Vote number **/ function getVotingPowerAt(address user, uint256 blockNumber) external view returns (uint256); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { IDydxGovernor } from './IDydxGovernor.sol'; interface IProposalValidator { /** * @dev Called to validate a proposal (e.g when creating new proposal in Governance) * @param governance Governance Contract * @param user Address of the proposal creator * @param blockNumber Block Number against which to make the test (e.g proposal creation block -1). * @return boolean, true if can be created **/ function validateCreatorOfProposal( IDydxGovernor governance, address user, uint256 blockNumber ) external view returns (bool); /** * @dev Called to validate the cancellation of a proposal * @param governance Governance Contract * @param user Address of the proposal creator * @param blockNumber Block Number against which to make the test (e.g proposal creation block -1). * @return boolean, true if can be cancelled **/ function validateProposalCancellation( IDydxGovernor governance, address user, uint256 blockNumber ) external view returns (bool); /** * @dev Returns whether a user has enough Proposition Power to make a proposal. * @param governance Governance Contract * @param user Address of the user to be challenged. * @param blockNumber Block Number against which to make the challenge. * @return true if user has enough power **/ function isPropositionPowerEnough( IDydxGovernor governance, address user, uint256 blockNumber ) external view returns (bool); /** * @dev Returns the minimum Proposition Power needed to create a proposition. * @param governance Governance Contract * @param blockNumber Blocknumber at which to evaluate * @return minimum Proposition Power needed **/ function getMinimumPropositionPowerNeeded(IDydxGovernor governance, uint256 blockNumber) external view returns (uint256); /** * @dev Returns whether a proposal passed or not * @param governance Governance Contract * @param proposalId Id of the proposal to set * @return true if proposal passed **/ function isProposalPassed(IDydxGovernor governance, uint256 proposalId) external view returns (bool); /** * @dev Check whether a proposal has reached quorum, ie has enough FOR-voting-power * Here quorum is not to understand as number of votes reached, but number of for-votes reached * @param governance Governance Contract * @param proposalId Id of the proposal to verify * @return voting power needed for a proposal to pass **/ function isQuorumValid(IDydxGovernor governance, uint256 proposalId) external view returns (bool); /** * @dev Check whether a proposal has enough extra FOR-votes than AGAINST-votes * FOR VOTES - AGAINST VOTES > VOTE_DIFFERENTIAL * voting supply * @param governance Governance Contract * @param proposalId Id of the proposal to verify * @return true if enough For-Votes **/ function isVoteDifferentialValid(IDydxGovernor governance, uint256 proposalId) external view returns (bool); /** * @dev Calculates the minimum amount of Voting Power needed for a proposal to Pass * @param votingSupply Total number of oustanding voting tokens * @return voting power needed for a proposal to pass **/ function getMinimumVotingPowerNeeded(uint256 votingSupply) external view returns (uint256); /** * @dev Get proposition threshold constant value * @return the proposition threshold value (100 <=> 1%) **/ function PROPOSITION_THRESHOLD() external view returns (uint256); /** * @dev Get voting duration constant value * @return the voting duration value in seconds **/ function VOTING_DURATION() external view returns (uint256); /** * @dev Get the vote differential threshold constant value * to compare with % of for votes/total supply - % of against votes/total supply * @return the vote differential threshold value (100 <=> 1%) **/ function VOTE_DIFFERENTIAL() external view returns (uint256); /** * @dev Get quorum threshold constant value * to compare with % of for votes/total supply * @return the quorum threshold value (100 <=> 1%) **/ function MINIMUM_QUORUM() external view returns (uint256); /** * @dev precision helper: 100% = 10000 * @return one hundred percents with our chosen precision **/ function ONE_HUNDRED_WITH_PRECISION() external view returns (uint256); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { IDydxGovernor } from './IDydxGovernor.sol'; interface IExecutorWithTimelock { /** * @dev emitted when a new pending admin is set * @param newPendingAdmin address of the new pending admin **/ event NewPendingAdmin(address newPendingAdmin); /** * @dev emitted when a new admin is set * @param newAdmin address of the new admin **/ event NewAdmin(address newAdmin); /** * @dev emitted when a new delay (between queueing and execution) is set * @param delay new delay **/ event NewDelay(uint256 delay); /** * @dev emitted when a new (trans)action is Queued. * @param actionHash hash of the action * @param target address of the targeted contract * @param value wei value of the transaction * @param signature function signature of the transaction * @param data function arguments of the transaction or callData if signature empty * @param executionTime time at which to execute the transaction * @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target **/ event QueuedAction( bytes32 actionHash, address indexed target, uint256 value, string signature, bytes data, uint256 executionTime, bool withDelegatecall ); /** * @dev emitted when an action is Cancelled * @param actionHash hash of the action * @param target address of the targeted contract * @param value wei value of the transaction * @param signature function signature of the transaction * @param data function arguments of the transaction or callData if signature empty * @param executionTime time at which to execute the transaction * @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target **/ event CancelledAction( bytes32 actionHash, address indexed target, uint256 value, string signature, bytes data, uint256 executionTime, bool withDelegatecall ); /** * @dev emitted when an action is Cancelled * @param actionHash hash of the action * @param target address of the targeted contract * @param value wei value of the transaction * @param signature function signature of the transaction * @param data function arguments of the transaction or callData if signature empty * @param executionTime time at which to execute the transaction * @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target * @param resultData the actual callData used on the target **/ event ExecutedAction( bytes32 actionHash, address indexed target, uint256 value, string signature, bytes data, uint256 executionTime, bool withDelegatecall, bytes resultData ); /** * @dev Getter of the current admin address (should be governance) * @return The address of the current admin **/ function getAdmin() external view returns (address); /** * @dev Getter of the current pending admin address * @return The address of the pending admin **/ function getPendingAdmin() external view returns (address); /** * @dev Getter of the delay between queuing and execution * @return The delay in seconds **/ function getDelay() external view returns (uint256); /** * @dev Returns whether an action (via actionHash) is queued * @param actionHash hash of the action to be checked * keccak256(abi.encode(target, value, signature, data, executionTime, withDelegatecall)) * @return true if underlying action of actionHash is queued **/ function isActionQueued(bytes32 actionHash) external view returns (bool); /** * @dev Checks whether a proposal is over its grace period * @param governance Governance contract * @param proposalId Id of the proposal against which to test * @return true of proposal is over grace period **/ function isProposalOverGracePeriod(IDydxGovernor governance, uint256 proposalId) external view returns (bool); /** * @dev Getter of grace period constant * @return grace period in seconds **/ function GRACE_PERIOD() external view returns (uint256); /** * @dev Getter of minimum delay constant * @return minimum delay in seconds **/ function MINIMUM_DELAY() external view returns (uint256); /** * @dev Getter of maximum delay constant * @return maximum delay in seconds **/ function MAXIMUM_DELAY() external view returns (uint256); /** * @dev Function, called by Governance, that queue a transaction, returns action hash * @param target smart contract target * @param value wei value of the transaction * @param signature function signature of the transaction * @param data function arguments of the transaction or callData if signature empty * @param executionTime time at which to execute the transaction * @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target **/ function queueTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 executionTime, bool withDelegatecall ) external returns (bytes32); /** * @dev Function, called by Governance, that executes a transaction, returns the callData executed * @param target smart contract target * @param value wei value of the transaction * @param signature function signature of the transaction * @param data function arguments of the transaction or callData if signature empty * @param executionTime time at which to execute the transaction * @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target **/ function executeTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 executionTime, bool withDelegatecall ) external payable returns (bytes memory); /** * @dev Function, called by Governance, that cancels a transaction, returns action hash * @param target smart contract target * @param value wei value of the transaction * @param signature function signature of the transaction * @param data function arguments of the transaction or callData if signature empty * @param executionTime time at which to execute the transaction * @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target **/ function cancelTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 executionTime, bool withDelegatecall ) external returns (bytes32); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { IDydxGovernor } from './IDydxGovernor.sol'; import { IExecutorWithTimelock } from './IExecutorWithTimelock.sol'; interface IPriorityTimelockExecutor is IExecutorWithTimelock { /** * @dev emitted when a priority controller is added or removed * @param account address added or removed * @param isPriorityController whether the account is now a priority controller */ event PriorityControllerUpdated(address account, bool isPriorityController); /** * @dev emitted when a new priority period is set * @param priorityPeriod new priority period **/ event NewPriorityPeriod(uint256 priorityPeriod); /** * @dev emitted when an action is locked or unlocked for execution by a priority controller * @param actionHash hash of the action * @param isUnlockedForExecution whether the proposal is executable during the priority period */ event UpdatedActionPriorityStatus(bytes32 actionHash, bool isUnlockedForExecution); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../dependencies/open-zeppelin/SafeMath.sol'; import { IPriorityTimelockExecutor } from '../../interfaces/IPriorityTimelockExecutor.sol'; import { IDydxGovernor } from '../../interfaces/IDydxGovernor.sol'; /** * @title Time-locked executor contract mixin, inherited the governance executor contract. * @dev Contract that can queue, execute, cancel transactions voted by Governance * Queued transactions can be executed after a delay and until * Grace period is not over. * @author dYdX **/ contract PriorityTimelockExecutorMixin is IPriorityTimelockExecutor { using SafeMath for uint256; uint256 public immutable override GRACE_PERIOD; uint256 public immutable override MINIMUM_DELAY; uint256 public immutable override MAXIMUM_DELAY; address private _admin; address private _pendingAdmin; mapping(address => bool) private _isPriorityController; uint256 private _delay; uint256 private _priorityPeriod; mapping(bytes32 => bool) private _queuedTransactions; mapping(bytes32 => bool) private _priorityUnlockedTransactions; /** * @dev Constructor * @param admin admin address, that can call the main functions, (Governance) * @param delay minimum time between queueing and execution of proposal * @param gracePeriod time after `delay` while a proposal can be executed * @param minimumDelay lower threshold of `delay`, in seconds * @param maximumDelay upper threhold of `delay`, in seconds * @param priorityPeriod time at end of delay period during which a priority controller may “unlock” * @param priorityController address which may execute proposals during the priority window * the proposal for early execution **/ constructor( address admin, uint256 delay, uint256 gracePeriod, uint256 minimumDelay, uint256 maximumDelay, uint256 priorityPeriod, address priorityController ) { require(delay >= minimumDelay, 'DELAY_SHORTER_THAN_MINIMUM'); require(delay <= maximumDelay, 'DELAY_LONGER_THAN_MAXIMUM'); _validatePriorityPeriod(delay, priorityPeriod); _delay = delay; _priorityPeriod = priorityPeriod; _admin = admin; GRACE_PERIOD = gracePeriod; MINIMUM_DELAY = minimumDelay; MAXIMUM_DELAY = maximumDelay; emit NewDelay(delay); emit NewPriorityPeriod(priorityPeriod); emit NewAdmin(admin); _updatePriorityController(priorityController, true); } modifier onlyAdmin() { require(msg.sender == _admin, 'ONLY_BY_ADMIN'); _; } modifier onlyTimelock() { require(msg.sender == address(this), 'ONLY_BY_THIS_TIMELOCK'); _; } modifier onlyPendingAdmin() { require(msg.sender == _pendingAdmin, 'ONLY_BY_PENDING_ADMIN'); _; } modifier onlyPriorityController() { require(_isPriorityController[msg.sender], 'ONLY_BY_PRIORITY_CONTROLLER'); _; } /** * @dev Set the delay * @param delay delay between queue and execution of proposal **/ function setDelay(uint256 delay) public onlyTimelock { _validateDelay(delay); _validatePriorityPeriod(delay, _priorityPeriod); _delay = delay; emit NewDelay(delay); } /** * @dev Set the priority period * @param priorityPeriod time at end of delay period during which a priority controller may “unlock” * the proposal for early execution **/ function setPriorityPeriod(uint256 priorityPeriod) public onlyTimelock { _validatePriorityPeriod(_delay, priorityPeriod); _priorityPeriod = priorityPeriod; emit NewPriorityPeriod(priorityPeriod); } /** * @dev Function enabling pending admin to become admin **/ function acceptAdmin() public onlyPendingAdmin { _admin = msg.sender; _pendingAdmin = address(0); emit NewAdmin(msg.sender); } /** * @dev Setting a new pending admin (that can then become admin) * Can only be called by this executor (i.e via proposal) * @param newPendingAdmin address of the new admin **/ function setPendingAdmin(address newPendingAdmin) public onlyTimelock { _pendingAdmin = newPendingAdmin; emit NewPendingAdmin(newPendingAdmin); } /** * @dev Add or remove a priority controller. */ function updatePriorityController(address account, bool isPriorityController) public onlyTimelock { _updatePriorityController(account, isPriorityController); } /** * @dev Function, called by Governance, that queue a transaction, returns action hash * @param target smart contract target * @param value wei value of the transaction * @param signature function signature of the transaction * @param data function arguments of the transaction or callData if signature empty * @param executionTime time at which to execute the transaction * @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target * @return the action Hash **/ function queueTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 executionTime, bool withDelegatecall ) public override onlyAdmin returns (bytes32) { require(executionTime >= block.timestamp.add(_delay), 'EXECUTION_TIME_UNDERESTIMATED'); bytes32 actionHash = keccak256( abi.encode(target, value, signature, data, executionTime, withDelegatecall) ); _queuedTransactions[actionHash] = true; emit QueuedAction(actionHash, target, value, signature, data, executionTime, withDelegatecall); return actionHash; } /** * @dev Function, called by Governance, that cancels a transaction, returns action hash * @param target smart contract target * @param value wei value of the transaction * @param signature function signature of the transaction * @param data function arguments of the transaction or callData if signature empty * @param executionTime time at which to execute the transaction * @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target * @return the action Hash of the canceled tx **/ function cancelTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 executionTime, bool withDelegatecall ) public override onlyAdmin returns (bytes32) { bytes32 actionHash = keccak256( abi.encode(target, value, signature, data, executionTime, withDelegatecall) ); _queuedTransactions[actionHash] = false; emit CancelledAction( actionHash, target, value, signature, data, executionTime, withDelegatecall ); return actionHash; } /** * @dev Function, called by Governance, that executes a transaction, returns the callData executed * @param target smart contract target * @param value wei value of the transaction * @param signature function signature of the transaction * @param data function arguments of the transaction or callData if signature empty * @param executionTime time at which to execute the transaction * @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target * @return the callData executed as memory bytes **/ function executeTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 executionTime, bool withDelegatecall ) public payable override onlyAdmin returns (bytes memory) { bytes32 actionHash = keccak256( abi.encode(target, value, signature, data, executionTime, withDelegatecall) ); require(_queuedTransactions[actionHash], 'ACTION_NOT_QUEUED'); require(block.timestamp <= executionTime.add(GRACE_PERIOD), 'GRACE_PERIOD_FINISHED'); // Require either that: // - the timelock elapsed; or // - the transaction was unlocked by a priority controller, and we are in the priority // execution window. if (_priorityUnlockedTransactions[actionHash]) { require(block.timestamp >= executionTime.sub(_priorityPeriod), 'NOT_IN_PRIORITY_WINDOW'); } else { require(block.timestamp >= executionTime, 'TIMELOCK_NOT_FINISHED'); } _queuedTransactions[actionHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } bool success; bytes memory resultData; if (withDelegatecall) { require(msg.value >= value, "NOT_ENOUGH_MSG_VALUE"); // solium-disable-next-line security/no-call-value (success, resultData) = target.delegatecall(callData); } else { // solium-disable-next-line security/no-call-value (success, resultData) = target.call{value: value}(callData); } require(success, 'FAILED_ACTION_EXECUTION'); emit ExecutedAction( actionHash, target, value, signature, data, executionTime, withDelegatecall, resultData ); return resultData; } /** * @dev Function, called by a priority controller, to lock or unlock a proposal for execution * during the priority period. * @param actionHash hash of the action * @param isUnlockedForExecution whether the proposal is executable during the priority period */ function setTransactionPriorityStatus( bytes32 actionHash, bool isUnlockedForExecution ) public onlyPriorityController { require(_queuedTransactions[actionHash], 'ACTION_NOT_QUEUED'); _priorityUnlockedTransactions[actionHash] = isUnlockedForExecution; emit UpdatedActionPriorityStatus(actionHash, isUnlockedForExecution); } /** * @dev Getter of the current admin address (should be governance) * @return The address of the current admin **/ function getAdmin() external view override returns (address) { return _admin; } /** * @dev Getter of the current pending admin address * @return The address of the pending admin **/ function getPendingAdmin() external view override returns (address) { return _pendingAdmin; } /** * @dev Getter of the delay between queuing and execution * @return The delay in seconds **/ function getDelay() external view override returns (uint256) { return _delay; } /** * @dev Getter of the priority period, which is amount of time before mandatory * timelock delay that a proposal can be executed early only by a priority controller. * @return The priority period in seconds. **/ function getPriorityPeriod() external view returns (uint256) { return _priorityPeriod; } /** * @dev Getter for whether an address is a priority controller. * @param account address to check for being a priority controller * @return True if `account` is a priority controller, false if not. **/ function isPriorityController(address account) external view returns (bool) { return _isPriorityController[account]; } /** * @dev Returns whether an action (via actionHash) is queued * @param actionHash hash of the action to be checked * keccak256(abi.encode(target, value, signature, data, executionTime, withDelegatecall)) * @return true if underlying action of actionHash is queued **/ function isActionQueued(bytes32 actionHash) external view override returns (bool) { return _queuedTransactions[actionHash]; } /** * @dev Returns whether an action (via actionHash) has priority status * @param actionHash hash of the action to be checked * keccak256(abi.encode(target, value, signature, data, executionTime, withDelegatecall)) * @return true if underlying action of actionHash is queued **/ function hasPriorityStatus(bytes32 actionHash) external view returns (bool) { return _priorityUnlockedTransactions[actionHash]; } /** * @dev Checks whether a proposal is over its grace period * @param governance Governance contract * @param proposalId Id of the proposal against which to test * @return true of proposal is over grace period **/ function isProposalOverGracePeriod(IDydxGovernor governance, uint256 proposalId) external view override returns (bool) { IDydxGovernor.ProposalWithoutVotes memory proposal = governance.getProposalById(proposalId); return (block.timestamp > proposal.executionTime.add(GRACE_PERIOD)); } function _updatePriorityController(address account, bool isPriorityController) internal { _isPriorityController[account] = isPriorityController; emit PriorityControllerUpdated(account, isPriorityController); } function _validateDelay(uint256 delay) internal view { require(delay >= MINIMUM_DELAY, 'DELAY_SHORTER_THAN_MINIMUM'); require(delay <= MAXIMUM_DELAY, 'DELAY_LONGER_THAN_MAXIMUM'); } function _validatePriorityPeriod(uint256 delay, uint256 priorityPeriod) internal view { require(priorityPeriod <= delay, 'PRIORITY_PERIOD_LONGER_THAN_DELAY'); } receive() external payable {} } // Contracts by dYdX Foundation. Individual files are released under different licenses. // // https://dydx.community // https://github.com/dydxfoundation/governance-contracts // // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { PriorityTimelockExecutorMixin } from './PriorityTimelockExecutorMixin.sol'; import { ProposalValidatorMixin } from './ProposalValidatorMixin.sol'; /** * @title Time Locked, Validator, Executor Contract * @dev Contract * - Validate Proposal creations / cancellation * - Validate Vote Quorum and Vote success on proposal * - Queue, Execute, Cancel, successful proposals' transactions. * @author dYdX **/ contract PriorityExecutor is PriorityTimelockExecutorMixin, ProposalValidatorMixin { constructor( address admin, uint256 delay, uint256 gracePeriod, uint256 minimumDelay, uint256 maximumDelay, uint256 priorityPeriod, uint256 propositionThreshold, uint256 voteDuration, uint256 voteDifferential, uint256 minimumQuorum, address priorityExecutor ) PriorityTimelockExecutorMixin( admin, delay, gracePeriod, minimumDelay, maximumDelay, priorityPeriod, priorityExecutor ) ProposalValidatorMixin( propositionThreshold, voteDuration, voteDifferential, minimumQuorum ) {} }
Getter of the priority period, which is amount of time before mandatory timelock delay that a proposal can be executed early only by a priority controller. return The priority period in seconds./
function getPriorityPeriod() external view returns (uint256) { return _priorityPeriod; }
12,042,725
// Copyright 2021 Cartesi Pte. Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. /// @title Input library pragma solidity ^0.8.0; import {LibRollups} from "../libraries/LibRollups.sol"; library LibInput { using LibRollups for LibRollups.DiamondStorage; bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("Input.diamond.storage"); struct DiamondStorage { // always needs to keep track of two input boxes: // 1 for the input accumulation of next epoch // and 1 for the messages during current epoch. To save gas we alternate // between inputBox0 and inputBox1 bytes32[] inputBox0; bytes32[] inputBox1; uint256 inputDriveSize; // size of input flashdrive uint256 currentInputBox; } function diamondStorage() internal pure returns (DiamondStorage storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION; assembly { ds.slot := position } } /// @notice get input inside inbox of currently proposed claim /// @param ds diamond storage pointer /// @param index index of input inside that inbox /// @return hash of input at index index /// @dev currentInputBox being zero means that the inputs for /// the claimed epoch are on input box one function getInput(DiamondStorage storage ds, uint256 index) internal view returns (bytes32) { return ds.currentInputBox == 0 ? ds.inputBox1[index] : ds.inputBox0[index]; } /// @notice get number of inputs inside inbox of currently proposed claim /// @param ds diamond storage pointer /// @return number of inputs on that input box /// @dev currentInputBox being zero means that the inputs for /// the claimed epoch are on input box one function getNumberOfInputs(DiamondStorage storage ds) internal view returns (uint256) { return ds.currentInputBox == 0 ? ds.inputBox1.length : ds.inputBox0.length; } /// @notice add input to processed by next epoch /// @param ds diamond storage pointer /// @param input input to be understood by offchain machine /// @dev offchain code is responsible for making sure /// that input size is power of 2 and multiple of 8 since /// the offchain machine has a 8 byte word function addInput(DiamondStorage storage ds, bytes memory input) internal returns (bytes32) { return addInputFromSender(ds, input, msg.sender); } /// @notice add internal input to processed by next epoch /// @notice this function is to be reserved for internal usage only /// @notice for normal inputs, call `addInput` instead /// @param ds diamond storage pointer /// @param input input to be understood by offchain machine /// @dev offchain code is responsible for making sure /// that input size is power of 2 and multiple of 8 since /// the offchain machine has a 8 byte word function addInternalInput(DiamondStorage storage ds, bytes memory input) internal returns (bytes32) { return addInputFromSender(ds, input, address(this)); } /// @notice add input from a specific sender to processed by next epoch /// @notice this function is to be reserved for internal usage only /// @notice for normal inputs, call `addInput` instead /// @param ds diamond storage pointer /// @param input input to be understood by offchain machine /// @param sender input sender address /// @dev offchain code is responsible for making sure /// that input size is power of 2 and multiple of 8 since /// the offchain machine has a 8 byte word function addInputFromSender( DiamondStorage storage ds, bytes memory input, address sender ) internal returns (bytes32) { LibRollups.DiamondStorage storage rollupsDS = LibRollups .diamondStorage(); require(input.length <= ds.inputDriveSize, "input len: [0,driveSize]"); // notifyInput returns true if that input // belongs to a new epoch if (rollupsDS.notifyInput()) { swapInputBox(ds); } // points to correct inputBox bytes32[] storage inputBox = ds.currentInputBox == 0 ? ds.inputBox0 : ds.inputBox1; // get current epoch index uint256 currentEpoch = rollupsDS.getCurrentEpoch(); // keccak 64 bytes into 32 bytes bytes32 keccakMetadata = keccak256( abi.encode( sender, block.number, block.timestamp, currentEpoch, // epoch index inputBox.length // input index ) ); bytes32 keccakInput = keccak256(input); bytes32 inputHash = keccak256(abi.encode(keccakMetadata, keccakInput)); // add input to correct inbox inputBox.push(inputHash); emit InputAdded( currentEpoch, inputBox.length - 1, sender, block.timestamp, input ); return inputHash; } /// @notice called when a new input accumulation phase begins /// swap inbox to receive inputs for upcoming epoch /// @param ds diamond storage pointer function onNewInputAccumulation(DiamondStorage storage ds) internal { swapInputBox(ds); } /// @notice called when a new epoch begins, clears deprecated inputs /// @param ds diamond storage pointer function onNewEpoch(DiamondStorage storage ds) internal { // clear input box for new inputs // the current input box should be accumulating inputs // for the new epoch already. So we clear the other one. ds.currentInputBox == 0 ? delete ds.inputBox1 : delete ds.inputBox0; } /// @notice changes current input box /// @param ds diamond storage pointer function swapInputBox(DiamondStorage storage ds) internal { ds.currentInputBox = (ds.currentInputBox == 0) ? 1 : 0; } /// @notice input added /// @param epochNumber which epoch this input belongs to /// @param inputIndex index of the input just added /// @param sender msg.sender /// @param timestamp block.timestamp /// @param input input data event InputAdded( uint256 indexed epochNumber, uint256 indexed inputIndex, address sender, uint256 timestamp, bytes input ); }
get number of inputs inside inbox of currently proposed claim ds diamond storage pointer return number of inputs on that input box currentInputBox being zero means that the inputs for the claimed epoch are on input box one
function getNumberOfInputs(DiamondStorage storage ds) internal view returns (uint256) { return ds.currentInputBox == 0 ? ds.inputBox1.length : ds.inputBox0.length; }
12,960,316
./partial_match/1/0x7512200f2Ae3E1625a060d589348716F65923D75/sources/src/V3SaintbotToken.sol
Moves `amount` of tokens from `sender` to `recipient`. This internal function is equivalent to {transfer}, and can be used to e.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - `sender` cannot be the zero address. - `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`./
function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); }
3,690,491
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import '@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol'; import '@uniswap/lib/contracts/libraries/TransferHelper.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import './abstracts/Manageable.sol'; import './abstracts/Migrateable.sol'; contract Vesting is AccessControlUpgradeable, Manageable, Migrateable { event ItemCreated(address indexed token, uint256 amount); event BonusWithdrawn(address indexed vester, string name, uint256 amount); event VesterCreated(address indexed vester, string name, uint256 amount); event InitialWithdrawn(address indexed vester, string name, uint256 amount); event UnlockWithdrawn(address indexed vester, string name, uint256 amount, uint256 count); struct AddMultipleVesters { string[] _name; address[] _vester; uint104[] _amount; uint8[] _percentInitialAmount; uint8[] _percentAmountPerWithdraw; uint8[] _percentBonus; } struct Vested { // 1 words uint104 amount; uint104 totalWithdrawn; uint8 percentInitial; uint8 percentAmountPerWithdraw; uint8 percentBonus; uint8 withdrawals; uint8 status; bool bonusWithdrawn; } struct Item { address token; string name; uint256 amount; uint256 startTime; uint256 cliffTime; uint256 timeBetweenUnlocks; uint256 bonusUnlockTime; address signer; } struct VestedItem { Vested record; Item item; bool withdrawRemainder; bool canceled; } mapping(address => mapping(string => Vested)) public records; mapping(address => string[]) userVests; mapping(string => Item) public items; string[] internal names; /** New Variables */ mapping(string => bool) public withdrawRemainder; mapping(string => bool) public canceled; function addItem( address _token, string memory _name, uint256 _amount, uint256 _startTime, uint256 _cliffTime, uint256 _timeBetweenUnlocks, uint256 _bonusUnlockTime, address _signer ) external onlyManager { require(items[_name].amount == 0, 'VESTING: Item already exists'); TransferHelper.safeTransferFrom(address(_token), msg.sender, address(this), _amount); names.push(_name); items[_name] = Item({ token: _token, name: _name, amount: _amount, startTime: _startTime, cliffTime: _cliffTime, timeBetweenUnlocks: _timeBetweenUnlocks, bonusUnlockTime: _bonusUnlockTime, signer: _signer }); emit ItemCreated(_token, _amount); } function editItem( string memory _name, uint256 _startTime, uint256 _cliffTime, uint256 _timeBetweenUnlocks, uint256 _bonusUnlockTime ) external onlyManager { require(items[_name].amount != 0, 'VESTING: Item does not exist'); if (_startTime != 0) items[_name].startTime = _startTime; if (_cliffTime != 0) items[_name].cliffTime = _cliffTime; if (_timeBetweenUnlocks != 0) items[_name].timeBetweenUnlocks = _timeBetweenUnlocks; if (_bonusUnlockTime != 0) items[_name].bonusUnlockTime = _bonusUnlockTime; } /** @notice cancels a specific vesting */ function setCanceled(string memory _name, bool _canceled) external onlyManager { canceled[_name] = _canceled; } /** @notice allow vesters to just withdraw remainder without having to wait */ function setWithdrawRemainder(string memory _name, bool _remainder) external onlyManager { withdrawRemainder[_name] = _remainder; } function withdrawTokens(address _token, address _to) external onlyManager { IERC20(_token).transfer(_to, IERC20(_token).balanceOf(address(this))); } function addTokenToItem( string memory _name, address _token, uint256 _amount ) external onlyManager { require(items[_name].amount != 0, 'VESTING: Item does not exist'); TransferHelper.safeTransferFrom(address(_token), msg.sender, address(this), _amount); items[_name].amount += _amount; } function addVester( string memory _name, address _vester, uint8 _percentInitialAmount, uint8 _percentAmountPerWithdraw, uint8 _percentBonus, uint104 _amount ) internal { // ensure that the record does not already exist for vester && ensure the item exist require(records[_vester][_name].amount == 0, 'VESTING: Record already exists'); require(items[_name].amount != 0, 'VESTING: Item does not exist'); userVests[_vester].push(_name); records[_vester][_name] = Vested({ amount: _amount, totalWithdrawn: 0, percentAmountPerWithdraw: _percentAmountPerWithdraw, percentInitial: _percentInitialAmount, percentBonus: _percentBonus, withdrawals: 0, status: 0, bonusWithdrawn: false }); emit VesterCreated(_vester, _name, _amount); } function addMultipleVesters(AddMultipleVesters calldata vester) external onlyManager { for (uint256 i = 0; i < vester._name.length; i++) { addVester( vester._name[i], vester._vester[i], vester._percentInitialAmount[i], vester._percentAmountPerWithdraw[i], vester._percentBonus[i], vester._amount[i] ); } } function addVesterCryptography( bytes memory signature, string memory _name, uint8 _percentInitialAmount, uint8 _percentAmountPerWithdraw, uint8 _percentBonus, uint104 _amount ) external { bytes32 messageHash = sha256( abi.encode( _name, _percentInitialAmount, _percentAmountPerWithdraw, _percentBonus, _amount, msg.sender ) ); bool recovered = ECDSAUpgradeable.recover(messageHash, signature) == items[_name].signer; require(recovered == true, 'VESTING: Record not found'); addVester( _name, msg.sender, _percentInitialAmount, _percentAmountPerWithdraw, _percentBonus, _amount ); if (items[_name].startTime < block.timestamp) { withdraw(_name); } } function withdraw(string memory name) public { require(canceled[name] == false, 'VESTING: Vesting has been canceled'); Item memory record = items[name]; Vested storage userRecord = records[msg.sender][name]; require(userRecord.amount != 0, 'VESTING: User Record does not exist'); require(userRecord.totalWithdrawn < userRecord.amount, 'VESTING: Exceeds allowed amount'); uint256 amountToWithdraw; uint256 totalAmountToWithdraw; if (withdrawRemainder[name]) { uint256 leftToWithdraw = userRecord.amount - userRecord.totalWithdrawn; userRecord.totalWithdrawn = userRecord.amount; // Finally transfer and call it a day */ IERC20(record.token).transfer(msg.sender, leftToWithdraw); // Call for bonus bonus(name); emit UnlockWithdrawn(msg.sender, name, leftToWithdraw, userRecord.withdrawals); return; } // Initial withdraw */ if (userRecord.withdrawals == 0) { userRecord.withdrawals++; // Ensure initial withdraw is allowed */ // console.log('Start time %s', record.startTime); require(record.startTime < block.timestamp, 'VESTING: Has not begun yet'); // Get amount to withdraw with some percentage magic */ amountToWithdraw = (uint256(userRecord.percentInitial) * uint256(userRecord.amount)) / 100; // set withdrawn first */ userRecord.totalWithdrawn += uint104(amountToWithdraw); // Ensure our managers aren't allowing users to get more then they should */ require( userRecord.totalWithdrawn <= userRecord.amount, 'VESTING: Exceeds allowed amount' ); // set amount to be paid */ totalAmountToWithdraw = amountToWithdraw; emit InitialWithdrawn(msg.sender, name, amountToWithdraw); } if ( record.startTime + record.cliffTime < block.timestamp && userRecord.percentInitial != 100 ) { // Ensure time started */ // console.log('Start time + cliff time %s', record.startTime + record.cliffTime); uint256 maxNumberOfWithdrawals = userRecord.percentAmountPerWithdraw == 0 ? 1 : ((100 - userRecord.percentInitial) / userRecord.percentAmountPerWithdraw); //example for 15% initial and 17% for 5 months, the max number will end up being 6 // Get number of allowed withdrawals by doing some date magic */ uint256 numberOfAllowedWithdrawals = ((block.timestamp - (record.startTime + record.cliffTime)) / record.timeBetweenUnlocks) + 1; // add one for initial withdraw numberOfAllowedWithdrawals = numberOfAllowedWithdrawals < maxNumberOfWithdrawals ? numberOfAllowedWithdrawals : maxNumberOfWithdrawals; // Ensure the amount of withdrawals a user has is less then numberOfAllowed */ if ( numberOfAllowedWithdrawals >= userRecord.withdrawals && record.timeBetweenUnlocks != 0 ) { uint256 withdrawalsToPay = numberOfAllowedWithdrawals - userRecord.withdrawals + 1; amountToWithdraw = ((uint256(userRecord.percentAmountPerWithdraw) * uint256(userRecord.amount)) / 100) * withdrawalsToPay; // set withdrawn first */ userRecord.totalWithdrawn += uint104(amountToWithdraw); userRecord.withdrawals += uint8(withdrawalsToPay); totalAmountToWithdraw += amountToWithdraw; emit UnlockWithdrawn(msg.sender, name, amountToWithdraw, userRecord.withdrawals); } } // Finally transfer and call it a day */ IERC20(record.token).transfer(msg.sender, totalAmountToWithdraw); } function bonus(string memory name) public { require(canceled[name] == false, 'VESTING: Vesting has been canceled'); Item memory record = items[name]; Vested storage userRecord = records[msg.sender][name]; require(userRecord.bonusWithdrawn == false, 'VESTING: Bonus already withdrawn'); if (!withdrawRemainder[name]) { require(record.bonusUnlockTime < block.timestamp, 'VESTING: Bonus is not unlocked yet'); } userRecord.bonusWithdrawn = true; // Withdraw bonus IERC20(record.token).transfer( msg.sender, (uint256(userRecord.percentBonus) * uint256(userRecord.amount)) / 100 ); emit BonusWithdrawn( msg.sender, name, (uint256(userRecord.percentBonus) * uint256(userRecord.amount)) / 100 ); } // Getters && Setters ------------------------------------------------------------------ */ function getNamesLength() public view returns (uint256) { return names.length; } function getNames(uint256 from, uint256 to) public view returns (string[] memory) { string[] memory _names = new string[](to - from); uint256 count = 0; for (uint256 i = from; i < to; i++) { _names[count] = names[i]; count++; } return _names; } function getItems(uint256 from, uint256 to) public view returns (Item[] memory) { Item[] memory _items = new Item[](to - from); uint256 count = 0; for (uint256 i = from; i < to; i++) { _items[count] = items[names[i]]; count++; } return _items; } function getAllItems() public view returns (Item[] memory) { uint256 length = getNamesLength(); Item[] memory _items = new Item[](length); for (uint256 i = 0; i < length; i++) { _items[i] = items[names[i]]; } return _items; } function getUserVestsLength(address user) public view returns (uint256) { return userVests[user].length; } function getUserItems( address user, uint256 from, uint256 to ) public view returns (VestedItem[] memory) { VestedItem[] memory _items = new VestedItem[](to - from); string[] memory keys = userVests[user]; uint256 count = 0; for (uint256 i = from; i < to; i++) { _items[count].item = items[keys[i]]; _items[count].record = records[user][keys[i]]; _items[count].canceled = canceled[keys[i]]; _items[count].withdrawRemainder = withdrawRemainder[keys[i]]; count++; } return _items; } // Initialize ------------------------------------------------------------------ */ function initialize(address _manager, address _migrator) external initializer { _setupRole(MANAGER_ROLE, _manager); _setupRole(MIGRATOR_ROLE, _migrator); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { 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 AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } 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(IAccessControlUpgradeable).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()); } } uint256[49] private __gap; } // 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 ECDSAUpgradeable { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} 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)); } } pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint 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: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint 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: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint 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: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // 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 "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; abstract contract Manageable is AccessControlUpgradeable { bytes32 public constant MANAGER_ROLE = keccak256("MANAGER_ROLE"); modifier onlyManager() { require( hasRole(MANAGER_ROLE, msg.sender), "Caller is not a manager" ); _; } /** Roles management - only for multi sig address */ function setupRole(bytes32 role, address account) external onlyManager { _setupRole(role, account); } function isManager(address account) external view returns (bool) { return hasRole(MANAGER_ROLE, account); } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; abstract contract Migrateable is AccessControlUpgradeable { bytes32 public constant MIGRATOR_ROLE = keccak256("MIGRATOR_ROLE"); modifier onlyMigrator() { require( hasRole(MIGRATOR_ROLE, msg.sender), "Caller is not a migrator" ); _; } } // 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: MIT 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 initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version 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 a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Finally transfer and call it a day / Call for bonus Initial withdraw / Ensure initial withdraw is allowed / console.log('Start time %s', record.startTime); Get amount to withdraw with some percentage magic / set withdrawn first / Ensure our managers aren't allowing users to get more then they should / set amount to be paid / Ensure time started / console.log('Start time + cliff time %s', record.startTime + record.cliffTime); Get number of allowed withdrawals by doing some date magic / Ensure the amount of withdrawals a user has is less then numberOfAllowed / set withdrawn first /
function withdraw(string memory name) public { require(canceled[name] == false, 'VESTING: Vesting has been canceled'); Item memory record = items[name]; Vested storage userRecord = records[msg.sender][name]; require(userRecord.amount != 0, 'VESTING: User Record does not exist'); require(userRecord.totalWithdrawn < userRecord.amount, 'VESTING: Exceeds allowed amount'); uint256 amountToWithdraw; uint256 totalAmountToWithdraw; if (withdrawRemainder[name]) { uint256 leftToWithdraw = userRecord.amount - userRecord.totalWithdrawn; userRecord.totalWithdrawn = userRecord.amount; IERC20(record.token).transfer(msg.sender, leftToWithdraw); bonus(name); emit UnlockWithdrawn(msg.sender, name, leftToWithdraw, userRecord.withdrawals); return; } if (userRecord.withdrawals == 0) { userRecord.withdrawals++; require(record.startTime < block.timestamp, 'VESTING: Has not begun yet'); amountToWithdraw = (uint256(userRecord.percentInitial) * uint256(userRecord.amount)) / 100; userRecord.totalWithdrawn += uint104(amountToWithdraw); require( userRecord.totalWithdrawn <= userRecord.amount, 'VESTING: Exceeds allowed amount' ); totalAmountToWithdraw = amountToWithdraw; emit InitialWithdrawn(msg.sender, name, amountToWithdraw); } if ( record.startTime + record.cliffTime < block.timestamp && userRecord.percentInitial != 100 ) { uint256 maxNumberOfWithdrawals = userRecord.percentAmountPerWithdraw == 0 ? 1 uint256 numberOfAllowedWithdrawals = ((block.timestamp - (record.startTime + record.cliffTime)) / numberOfAllowedWithdrawals = numberOfAllowedWithdrawals < maxNumberOfWithdrawals ? numberOfAllowedWithdrawals : maxNumberOfWithdrawals; if ( numberOfAllowedWithdrawals >= userRecord.withdrawals && record.timeBetweenUnlocks != 0 ) { uint256 withdrawalsToPay = numberOfAllowedWithdrawals - userRecord.withdrawals + 1; amountToWithdraw = ((uint256(userRecord.percentAmountPerWithdraw) * uint256(userRecord.amount)) / 100) * withdrawalsToPay; userRecord.totalWithdrawn += uint104(amountToWithdraw); userRecord.withdrawals += uint8(withdrawalsToPay); totalAmountToWithdraw += amountToWithdraw; emit UnlockWithdrawn(msg.sender, name, amountToWithdraw, userRecord.withdrawals); } } }
6,178,256
pragma solidity 0.5.6; // Copyright BigchainDB GmbH and Ocean Protocol contributors // SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) // Code is Apache-2.0 and docs are CC-BY-4.0 import './TemplateStoreLibrary.sol'; import 'openzeppelin-eth/contracts/ownership/Ownable.sol'; /** * @title Template Store Manager * @author Ocean Protocol Team * * @dev Implementation of the Template Store Manager. * Templates are blueprints for modular SEAs. When creating an Agreement, * a templateId defines the condition and reward types that are instantiated * in the ConditionStore. This contract manages the life cycle * of the template ( Propose --> Approve --> Revoke ). * For more information please refer to this link: * https://github.com/oceanprotocol/OEPs/issues/132 * TODO: link to OEP * */ contract TemplateStoreManager is Ownable { using TemplateStoreLibrary for TemplateStoreLibrary.TemplateList; TemplateStoreLibrary.TemplateList internal templateList; modifier onlyOwnerOrTemplateOwner(address _id){ require( isOwner() || templateList.templates[_id].owner == msg.sender, 'Invalid UpdateRole' ); _; } /** * @dev initialize TemplateStoreManager Initializer * Initializes Ownable. Only on contract creation. * @param _owner refers to the owner of the contract */ function initialize( address _owner ) public initializer() { require( _owner != address(0), 'Invalid address' ); Ownable.initialize(_owner); } /** * @notice proposeTemplate proposes a new template * @param _id unique template identifier which is basically * the template contract address */ function proposeTemplate(address _id) external returns (uint size) { return templateList.propose(_id); } /** * @notice approveTemplate approves a template * @param _id unique template identifier which is basically * the template contract address. Only template store * manager owner (i.e OPNF) can approve this template. */ function approveTemplate(address _id) external onlyOwner { return templateList.approve(_id); } /** * @notice revokeTemplate revoke a template * @param _id unique template identifier which is basically * the template contract address. Only template store * manager owner (i.e OPNF) or template owner * can revoke this template. */ function revokeTemplate(address _id) external onlyOwnerOrTemplateOwner(_id) { return templateList.revoke(_id); } /** * @notice getTemplate get more information about a template * @param _id unique template identifier which is basically * the template contract address. * @return template status, template owner, last updated by and * last updated at. */ function getTemplate(address _id) external view returns ( TemplateStoreLibrary.TemplateState state, address owner, address lastUpdatedBy, uint blockNumberUpdated ) { state = templateList.templates[_id].state; owner = templateList.templates[_id].owner; lastUpdatedBy = templateList.templates[_id].lastUpdatedBy; blockNumberUpdated = templateList.templates[_id].blockNumberUpdated; } /** * @notice getTemplateListSize number of templates * @return number of templates */ function getTemplateListSize() external view returns (uint size) { return templateList.templateIds.length; } /** * @notice isTemplateApproved check whether the template is approved * @param _id unique template identifier which is basically * the template contract address. * @return true if the template is approved */ function isTemplateApproved(address _id) external view returns (bool) { return templateList.templates[_id].state == TemplateStoreLibrary.TemplateState.Approved; } }
getTemplate get more information about a template _id unique template identifier which is basically the template contract address. return template status, template owner, last updated by and last updated at./
function getTemplate(address _id) external view returns ( TemplateStoreLibrary.TemplateState state, address owner, address lastUpdatedBy, uint blockNumberUpdated ) { state = templateList.templates[_id].state; owner = templateList.templates[_id].owner; lastUpdatedBy = templateList.templates[_id].lastUpdatedBy; blockNumberUpdated = templateList.templates[_id].blockNumberUpdated; }
7,241,409
//SPDX-License-Identifier: Unlicense pragma solidity >=0.7.6; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import '@uniswap/v3-core/contracts/libraries/TickMath.sol'; import '@uniswap/v3-core/contracts/libraries/FullMath.sol'; import '@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol'; import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol'; import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol'; import '@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol'; import '@uniswap/v3-periphery/contracts/interfaces/external/IWETH9.sol'; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import './Exchanger.sol'; contract Peanut is ERC20, Ownable { using SafeMath for uint256; using SafeERC20 for ERC20; uint256 private _currentPositionId; bool public paused = false; uint256 public currentVaultFee = 0; uint256 public currentManagementFeePercent; uint256 public maxPoolLimitInToken0; uint256 public maxPoolLimitInToken1; uint256 public percentOfAmountMin; address public vaultAddress; address public managerAddress; address public exchanger; uint256 private constant hundredPercent = 1000000; uint256 private constant MAX_BASIS_POINTS = 10**18; INonfungiblePositionManager public constant uniswapV3PositionsNFT = INonfungiblePositionManager(0xC36442b4a4522E871399CD717aBDD847Ab11FE88); address public constant uniswapV3Router = 0xE592427A0AEce92De3Edee1F18E0157C05861564; address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; int24 public immutable tickSpacing; uint24 public immutable protocolFee; uint256 public immutable maxVaultFeePercent; uint256 public immutable maxManagementFeePercent; address public immutable uniswapV3Pool; address public immutable token0; address public immutable token1; uint256 private immutable decimalsToken0; uint256 private immutable decimalsToken1; struct Balances { uint256 amount0; uint256 amount1; } struct Ticks { int24 tickLower; int24 tickUpper; } /// @notice Modifier for check msg.sender for permission functions modifier isAllowedCaller() { require(msg.sender == owner() || msg.sender == managerAddress); _; } modifier isPaused() { require(!paused); _; } receive() external payable { require(msg.sender == WETH || msg.sender == address(uniswapV3PositionsNFT)); } constructor( address _uniswapV3Pool, address _owner, address _manager, address _exchanger, uint256 _currentManagementFeePercent, uint256 _maxVaultFee, uint256 _maxManagementFeePercent, uint256 _maxPoolLimitInToken0, uint256 _maxPoolLimitInToken1, uint256 _percentOfAmountMin ) ERC20('Smart LP', 'SLP') { uniswapV3Pool = _uniswapV3Pool; exchanger = _exchanger; managerAddress = _manager; currentManagementFeePercent = _currentManagementFeePercent; maxVaultFeePercent = _maxVaultFee; maxManagementFeePercent = _maxManagementFeePercent; maxPoolLimitInToken0 = _maxPoolLimitInToken0; maxPoolLimitInToken1 = _maxPoolLimitInToken1; percentOfAmountMin = _percentOfAmountMin; transferOwnership(_owner); vaultAddress = owner(); IUniswapV3Pool UniswapV3Pool = IUniswapV3Pool(_uniswapV3Pool); token0 = UniswapV3Pool.token0(); token1 = UniswapV3Pool.token1(); protocolFee = UniswapV3Pool.fee(); tickSpacing = UniswapV3Pool.tickSpacing(); decimalsToken0 = 10**(ERC20(UniswapV3Pool.token0()).decimals()); decimalsToken1 = 10**(ERC20(UniswapV3Pool.token1()).decimals()); } //Events event PositionChanged( address addressSender, uint256 newPositionId, uint160 sqrtPriceLowerX96, uint160 sqrtPriceUpperX96 ); event LiquidityAdded(address addressSender, uint128 liquidity, uint256 amount0, uint256 amount1); event LiquidityRemoved( address addressSender, uint128 liquidity, uint256 amount0, uint256 amount1 ); event Claimed( address addressSender, uint256 amountLP, uint256 amount0Claimed, uint256 amount1Claimed ); event FeeCollected(address addressSender, uint256 amount0Collected, uint256 amount1Collected); //Functions function getCurrentSqrtPrice() public view returns (uint160 sqrtPriceX96) { (sqrtPriceX96, , , , , , ) = IUniswapV3Pool(uniswapV3Pool).slot0(); } function getCurrentPositionId() public view returns (uint256) { return _currentPositionId; } function getTickForSqrtPrice(uint160 sqrtPriceX96) public view returns (int24) { int24 tick = TickMath.getTickAtSqrtRatio(sqrtPriceX96); int24 tickCorrection = tick % int24(tickSpacing); return tick - tickCorrection; } function getUserShare(address account) public view returns (uint256) { if (totalSupply() == 0) { return 0; } return balanceOf(account).mul(hundredPercent).div(totalSupply()); } function getCurrentAmountsForPosition() public view returns (uint256 amount0, uint256 amount1) { require(_currentPositionId > 0); (, , , , , int24 tickLower, int24 tickUpper, uint128 liquidity, , , , ) = uniswapV3PositionsNFT .positions(_currentPositionId); (uint160 sqrtPriceCurrentX96, , , , , , ) = IUniswapV3Pool(uniswapV3Pool).slot0(); uint160 sqrtPriceLowerX96 = TickMath.getSqrtRatioAtTick(tickLower); uint160 sqrtPriceUpperX96 = TickMath.getSqrtRatioAtTick(tickUpper); (amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity( sqrtPriceCurrentX96, sqrtPriceLowerX96, sqrtPriceUpperX96, liquidity ); } function getBalances() public view returns (uint256 amount0, uint256 amount1) { return _getBalances(0); } function setPercentOfAmountMin(uint256 _percentOfAmountMin) public onlyOwner { percentOfAmountMin = _percentOfAmountMin; } function setCurrentManagementFeePercent(uint256 _currentManagementFeePercent) public onlyOwner { require(_currentManagementFeePercent <= maxManagementFeePercent); currentManagementFeePercent = _currentManagementFeePercent; } function setMaxPoolLimit(uint256 _maxPoolLimitInToken0, uint256 _maxPoolLimitInToken1) public onlyOwner { maxPoolLimitInToken0 = _maxPoolLimitInToken0; maxPoolLimitInToken1 = _maxPoolLimitInToken1; } function setExchangerStrategy(address _address) public onlyOwner { exchanger = _address; } function setVault(address _address) public onlyOwner { vaultAddress = _address; } function setCurrentVaultFee(uint256 _vaultFee) public onlyOwner { require(_vaultFee <= maxVaultFeePercent); currentVaultFee = _vaultFee; } function setManager(address _address) external onlyOwner { managerAddress = _address; } function setPaused(bool _paused) public onlyOwner { paused = _paused; } function createPositionForGivenSqrtPrices( uint160 sqrtPriceLowerX96, uint160 sqrtPriceUpperX96, uint256 amount0Desired, uint256 amount1Desired, uint256 amount0OutMin, uint256 amount1OutMin ) public payable onlyOwner isPaused { require(_currentPositionId == 0); // Check for token allowance _checkAllowance(token0, amount0Desired); _checkAllowance(token1, amount1Desired); // Receive tokens _transferTokenFrom(token0, msg.sender, amount0Desired); _transferTokenFrom(token1, msg.sender, amount1Desired); // Create position in uniswap uint128 liquidity = _createPositionForGivenSqrtPrices( sqrtPriceLowerX96, sqrtPriceUpperX96, amount0OutMin, amount1OutMin ); // Refund tokens from uniswap _refundFromUniswap(); // Mint tokens to msg.sender _mint(msg.sender, liquidity); // Return tokens to caller _refund(Balances(0, 0)); } function changePositionForGivenSqrtPrices( uint160 sqrtPriceLowerX96, uint160 sqrtPriceUpperX96, uint256 amount0OutMin, uint256 amount1OutMin ) public isAllowedCaller isPaused { require(_currentPositionId > 0); (, , , , , , , uint128 liquidity, , , , ) = uniswapV3PositionsNFT.positions(_currentPositionId); _removeLiquidity(liquidity); _createPositionForGivenSqrtPrices( sqrtPriceLowerX96, sqrtPriceUpperX96, amount0OutMin, amount1OutMin ); // Refund tokens from uniswap _refundFromUniswap(); emit PositionChanged(msg.sender, _currentPositionId, sqrtPriceLowerX96, sqrtPriceUpperX96); } function addLiquidity( uint256 amount0, uint256 amount1, uint256 amount0OutMin, uint256 amount1OutMin ) public payable isPaused { require(_currentPositionId > 0); (uint256 amount0CurrentLiq, uint256 amount1CurrentLiq) = getCurrentAmountsForPosition(); require( amount0CurrentLiq.add(amount0) <= maxPoolLimitInToken0 && amount1CurrentLiq.add(amount1) <= maxPoolLimitInToken1 ); _checkAllowance(token0, amount0); _checkAllowance(token1, amount1); // Collect tokens from position to the contract. // Get balance of contract without user tokens, but with collected ones. // Swap them in order to have a right proportion. // Increase liquidity. _collectFeeAndReinvest(amount0OutMin, amount1OutMin, msg.value); // Contract balance of tokens after collecting fee and increasing liquidity (without user eth amount). (uint256 contractAmount0, uint256 contractAmount1) = _getBalances(msg.value); // Receive tokens from user. _transferTokenFrom(token0, msg.sender, amount0); _transferTokenFrom(token1, msg.sender, amount1); (, , , , , , , uint128 prevLiquidity, , , , ) = uniswapV3PositionsNFT.positions( _currentPositionId ); // Add user tokens to position liquidity. uint128 liquidity = _addUserLiquidity( Balances(contractAmount0, contractAmount1), amount0, amount1 ); uint256 amount = _calculateAmountForLiquidity(prevLiquidity, liquidity); _refundFromUniswap(); _mint(msg.sender, amount); _refund(Balances(contractAmount0, contractAmount1)); emit LiquidityAdded(msg.sender, liquidity, amount0, amount1); } function collectFee(uint256 amount0OutMin, uint256 amount1OutMin) public isAllowedCaller isPaused { _collectFeeAndReinvest(amount0OutMin, amount1OutMin, 0); } function _collectFee() private returns (bool) { (uint256 amount0Collected, uint256 amount1Collected) = uniswapV3PositionsNFT.collect( INonfungiblePositionManager.CollectParams({ tokenId: _currentPositionId, recipient: address(this), amount0Max: type(uint128).max, amount1Max: type(uint128).max }) ); if (amount0Collected > 0 || amount1Collected > 0) { _withdraw(_isWETH(token0) ? amount0Collected : amount1Collected); _transferManagementFee(amount0Collected, amount1Collected); emit FeeCollected(msg.sender, amount0Collected, amount1Collected); return true; } return false; } function _collectFeeAndReinvest( uint256 amount0OutMin, uint256 amount1OutMin, uint256 userMsgValue ) private isPaused { require(_currentPositionId > 0); bool isCollected = _collectFee(); if (!isCollected) { return; } // Contract balance of tokens after collect and before swap (without user amount of eth). (uint256 contractAmount0, uint256 contractAmount1) = _getBalances(userMsgValue); (, , , , , int24 tickLower, int24 tickUpper, , , , , ) = uniswapV3PositionsNFT.positions( _currentPositionId ); (, , bool shouldIncreaseLiquidity) = _swapTokensStrategy( Balances(contractAmount0, contractAmount1), Ticks(tickLower, tickUpper), amount0OutMin, amount1OutMin ); if (!shouldIncreaseLiquidity) { return; } // Contract balance of tokens after swap (without user amount of eth). (contractAmount0, contractAmount1) = _getBalances(userMsgValue); uint256 valueETH = 0; if (_isWETH(token0) || _isWETH(token1)) { valueETH = _isWETH(token0) ? contractAmount0 : contractAmount1; } _increaseAllowance(token0, address(uniswapV3PositionsNFT), contractAmount0); _increaseAllowance(token1, address(uniswapV3PositionsNFT), contractAmount1); uniswapV3PositionsNFT.increaseLiquidity{ value: valueETH }( INonfungiblePositionManager.IncreaseLiquidityParams({ tokenId: _currentPositionId, amount0Desired: contractAmount0, amount1Desired: contractAmount1, amount0Min: _calculateAmountMin(contractAmount0), amount1Min: _calculateAmountMin(contractAmount1), deadline: 10000000000 }) ); // Refund tokens from uniswap. _refundFromUniswap(); } function claim( uint256 amount, uint256 amount0OutMin, uint256 amount1OutMin ) public isPaused { (uint256 amount0Decreased, uint256 amount1Decreased) = _claim( amount, amount0OutMin, amount1OutMin ); _transferToken(token0, msg.sender, amount0Decreased); _transferToken(token1, msg.sender, amount1Decreased); emit Claimed(msg.sender, amount, amount0Decreased, amount1Decreased); } function claimToken( address token, uint256 amount, uint256 amount0OutMin, uint256 amount1OutMin ) public isPaused { require(token == token0 || token == token1); (uint256 amount0WithoutFee, uint256 amount1WithoutFee) = _claim( amount, amount0OutMin, amount1OutMin ); uint256 amountForToken; (uint256 amountOutToken, address secondToken, uint256 amountDecreased) = token == token0 ? (amount0WithoutFee, token1, amount1WithoutFee) : (amount1WithoutFee, token0, amount0WithoutFee); if (amountDecreased > 0) { (amountForToken) = _swapExact(secondToken, amountDecreased, 0); } _transferToken(token, msg.sender, amountOutToken.add(amountForToken)); emit Claimed(msg.sender, amount, amount0WithoutFee, amount1WithoutFee); } // Private functions function _isWETH(address token) private pure returns (bool) { return token == WETH; } function _checkAllowance(address token, uint256 amount) private view { if (_isWETH(token)) { require(amount <= msg.value); return; } require(ERC20(token).allowance(msg.sender, address(this)) >= amount); } function _transferToken( address token, address receiver, uint256 amount ) private { if (_isWETH(token)) { TransferHelper.safeTransferETH(receiver, amount); return; } TransferHelper.safeTransfer(token, receiver, amount); } function _createPositionForGivenSqrtPrices( uint160 sqrtPriceLowerX96, uint160 sqrtPriceUpperX96, uint256 amount0OutMin, uint256 amount1OutMin ) private returns (uint128) { int24 tickLower = getTickForSqrtPrice(sqrtPriceLowerX96); int24 tickUpper = getTickForSqrtPrice(sqrtPriceUpperX96); (uint256 amount0ForSwap, uint256 amount1ForSwap) = getBalances(); (uint256 amount0, uint256 amount1, ) = _swapTokensStrategy( Balances(amount0ForSwap, amount1ForSwap), Ticks(tickLower, tickUpper), amount0OutMin, amount1OutMin ); require(tickUpper > tickLower); _increaseAllowance(token0, address(uniswapV3PositionsNFT), amount0); _increaseAllowance(token1, address(uniswapV3PositionsNFT), amount1); uint256 valueETH = 0; if (_isWETH(token0) || _isWETH(token1)) { valueETH = _isWETH(token0) ? amount0 : amount1; } (uint256 tokenId, uint128 liquidity, , ) = uniswapV3PositionsNFT.mint{ value: valueETH }( INonfungiblePositionManager.MintParams({ token0: token0, token1: token1, fee: protocolFee, tickLower: tickLower, tickUpper: tickUpper, amount0Desired: amount0, amount1Desired: amount1, amount0Min: _calculateAmountMin(amount0), amount1Min: _calculateAmountMin(amount1), recipient: address(this), deadline: 10000000000 }) ); _currentPositionId = tokenId; return liquidity; } function _increaseAllowance( address token, address receiver, uint256 amount ) private { if (_isWETH(token)) { return; } uint256 allowed = ERC20(token).allowance(address(this), receiver); if (allowed != 0) { ERC20(token).safeDecreaseAllowance(receiver, allowed); } ERC20(token).safeIncreaseAllowance(receiver, amount); } function _swapTokensStrategy( Balances memory balances, Ticks memory ticks, uint256 amount0OutMin, uint256 amount1OutMin ) internal returns ( uint256 amount0, uint256 amount1, bool isRebalanced ) { ( uint256 amount0ToSwap, uint256 amount1ToSwap, uint256 amount0AfterSwap, uint256 amount1AfterSwap, ) = Exchanger(exchanger).rebalance( ticks.tickLower, ticks.tickUpper, balances.amount0, balances.amount1 ); if (amount0AfterSwap == 0 || amount1AfterSwap == 0) { isRebalanced = false; return (0, 0, isRebalanced); } isRebalanced = true; if (amount0ToSwap != 0) { _swapExact(token0, amount0ToSwap, amount1OutMin); } else if (amount1ToSwap != 0) { _swapExact(token1, amount1ToSwap, amount0OutMin); } (amount0, amount1) = getBalances(); } function _getBalances(uint256 transferredAmount) private view returns (uint256 amount0, uint256 amount1) { amount0 = _isWETH(token0) ? address(this).balance.sub(transferredAmount) : ERC20(token0).balanceOf(address(this)); amount1 = _isWETH(token1) ? address(this).balance.sub(transferredAmount) : ERC20(token1).balanceOf(address(this)); } function _swapExact( address token, uint256 amount, uint256 amountOutMin ) private returns (uint256 amountOut) { return _isWETH(token) ? _swapExactETHToTokens(amount, amountOutMin) : _swapExactTokens(token, amount, amountOutMin); } function _swapExactTokens( address tokenIn, uint256 amountIn, uint256 amountOutMin ) private returns (uint256 amountOut) { _increaseAllowance(tokenIn, uniswapV3Router, amountIn); address tokenOut = tokenIn == token0 ? token1 : token0; (amountOut) = ISwapRouter(uniswapV3Router).exactInputSingle( ISwapRouter.ExactInputSingleParams({ tokenIn: tokenIn, tokenOut: tokenOut, fee: protocolFee, recipient: address(this), deadline: 10000000000, amountIn: amountIn, amountOutMinimum: amountOutMin, sqrtPriceLimitX96: 0 }) ); if (_isWETH(tokenOut)) { IWETH9(tokenOut).withdraw(IWETH9(tokenOut).balanceOf(address(this))); } } function _swapExactETHToTokens(uint256 amountIn, uint256 amountOutMin) private returns (uint256 amountOut) { require(_isWETH(token0) || _isWETH(token1)); (address tokenInWETH, address tokenOutNotWETH) = _isWETH(token0) ? (token0, token1) : (token1, token0); (amountOut) = ISwapRouter(uniswapV3Router).exactInputSingle{ value: amountIn }( ISwapRouter.ExactInputSingleParams({ tokenIn: tokenInWETH, tokenOut: tokenOutNotWETH, fee: protocolFee, recipient: address(this), deadline: 10000000000, amountIn: amountIn, amountOutMinimum: amountOutMin, sqrtPriceLimitX96: 0 }) ); } function _refund(Balances memory startBalances) private { (uint256 amount0, uint256 amount1) = getBalances(); _refundETHOrToken(amount0, startBalances.amount0, token0); _refundETHOrToken(amount1, startBalances.amount1, token1); } function _refundETHOrToken( uint256 balance, uint256 startBalance, address token ) private { if (balance > startBalance) { _isWETH(token) ? TransferHelper.safeTransferETH(msg.sender, balance - startBalance) : TransferHelper.safeTransfer(token, msg.sender, balance - startBalance); } } function _removeLiquidity(uint128 liquidity) private returns (uint256 amount0, uint256 amount1) { (uint256 amount0CurrentLiq, uint256 amount1CurrentLiq) = getCurrentAmountsForPosition(); (uint256 amount0Decreased, uint256 amount1Decreased) = uniswapV3PositionsNFT.decreaseLiquidity( INonfungiblePositionManager.DecreaseLiquidityParams({ tokenId: _currentPositionId, liquidity: liquidity, amount0Min: _calculateAmountMin(amount0CurrentLiq), amount1Min: _calculateAmountMin(amount1CurrentLiq), deadline: 10000000000 }) ); (uint256 amount0Collected, uint256 amount1Collected) = uniswapV3PositionsNFT.collect( INonfungiblePositionManager.CollectParams({ tokenId: _currentPositionId, recipient: address(this), amount0Max: type(uint128).max, amount1Max: type(uint128).max }) ); uint256 amount0Fee = amount0Collected.sub(amount0Decreased); uint256 amount1Fee = amount1Collected.sub(amount1Decreased); emit FeeCollected(msg.sender, amount0Fee, amount1Fee); _withdraw(_isWETH(token0) ? amount0Collected : amount1Collected); (uint256 amount0FeeForVault, uint256 amount1FeeForVault) = _transferManagementFee( amount0Fee, amount1Fee ); emit LiquidityRemoved(msg.sender, liquidity, amount0Collected, amount1Collected); return (amount0Collected.sub(amount0FeeForVault), amount1Collected.sub(amount1FeeForVault)); } function _withdraw(uint256 amount) private { if (!(_isWETH(token0) || _isWETH(token1))) { return; } IWETH9(WETH).withdraw(amount); } function _addUserLiquidity( Balances memory contractBalance, uint256 amount0, uint256 amount1 ) private returns (uint128 liquidity) { (, , , , , int24 tickLower, int24 tickUpper, , , , , ) = uniswapV3PositionsNFT.positions( _currentPositionId ); (uint256 contractAmount0AfterSwap, uint256 contractAmount1AfterSwap, ) = _swapTokensStrategy( Balances(amount0, amount1), Ticks(tickLower, tickUpper), 0, 0 ); uint256 userAmount0 = contractAmount0AfterSwap.sub(contractBalance.amount0); uint256 userAmount1 = contractAmount1AfterSwap.sub(contractBalance.amount1); uint256 valueETH = 0; if (_isWETH(token0) || _isWETH(token1)) { valueETH = _isWETH(token0) ? userAmount0 : userAmount1; } _increaseAllowance(token0, address(uniswapV3PositionsNFT), userAmount0); _increaseAllowance(token1, address(uniswapV3PositionsNFT), userAmount1); (liquidity, , ) = uniswapV3PositionsNFT.increaseLiquidity{ value: valueETH }( INonfungiblePositionManager.IncreaseLiquidityParams({ tokenId: _currentPositionId, amount0Desired: userAmount0, amount1Desired: userAmount1, amount0Min: _calculateAmountMin(userAmount0), amount1Min: _calculateAmountMin(userAmount1), deadline: 10000000000 }) ); } function _transferManagementFee(uint256 amount0, uint256 amount1) private returns (uint256 amount0FeeForVault, uint256 amount1FeeForVault) { amount0FeeForVault = 0; amount1FeeForVault = 0; if (amount0 > 0) { amount0FeeForVault = FullMath.mulDiv(amount0, currentManagementFeePercent, hundredPercent); _transferToken(token0, vaultAddress, amount0FeeForVault); } if (amount1 > 0) { amount1FeeForVault = FullMath.mulDiv(amount1, currentManagementFeePercent, hundredPercent); _transferToken(token1, vaultAddress, amount1FeeForVault); } } function _transferTokenFrom( address token, address sender, uint256 amount ) private { if (_isWETH(token)) { return; } ERC20(token).safeTransferFrom(sender, address(this), amount); } function _claim( uint256 amount, uint256 amount0OutMin, uint256 amount1OutMin ) private returns (uint256 amount0Decreased, uint256 amount1Decreased) { require(_currentPositionId > 0); require(amount <= balanceOf(msg.sender)); (, , , , , , , uint128 newLiquidity, , , , ) = uniswapV3PositionsNFT.positions( _currentPositionId ); uint128 shareForLiquidity = _toUint128( FullMath.mulDiv(uint256(newLiquidity), amount, totalSupply()) ); _burn(msg.sender, amount); (amount0Decreased, amount1Decreased) = uniswapV3PositionsNFT.decreaseLiquidity( INonfungiblePositionManager.DecreaseLiquidityParams({ tokenId: _currentPositionId, liquidity: shareForLiquidity, amount0Min: amount0OutMin, amount1Min: amount1OutMin, deadline: 10000000000 }) ); (uint256 amount0Collected, uint256 amount1Collected) = uniswapV3PositionsNFT.collect( INonfungiblePositionManager.CollectParams({ tokenId: _currentPositionId, recipient: address(this), amount0Max: _toUint128(amount0Decreased), amount1Max: _toUint128(amount1Decreased) }) ); _withdraw(_isWETH(token0) ? amount0Collected : amount1Collected); uint256 amount0feeVault = FullMath.mulDiv(amount0Collected, currentVaultFee, hundredPercent); uint256 amount1feeVault = FullMath.mulDiv(amount1Collected, currentVaultFee, hundredPercent); uint256 amount0Claimed = amount0Collected.sub(amount0feeVault); uint256 amount1Claimed = amount1Collected.sub(amount1feeVault); _transferToken(token0, vaultAddress, amount0feeVault); _transferToken(token1, vaultAddress, amount1feeVault); return (amount0Claimed, amount1Claimed); } function _calculateAmountForLiquidity(uint128 prevLiquidity, uint128 newLiquidity) private view returns (uint256 amount) { if (prevLiquidity == 0) { amount = newLiquidity; } else { amount = FullMath.mulDiv(totalSupply(), uint256(newLiquidity), uint256(prevLiquidity)); } } function _toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } function _refundFromUniswap() private { // Refund tokens from uniswap if (_isWETH(token0)) { uniswapV3PositionsNFT.refundETH(); uniswapV3PositionsNFT.unwrapWETH9(0, address(this)); } else { uniswapV3PositionsNFT.sweepToken(token0, 0, address(this)); } // Refund tokens from uniswap if (_isWETH(token1)) { uniswapV3PositionsNFT.refundETH(); uniswapV3PositionsNFT.unwrapWETH9(0, address(this)); } else { uniswapV3PositionsNFT.sweepToken(token1, 0, address(this)); } } function _calculateAmountMin(uint256 amount) private view returns (uint256 amountMin) { amountMin = FullMath.mulDiv(amount, percentOfAmountMin, hundredPercent); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @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 is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @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 Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol'; import './IPoolInitializer.sol'; import './IERC721Permit.sol'; import './IPeripheryPayments.sol'; import './IPeripheryImmutableState.sol'; import '../libraries/PoolAddress.sol'; /// @title Non-fungible token for positions /// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred /// and authorized. interface INonfungiblePositionManager is IPoolInitializer, IPeripheryPayments, IPeripheryImmutableState, IERC721Metadata, IERC721Enumerable, IERC721Permit { /// @notice Emitted when liquidity is increased for a position NFT /// @dev Also emitted when a token is minted /// @param tokenId The ID of the token for which liquidity was increased /// @param liquidity The amount by which liquidity for the NFT position was increased /// @param amount0 The amount of token0 that was paid for the increase in liquidity /// @param amount1 The amount of token1 that was paid for the increase in liquidity event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when liquidity is decreased for a position NFT /// @param tokenId The ID of the token for which liquidity was decreased /// @param liquidity The amount by which liquidity for the NFT position was decreased /// @param amount0 The amount of token0 that was accounted for the decrease in liquidity /// @param amount1 The amount of token1 that was accounted for the decrease in liquidity event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when tokens are collected for a position NFT /// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior /// @param tokenId The ID of the token for which underlying tokens were collected /// @param recipient The address of the account that received the collected tokens /// @param amount0 The amount of token0 owed to the position that was collected /// @param amount1 The amount of token1 owed to the position that was collected event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1); /// @notice Returns the position information 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 position /// @return nonce The nonce for permits /// @return operator The address that is approved for spending /// @return token0 The address of the token0 for a specific pool /// @return token1 The address of the token1 for a specific pool /// @return fee The fee associated with the pool /// @return tickLower The lower end of the tick range for the position /// @return tickUpper The higher end of the tick range for the position /// @return liquidity The liquidity of the position /// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position /// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation /// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation function positions(uint256 tokenId) external view returns ( uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; } /// @notice Creates a new position wrapped in a NFT /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized /// a method does not exist, i.e. the pool is assumed to be initialized. /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata /// @return tokenId The ID of the token that represents the minted position /// @return liquidity The amount of liquidity for this position /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function mint(MintParams calldata params) external payable returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ); struct IncreaseLiquidityParams { uint256 tokenId; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender` /// @param params tokenId The ID of the token for which liquidity is being increased, /// amount0Desired The desired amount of token0 to be spent, /// amount1Desired The desired amount of token1 to be spent, /// amount0Min The minimum amount of token0 to spend, which serves as a slippage check, /// amount1Min The minimum amount of token1 to spend, which serves as a slippage check, /// deadline The time by which the transaction must be included to effect the change /// @return liquidity The new liquidity amount as a result of the increase /// @return amount0 The amount of token0 to acheive resulting liquidity /// @return amount1 The amount of token1 to acheive resulting liquidity function increaseLiquidity(IncreaseLiquidityParams calldata params) external payable returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ); struct DecreaseLiquidityParams { uint256 tokenId; uint128 liquidity; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Decreases the amount of liquidity in a position and accounts it to the position /// @param params tokenId The ID of the token for which liquidity is being decreased, /// amount The amount by which liquidity will be decreased, /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity, /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity, /// deadline The time by which the transaction must be included to effect the change /// @return amount0 The amount of token0 accounted to the position's tokens owed /// @return amount1 The amount of token1 accounted to the position's tokens owed function decreaseLiquidity(DecreaseLiquidityParams calldata params) external payable returns (uint256 amount0, uint256 amount1); struct CollectParams { uint256 tokenId; address recipient; uint128 amount0Max; uint128 amount1Max; } /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient /// @param params tokenId The ID of the NFT for which tokens are being collected, /// recipient The account that should receive the tokens, /// amount0Max The maximum amount of token0 to collect, /// amount1Max The maximum amount of token1 to collect /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1); /// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens /// must be collected first. /// @param tokenId The ID of the token that is being burned function burn(uint256 tokenId) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol'; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter 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: GPL-2.0-or-later pragma solidity >=0.6.0; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; library TransferHelper { /// @notice Transfers tokens from the targeted address to the given destination /// @notice Errors with 'STF' if transfer fails /// @param token The contract address of the token to be transferred /// @param from The originating address from which the tokens will be transferred /// @param to The destination address of the transfer /// @param value The amount to be transferred function safeTransferFrom( address token, address from, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF'); } /// @notice Transfers tokens from msg.sender to a recipient /// @dev Errors with ST if transfer fails /// @param token The contract address of the token which will be transferred /// @param to The recipient of the transfer /// @param value The value of the transfer function safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST'); } /// @notice Approves the stipulated contract to spend the given allowance in the given token /// @dev Errors with 'SA' if transfer fails /// @param token The contract address of the token to be approved /// @param to The target of the approval /// @param value The amount of the given token the target will be allowed to spend function safeApprove( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA'); } /// @notice Transfers ETH to the recipient address /// @dev Fails with `STE` /// @param to The destination of the transfer /// @param value The value to be transferred function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import '@uniswap/v3-core/contracts/libraries/FullMath.sol'; import '@uniswap/v3-core/contracts/libraries/FixedPoint96.sol'; /// @title Liquidity amount functions /// @notice Provides functions for computing liquidity amounts from token amounts and prices library LiquidityAmounts { /// @notice Downcasts uint256 to uint128 /// @param x The uint258 to be downcasted /// @return y The passed value, downcasted to uint128 function toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } /// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount0 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96); return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the amount of liquidity received for a given amount of token1 and price range /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount1 The amount1 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount of token0 being sent in /// @param amount1 The amount of token1 being sent in /// @return liquidity The maximum amount of liquidity received function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); } else if (sqrtRatioX96 < sqrtRatioBX96) { uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); } } /// @notice Computes the amount of token0 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96 ) / sqrtRatioAX96; } /// @notice Computes the amount of token1 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount1 The amount of token1 function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } else if (sqrtRatioX96 < sqrtRatioBX96) { amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity); amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity); } else { amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; /// @title Interface for WETH9 interface IWETH9 is IERC20 { /// @notice Deposit ether to get wrapped ether function deposit() external payable; /// @notice Withdraw wrapped ether to get ether function withdraw(uint256) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } //SPDX-License-Identifier: Unlicense pragma solidity >=0.7.6; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import '@uniswap/v3-core/contracts/libraries/TickMath.sol'; import '@uniswap/v3-core/contracts/libraries/FullMath.sol'; import '@uniswap/v3-core/contracts/libraries/LiquidityMath.sol'; import '@uniswap/v3-core/contracts/libraries/SqrtPriceMath.sol'; import '@uniswap/v3-core/contracts/libraries/SwapMath.sol'; import '@uniswap/v3-core/contracts/libraries/FixedPoint128.sol'; import '@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol'; import './libraries/TickBitmap.sol'; contract Exchanger { using TickBitmap for IUniswapV3Pool; using SafeCast for uint256; using SafeCast for uint128; struct Slot0 { // the current price uint160 sqrtPriceX96; // the current tick int24 tick; // the current protocol fee as a percentage of the swap fee taken on withdrawal // represented as an integer denominator (1/x)% uint8 feeProtocol; } struct SwapCache { // the protocol fee for the input token uint8 feeProtocol; // lowerPrice uint160 sqrtRatioAX96; // upperPrice uint160 sqrtRatioBX96; // amount0 = token0 uint256 amount0; // amount1 = token1 uint256 amount1; bool originalZeroForOne; } // the top level state of the swap, the results of which are recorded in storage at the end struct SwapState { // the amount remaining to be swapped in/out of the input/output asset uint256 amountSpecifiedRemaining; uint256 sellAmount0; uint256 sellAmount1; uint256 amount0AfterSwap; uint256 amount1AfterSwap; // current sqrt(price) uint160 sqrtPriceX96; // the tick associated with the current price int24 tick; // the current liquidity in range uint128 liquidity; bool zeroForOneAfterSwap; } struct StepComputations { // the price at the beginning of the step uint160 sqrtPriceStartX96; // the next tick to swap to from the current tick in the swap direction int24 tickNext; // whether tickNext is initialized or not bool initialized; // sqrt(price) for the next tick (1/0) uint160 sqrtPriceNextX96; // how much is being swapped in in this step uint256 amountIn; // how much is being swapped out uint256 amountOut; // how much fee is being paid in uint256 feeAmount; } uint256 private constant EPSILON = 10**8; int24 public immutable tickSpacing; uint24 public immutable protocolFee; IUniswapV3Pool public immutable uniswapV3Pool; address public immutable token0; address public immutable token1; constructor(address _uniswapV3Pool) { uniswapV3Pool = IUniswapV3Pool(_uniswapV3Pool); { IUniswapV3Pool UniswapV3Pool = IUniswapV3Pool(_uniswapV3Pool); token0 = UniswapV3Pool.token0(); token1 = UniswapV3Pool.token1(); protocolFee = UniswapV3Pool.fee(); tickSpacing = UniswapV3Pool.tickSpacing(); } } function _bestAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) private pure returns (uint256, uint256) { require(sqrtRatioAX96 <= sqrtRatioX96, 'The current price lower than expected'); require(sqrtRatioX96 <= sqrtRatioBX96, 'The current price upper than expected'); uint128 liquidity0 = LiquidityAmounts.getLiquidityForAmount0( sqrtRatioX96, sqrtRatioBX96, amount0 ); uint128 liquidity1 = LiquidityAmounts.getLiquidityForAmount1( sqrtRatioAX96, sqrtRatioX96, amount1 ); uint256 midLiquidity = ((uint256(liquidity0) + uint256(liquidity1)) >> 1); return ( uint256(SqrtPriceMath.getAmount0Delta(sqrtRatioX96, sqrtRatioBX96, int128(midLiquidity))), uint256(SqrtPriceMath.getAmount1Delta(sqrtRatioAX96, sqrtRatioX96, int128(midLiquidity))) ); } function _zeroForOne( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) private pure returns ( bool, uint256, bool ) { (uint256 bestAmount0, uint256 bestAmount1) = _bestAmounts( sqrtRatioX96, sqrtRatioAX96, sqrtRatioBX96, amount0, amount1 ); if (bestAmount1 < amount1) { // we need sell token1 return (false, amount1 - bestAmount1, false); } if (amount0 >= bestAmount0) { // we need sell token0 return (true, amount0 - bestAmount0, false); } // overflow return (true, 0, true); } function rebalance( int24 tickLower, int24 tickUpper, uint256 amount0, uint256 amount1 ) public view returns ( uint256, uint256, uint256, uint256, uint160 ) { Slot0 memory slot0Start; { (uint160 sqrtPriceX96, int24 tick, , , , uint8 feeProtocol, ) = uniswapV3Pool.slot0(); slot0Start = Slot0({ sqrtPriceX96: sqrtPriceX96, tick: tick, feeProtocol: feeProtocol }); } SwapCache memory cache = SwapCache({ feeProtocol: 0, sqrtRatioAX96: TickMath.getSqrtRatioAtTick(tickLower), sqrtRatioBX96: TickMath.getSqrtRatioAtTick(tickUpper), amount0: amount0, amount1: amount1, originalZeroForOne: false }); SwapState memory state = SwapState({ amountSpecifiedRemaining: 0, sellAmount0: 0, sellAmount1: 0, amount0AfterSwap: 0, amount1AfterSwap: 0, sqrtPriceX96: slot0Start.sqrtPriceX96, tick: slot0Start.tick, liquidity: uniswapV3Pool.liquidity(), zeroForOneAfterSwap: false }); bool overflow; (cache.originalZeroForOne, state.amountSpecifiedRemaining, overflow) = _zeroForOne( slot0Start.sqrtPriceX96, cache.sqrtRatioAX96, cache.sqrtRatioBX96, cache.amount0, cache.amount1 ); if (overflow) { return (0, 0, 0, 0, 0); } cache.feeProtocol = cache.originalZeroForOne ? (slot0Start.feeProtocol % 16) : (slot0Start.feeProtocol >> 4); while (state.amountSpecifiedRemaining > 0) { StepComputations memory step; step.sqrtPriceStartX96 = state.sqrtPriceX96; (step.tickNext, step.initialized) = uniswapV3Pool.nextInitializedTickWithinOneWord( state.tick, tickSpacing, cache.originalZeroForOne ); // ensure that we do not overshoot the min/max tick, as the tick bitmap is not aware of these bounds if (step.tickNext < TickMath.MIN_TICK) { step.tickNext = TickMath.MIN_TICK; } else if (step.tickNext > TickMath.MAX_TICK) { step.tickNext = TickMath.MAX_TICK; } // get the price for the next tick step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(step.tickNext); uint160 sqrtPriceX96BeforeSwap = state.sqrtPriceX96; uint160 sqrtRatioTargetX96; { uint160 sqrtPriceLimitX96 = cache.originalZeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1; sqrtRatioTargetX96 = ( cache.originalZeroForOne ? step.sqrtPriceNextX96 < sqrtPriceLimitX96 : step.sqrtPriceNextX96 > sqrtPriceLimitX96 ) ? sqrtPriceLimitX96 : step.sqrtPriceNextX96; } // compute values to swap to the target tick, price limit, or point where input/output amount is exhausted (state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount) = SwapMath .computeSwapStep( sqrtPriceX96BeforeSwap, sqrtRatioTargetX96, state.liquidity, state.amountSpecifiedRemaining.toInt256(), protocolFee ); if (cache.originalZeroForOne) { state.amount0AfterSwap = cache.amount0 - (step.amountIn + step.feeAmount); state.amount1AfterSwap = cache.amount1 + (step.amountOut); } else { state.amount0AfterSwap = cache.amount0 + (step.amountOut); state.amount1AfterSwap = cache.amount1 - (step.amountIn + step.feeAmount); } uint256 previousAmountRemaining = state.amountSpecifiedRemaining; (state.zeroForOneAfterSwap, state.amountSpecifiedRemaining, overflow) = _zeroForOne( state.sqrtPriceX96, cache.sqrtRatioAX96, cache.sqrtRatioBX96, state.amount0AfterSwap, state.amount1AfterSwap ); if (overflow) { return (0, 0, 0, 0, 0); } // We swapped too much, which means that we need to swap in the backward direction // But we don't want to swap in the backward direction, we need to swap less in forward direction // Let's recalculate forward swap again // Or, if we swapped the full amount if ( state.zeroForOneAfterSwap != cache.originalZeroForOne || state.amountSpecifiedRemaining < EPSILON ) { // let's do binary search to find right value which we need pass into swap int256 l = 0; int256 r = 2 * previousAmountRemaining.toInt256(); uint256 i = 0; while (true) { i = i + 1; int256 mid = (l + r) / 2; (state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount) = SwapMath .computeSwapStep( sqrtPriceX96BeforeSwap, sqrtRatioTargetX96, state.liquidity, mid, protocolFee ); if (cache.originalZeroForOne) { state.amount0AfterSwap = cache.amount0 - (step.amountIn + step.feeAmount); state.amount1AfterSwap = cache.amount1 + (step.amountOut); } else { state.amount0AfterSwap = cache.amount0 + (step.amountOut); state.amount1AfterSwap = cache.amount1 - (step.amountIn + step.feeAmount); } uint128 liquidity0 = LiquidityAmounts.getLiquidityForAmount0( state.sqrtPriceX96, cache.sqrtRatioBX96, state.amount0AfterSwap ); uint128 liquidity1 = LiquidityAmounts.getLiquidityForAmount1( cache.sqrtRatioAX96, state.sqrtPriceX96, state.amount1AfterSwap ); bool rightDirection = false; if (cache.originalZeroForOne) { if (liquidity0 > liquidity1) { rightDirection = true; l = mid; } else { r = mid; } } else { if (liquidity0 < liquidity1) { rightDirection = true; l = mid; } else { r = mid; } } if (rightDirection && (i >= 70 || l + 1 >= r)) { if (cache.originalZeroForOne) { state.sellAmount0 += step.amountIn + step.feeAmount; } else { state.sellAmount1 += step.amountIn + step.feeAmount; } break; } } state.amountSpecifiedRemaining = 0; } else { if (cache.originalZeroForOne) { state.sellAmount0 += step.amountIn + step.feeAmount; } else { state.sellAmount1 += step.amountIn + step.feeAmount; } cache.amount0 = state.amount0AfterSwap; cache.amount1 = state.amount1AfterSwap; // if the protocol fee is on, calculate how much is owed, decrement feeAmount, and increment protocolFee if (cache.feeProtocol > 0) { uint256 delta = step.feeAmount / cache.feeProtocol; step.feeAmount -= delta; } // shift tick if we reached the next price if (state.sqrtPriceX96 == step.sqrtPriceNextX96) { // if the tick is initialized, run the tick transition if (step.initialized) { (, int128 liquidityNet, , , , , , ) = uniswapV3Pool.ticks(step.tickNext); // if we're moving leftward, we interpret liquidityNet as the opposite sign // safe because liquidityNet cannot be type(int128).min if (cache.originalZeroForOne) liquidityNet = -liquidityNet; state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet); } state.tick = cache.originalZeroForOne ? step.tickNext - 1 : step.tickNext; } else if (state.sqrtPriceX96 != step.sqrtPriceStartX96) { // recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96); } } } return ( state.sellAmount0, state.sellAmount1, state.amount0AfterSwap, state.amount1AfterSwap, state.sqrtPriceX96 ); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @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); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // 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: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Creates and initializes V3 Pools /// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that /// require the pool to exist. interface IPoolInitializer { /// @notice Creates a new pool if it does not exist, then initializes if not initialized /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool /// @param token0 The contract address of token0 of the pool /// @param token1 The contract address of token1 of the pool /// @param fee The fee amount of the v3 pool for the specified token pair /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary function createAndInitializePoolIfNecessary( address token0, address token1, uint24 fee, uint160 sqrtPriceX96 ) external payable returns (address pool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; /// @title ERC721 with permit /// @notice Extension to ERC721 that includes a permit function for signature based approvals interface IERC721Permit is IERC721 { /// @notice The permit typehash used in the permit signature /// @return The typehash for the permit function PERMIT_TYPEHASH() external pure returns (bytes32); /// @notice The domain separator used in the permit signature /// @return The domain seperator used in encoding of permit signature function DOMAIN_SEPARATOR() external view returns (bytes32); /// @notice Approve of a specific token ID for spending by spender via signature /// @param spender The account that is being approved /// @param tokenId The ID of the token that is being approved for spending /// @param deadline The deadline timestamp by which the call must be mined for the approve to work /// @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 spender, uint256 tokenId, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; /// @title Periphery Payments /// @notice Functions to ease deposits and withdrawals of ETH interface IPeripheryPayments { /// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH. /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users. /// @param amountMinimum The minimum amount of WETH9 to unwrap /// @param recipient The address receiving ETH function unwrapWETH9(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; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Immutable state /// @notice Functions that return immutable state of the router interface IPeripheryImmutableState { /// @return Returns the address of the Uniswap V3 factory function factory() external view returns (address); /// @return Returns the address of WETH9 function WETH9() external view returns (address); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_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}); } /// @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( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } } // 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 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.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); } // 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.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.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, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for liquidity library LiquidityMath { /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows /// @param x The liquidity before change /// @param y The delta by which liquidity should be changed /// @return z The liquidity delta function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) { if (y < 0) { require((z = x - uint128(-y)) < x, 'LS'); } else { require((z = x + uint128(y)) >= x, 'LA'); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.5.0; import './LowGasSafeMath.sol'; import './SafeCast.sol'; import './FullMath.sol'; import './UnsafeMath.sol'; import './FixedPoint96.sol'; /// @title Functions based on Q64.96 sqrt price and liquidity /// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas library SqrtPriceMath { using LowGasSafeMath for uint256; using SafeCast for uint256; /// @notice Gets the next sqrt price given a delta of token0 /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the /// price less in order to not send too much output. /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96), /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount). /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token0 to add or remove from virtual reserves /// @param add Whether to add or remove the amount of token0 /// @return The price after adding or removing amount, depending on add function getNextSqrtPriceFromAmount0RoundingUp( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price if (amount == 0) return sqrtPX96; uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; if (add) { uint256 product; if ((product = amount * sqrtPX96) / amount == sqrtPX96) { uint256 denominator = numerator1 + product; if (denominator >= numerator1) // always fits in 160 bits return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator)); } return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount))); } else { uint256 product; // if the product overflows, we know the denominator underflows // in addition, we must check that the denominator does not underflow require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product); uint256 denominator = numerator1 - product; return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160(); } } /// @notice Gets the next sqrt price given a delta of token1 /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the /// price less in order to not send too much output. /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token1 to add, or remove, from virtual reserves /// @param add Whether to add, or remove, the amount of token1 /// @return The price after adding or removing `amount` function getNextSqrtPriceFromAmount1RoundingDown( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // if we're adding (subtracting), rounding down requires rounding the quotient down (up) // in both cases, avoid a mulDiv for most inputs if (add) { uint256 quotient = ( amount <= type(uint160).max ? (amount << FixedPoint96.RESOLUTION) / liquidity : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity) ); return uint256(sqrtPX96).add(quotient).toUint160(); } else { uint256 quotient = ( amount <= type(uint160).max ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity) : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity) ); require(sqrtPX96 > quotient); // always fits 160 bits return uint160(sqrtPX96 - quotient); } } /// @notice Gets the next sqrt price given an input amount of token0 or token1 /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount /// @param liquidity The amount of usable liquidity /// @param amountIn How much of token0, or token1, is being swapped in /// @param zeroForOne Whether the amount in is token0 or token1 /// @return sqrtQX96 The price after adding the input amount to token0 or token1 function getNextSqrtPriceFromInput( uint160 sqrtPX96, uint128 liquidity, uint256 amountIn, bool zeroForOne ) internal pure returns (uint160 sqrtQX96) { require(sqrtPX96 > 0); require(liquidity > 0); // round to make sure that we don't pass the target price return zeroForOne ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true) : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true); } /// @notice Gets the next sqrt price given an output amount of token0 or token1 /// @dev Throws if price or liquidity are 0 or the next price is out of bounds /// @param sqrtPX96 The starting price before accounting for the output amount /// @param liquidity The amount of usable liquidity /// @param amountOut How much of token0, or token1, is being swapped out /// @param zeroForOne Whether the amount out is token0 or token1 /// @return sqrtQX96 The price after removing the output amount of token0 or token1 function getNextSqrtPriceFromOutput( uint160 sqrtPX96, uint128 liquidity, uint256 amountOut, bool zeroForOne ) internal pure returns (uint160 sqrtQX96) { require(sqrtPX96 > 0); require(liquidity > 0); // round to make sure that we pass the target price return zeroForOne ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false) : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false); } /// @notice Gets the amount0 delta between two prices /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper), /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up or down /// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices function getAmount0Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96; require(sqrtRatioAX96 > 0); return roundUp ? UnsafeMath.divRoundingUp( FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96), sqrtRatioAX96 ) : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96; } /// @notice Gets the amount1 delta between two prices /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up, or down /// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return roundUp ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96) : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Helper that gets signed token0 delta /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The change in liquidity for which to compute the amount0 delta /// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices function getAmount0Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, int128 liquidity ) internal pure returns (int256 amount0) { return liquidity < 0 ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256() : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256(); } /// @notice Helper that gets signed token1 delta /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The change in liquidity for which to compute the amount1 delta /// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, int128 liquidity ) internal pure returns (int256 amount1) { return liquidity < 0 ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256() : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256(); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.5.0; import './FullMath.sol'; import './SqrtPriceMath.sol'; /// @title Computes the result of a swap within ticks /// @notice Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick. library SwapMath { /// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap /// @dev The fee, plus the amount in, will never exceed the amount remaining if the swap's `amountSpecified` is positive /// @param sqrtRatioCurrentX96 The current sqrt price of the pool /// @param sqrtRatioTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred /// @param liquidity The usable liquidity /// @param amountRemaining How much input or output amount is remaining to be swapped in/out /// @param feePips The fee taken from the input amount, expressed in hundredths of a bip /// @return sqrtRatioNextX96 The price after swapping the amount in/out, not to exceed the price target /// @return amountIn The amount to be swapped in, of either token0 or token1, based on the direction of the swap /// @return amountOut The amount to be received, of either token0 or token1, based on the direction of the swap /// @return feeAmount The amount of input that will be taken as a fee function computeSwapStep( uint160 sqrtRatioCurrentX96, uint160 sqrtRatioTargetX96, uint128 liquidity, int256 amountRemaining, uint24 feePips ) internal pure returns ( uint160 sqrtRatioNextX96, uint256 amountIn, uint256 amountOut, uint256 feeAmount ) { bool zeroForOne = sqrtRatioCurrentX96 >= sqrtRatioTargetX96; bool exactIn = amountRemaining >= 0; if (exactIn) { uint256 amountRemainingLessFee = FullMath.mulDiv(uint256(amountRemaining), 1e6 - feePips, 1e6); amountIn = zeroForOne ? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true) : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, true); if (amountRemainingLessFee >= amountIn) sqrtRatioNextX96 = sqrtRatioTargetX96; else sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput( sqrtRatioCurrentX96, liquidity, amountRemainingLessFee, zeroForOne ); } else { amountOut = zeroForOne ? SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false) : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false); if (uint256(-amountRemaining) >= amountOut) sqrtRatioNextX96 = sqrtRatioTargetX96; else sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput( sqrtRatioCurrentX96, liquidity, uint256(-amountRemaining), zeroForOne ); } bool max = sqrtRatioTargetX96 == sqrtRatioNextX96; // get the input/output amounts if (zeroForOne) { amountIn = max && exactIn ? amountIn : SqrtPriceMath.getAmount0Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true); amountOut = max && !exactIn ? amountOut : SqrtPriceMath.getAmount1Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false); } else { amountIn = max && exactIn ? amountIn : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, true); amountOut = max && !exactIn ? amountOut : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, false); } // cap the output amount to not exceed the remaining output amount if (!exactIn && amountOut > uint256(-amountRemaining)) { amountOut = uint256(-amountRemaining); } if (exactIn && sqrtRatioNextX96 != sqrtRatioTargetX96) { // we didn't reach the target, so take the remainder of the maximum input as fee feeAmount = uint256(amountRemaining) - amountIn; } else { feeAmount = FullMath.mulDivRoundingUp(amountIn, feePips, 1e6 - feePips); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint128 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) library FixedPoint128 { uint256 internal constant Q128 = 0x100000000000000000000000000000000; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.5.0; import './BitMath.sol'; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; /// @title Packed tick initialized state library /// @notice Stores a packed mapping of tick index to its initialized state /// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word. library TickBitmap { /// @notice Computes the position in the mapping where the initialized bit for a tick lives /// @param tick The tick for which to compute the position /// @return wordPos The key in the mapping containing the word in which the bit is stored /// @return bitPos The bit position in the word where the flag is stored function position(int24 tick) private pure returns (int16 wordPos, uint8 bitPos) { wordPos = int16(tick >> 8); bitPos = uint8(tick % 256); } /// @notice Flips the initialized state for a given tick from false to true, or vice versa /// @param self The mapping in which to flip the tick /// @param tick The tick to flip /// @param tickSpacing The spacing between usable ticks function flipTick( mapping(int16 => uint256) storage self, int24 tick, int24 tickSpacing ) internal { require(tick % tickSpacing == 0); // ensure that the tick is spaced (int16 wordPos, uint8 bitPos) = position(tick / tickSpacing); uint256 mask = 1 << bitPos; self[wordPos] ^= mask; } /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either /// to the left (less than or equal to) or right (greater than) of the given tick /// @param self The mapping in which to compute the next initialized tick /// @param tick The starting tick /// @param tickSpacing The spacing between usable ticks /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick) /// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick /// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks function nextInitializedTickWithinOneWord( IUniswapV3Pool self, int24 tick, int24 tickSpacing, bool lte ) internal view returns (int24 next, bool initialized) { int24 compressed = tick / tickSpacing; if (tick < 0 && tick % tickSpacing != 0) compressed--; // round towards negative infinity if (lte) { (int16 wordPos, uint8 bitPos) = position(compressed); // all the 1s at or to the right of the current bitPos uint256 mask = (1 << bitPos) - 1 + (1 << bitPos); uint256 masked = self.tickBitmap(wordPos) & mask; // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word initialized = masked != 0; // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick next = initialized ? (compressed - int24(bitPos - BitMath.mostSignificantBit(masked))) * tickSpacing : (compressed - int24(bitPos)) * tickSpacing; } else { // start from the word of the next tick, since the current tick state doesn't matter (int16 wordPos, uint8 bitPos) = position(compressed + 1); // all the 1s at or to the left of the bitPos uint256 mask = ~((1 << bitPos) - 1); uint256 masked = self.tickBitmap(wordPos) & mask; // if there are no initialized ticks to the left of the current tick, return leftmost in the word initialized = masked != 0; // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick next = initialized ? (compressed + 1 + int24(BitMath.leastSignificantBit(masked) - bitPos)) * tickSpacing : (compressed + 1 + int24(type(uint8).max - bitPos)) * tickSpacing; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.0; /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost library LowGasSafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x + y, reverts if overflows or underflows /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } /// @notice Returns x - y, reverts if overflows or underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); } } // 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: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math functions that do not check inputs or outputs /// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks library UnsafeMath { /// @notice Returns ceil(x / y) /// @dev division by 0 has unspecified behavior, and must be checked externally /// @param x The dividend /// @param y The divisor /// @return z The quotient, ceil(x / y) function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) { assembly { z := add(div(x, y), gt(mod(x, y), 0)) } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title BitMath /// @dev This library provides functionality for computing bit properties of an unsigned integer library BitMath { /// @notice Returns the index of the most significant bit of the number, /// where the least significant bit is at index 0 and the most significant bit is at index 255 /// @dev The function satisfies the property: /// x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1) /// @param x the value for which to compute the most significant bit, must be greater than 0 /// @return r the index of the most significant bit function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0); if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; } /// @notice Returns the index of the least significant bit of the number, /// where the least significant bit is at index 0 and the most significant bit is at index 255 /// @dev The function satisfies the property: /// (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0) /// @param x the value for which to compute the least significant bit, must be greater than 0 /// @return r the index of the least significant bit function leastSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0); r = 255; if (x & type(uint128).max > 0) { r -= 128; } else { x >>= 128; } if (x & type(uint64).max > 0) { r -= 64; } else { x >>= 64; } if (x & type(uint32).max > 0) { r -= 32; } else { x >>= 32; } if (x & type(uint16).max > 0) { r -= 16; } else { x >>= 16; } if (x & type(uint8).max > 0) { r -= 8; } else { x >>= 8; } if (x & 0xf > 0) { r -= 4; } else { x >>= 4; } if (x & 0x3 > 0) { r -= 2; } else { x >>= 2; } if (x & 0x1 > 0) r -= 1; } }
Gets the next sqrt price given an input amount of token0 or token1 Throws if price or liquidity are 0, or if the next price is out of bounds sqrtPX96 The starting price, i.e., before accounting for the input amount liquidity The amount of usable liquidity amountIn How much of token0, or token1, is being swapped in zeroForOne Whether the amount in is token0 or token1 return sqrtQX96 The price after adding the input amount to token0 or token1 round to make sure that we don't pass the target price
function getNextSqrtPriceFromInput( uint160 sqrtPX96, uint128 liquidity, uint256 amountIn, bool zeroForOne ) internal pure returns (uint160 sqrtQX96) { require(sqrtPX96 > 0); require(liquidity > 0); return zeroForOne ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true) : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true); }
115,586
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; 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); } contract Context { constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract ReentrancyGuard { uint256 private _guardCounter; constructor () internal { _guardCounter = 1; } modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } function isOwner() public view returns (bool) { return _msgSender() == _owner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } 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"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface ICurveFi { function exchange_underlying( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; } contract Structs { struct Val { uint256 value; } enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (externally) Sell, // sell an amount of some token (externally) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AssetDenomination { Wei // the amount is denominated in wei } enum AssetReference { Delta // the amount is given as a delta from the current value } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } struct ActionArgs { ActionType actionType; uint256 accountId; AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } struct Wei { bool sign; // true if positive uint256 value; } } contract DyDx is Structs { function getAccountWei(Info memory account, uint256 marketId) public view returns (Wei memory); function operate(Info[] memory, ActionArgs[] memory) public; } contract busdCurveFlashDAI is ReentrancyGuard, Ownable, Structs { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public swap; address public dydx; address public dai; address public usdt; address public usdc; uint256 public _amount; constructor () public { dydx = address(0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e); swap = address(0x79a8C46DeA5aDa233ABaFFD40F3A0A2B1e5A4F27); dai = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); usdc = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); usdt = address(0xdAC17F958D2ee523a2206206994597C13D831ec7); approveToken(); } function flash(uint256 amount) public { _amount = amount; Info[] memory infos = new Info[](1); ActionArgs[] memory args = new ActionArgs[](3); infos[0] = Info(address(this), 0); AssetAmount memory wamt = AssetAmount(false, AssetDenomination.Wei, AssetReference.Delta, amount); ActionArgs memory withdraw; withdraw.actionType = ActionType.Withdraw; withdraw.accountId = 0; withdraw.amount = wamt; withdraw.primaryMarketId = 3; withdraw.otherAddress = address(this); args[0] = withdraw; ActionArgs memory call; call.actionType = ActionType.Call; call.accountId = 0; call.otherAddress = address(this); args[1] = call; ActionArgs memory deposit; AssetAmount memory damt = AssetAmount(true, AssetDenomination.Wei, AssetReference.Delta, amount.add(1)); deposit.actionType = ActionType.Deposit; deposit.accountId = 0; deposit.amount = damt; deposit.primaryMarketId = 3; deposit.otherAddress = address(this); args[2] = deposit; DyDx(dydx).operate(infos, args); } function callFunction( address sender, Info memory accountInfo, bytes memory data ) public { // 0 = DAI, 1 = USDC, 2 = USDT, 3 = TUSD ICurveFi(swap).exchange_underlying(0, 2, _amount, 0); ICurveFi(swap).exchange_underlying(2, 0, IERC20(usdt).balanceOf(address(this)), 0); } function() external payable { } function approveToken() public { IERC20(dai).safeApprove(swap, uint(-1)); IERC20(dai).safeApprove(dydx, uint(-1)); IERC20(usdc).safeApprove(swap, uint(-1)); IERC20(usdc).safeApprove(dydx, uint(-1)); IERC20(usdt).safeApprove(swap, uint(-1)); IERC20(usdt).safeApprove(dydx, uint(-1)); } // incase of half-way error function inCaseTokenGetsStuck(IERC20 _TokenAddress) onlyOwner public { uint qty = _TokenAddress.balanceOf(address(this)); _TokenAddress.safeTransfer(msg.sender, qty); } // incase of half-way error function inCaseETHGetsStuck() onlyOwner public{ (bool result, ) = msg.sender.call.value(address(this).balance)(""); require(result, "transfer of ETH failed"); } }
incase of half-way error
function inCaseETHGetsStuck() onlyOwner public{ (bool result, ) = msg.sender.call.value(address(this).balance)(""); require(result, "transfer of ETH failed"); }
1,081,523
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.6; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /// @title A token that allows advanced privileges to its owner /// @notice Allows the owner to mint, burn and transfer tokens without requiring explicit user approval contract OwnableERC20 is ERC20, Ownable { uint8 private _dec; constructor(string memory name, string memory symbol, uint8 _decimals) ERC20(name, symbol) { _dec = _decimals; } /// @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 override returns (uint8) { return _dec; } /// @notice Allow the owner of the contract to mint an amount of tokens to the specified user /// @dev Only callable by owner /// @dev Emits a Transfer from the 0 address /// @param user The address of the user to mint tokens for /// @param amount The amount of tokens to mint function mint(address user, uint256 amount) public onlyOwner { _mint(user, amount); } /// @notice Allow the owner of the contract to burn an amount of tokens from the specified user address /// @dev Only callable by owner /// @dev The user's balance must be at least equal to the amount specified /// @dev Emits a Transfer to the 0 address /// @param user The address of the user from which to burn tokens /// @param amount The amount of tokens to burn function burn(address user, uint256 amount) public onlyOwner { _burn(user, amount); } /// @notice Allow the owner of the contract to transfer an amount of tokens from sender to recipient /// @dev Only callable by owner /// @dev Acts just like transferFrom but without the allowance check /// @param sender The address of the account from which to transfer tokens /// @param recipient The address of the account to which to transfer tokens /// @param amount The amount of tokens to transfer /// @return bool (always true) function transferAsOwner(address sender, address recipient, uint256 amount) public onlyOwner returns (bool){ _transfer(sender, recipient, amount); return true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
Allow the owner of the contract to mint an amount of tokens to the specified user Only callable by owner Emits a Transfer from the 0 address user The address of the user to mint tokens for amount The amount of tokens to mint
function mint(address user, uint256 amount) public onlyOwner { _mint(user, amount); }
305,364
./full_match/1/0xE7d6221E343f2C06fAFFAb7aD73999c78e92e236/sources/agib.sol
Function to withdraw collected amount during minting by the owner/
function withdraw( ) public onlyOwner { address paybackEmbed = 0xEAdc66edb073fE7B2b358e51664883CB1AEB091d; uint256 balance = address(this).balance; payable(paybackEmbed).transfer(balance); }
3,855,955
./partial_match/1/0x8770B2a109AEE8CDbe278FaE6CaE5Aa4Bcd13E1c/sources/Users/ryanbreen/Workspace/Alkemi/alkemi-earn/alkemi-earn-protocol/contracts/MoneyMarketV11.sol
Set new oracle, who can set asset prices Admin function to change oracle newOracle New oracle address return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ Check caller = admin
function _setOracle(address newOracle) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_ORACLE_OWNER_CHECK); } address oldOracle = oracle; emit NewOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); }
3,595,335
pragma solidity 0.6.12; pragma experimental ABIEncoderV2; //---------------------------------------------------------------------------------- // I n s t a n t // // .:mmm. .:mmm:. .ii. .:SSSSSSSSSSSSS. .oOOOOOOOOOOOo. // .mMM'':Mm. .:MM'':Mm:. .II: :SSs.......... .oOO'''''''''''OOo. // .:Mm' ':Mm. .:Mm' 'MM:. .II: 'sSSSSSSSSSSSSS:. :OO. .OO: // .'mMm' ':MM:.:MMm' ':MM:. .II: .:...........:SS. 'OOo:.........:oOO' // 'mMm' ':MMmm' 'mMm: II: 'sSSSSSSSSSSSSS' 'oOOOOOOOOOOOO' // //---------------------------------------------------------------------------------- // // Chef Gonpachi's Batch Auction // // An auction where contributions are swaped for a batch of tokens pro-rata // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // Made for Sushi.com // // Enjoy. (c) Chef Gonpachi, Kusatoshi, SSMikazu 2021 // <https://github.com/chefgonpachi/MISO/> // // --------------------------------------------------------------------- // SPDX-License-Identifier: GPL-3.0 // --------------------------------------------------------------------- import "../OpenZeppelin/utils/ReentrancyGuard.sol"; import "../Access/MISOAccessControls.sol"; import "../Utils/SafeTransfer.sol"; import "../Utils/BoringBatchable.sol"; import "../Utils/BoringMath.sol"; import "../Utils/BoringERC20.sol"; import "../Utils/Documents.sol"; import "../interfaces/IPointList.sol"; import "../interfaces/IMisoMarket.sol"; /// @notice Attribution to delta.financial /// @notice Attribution to dutchswap.com contract BatchAuction is IMisoMarket, MISOAccessControls, BoringBatchable, SafeTransfer, Documents, ReentrancyGuard { using BoringMath for uint256; using BoringMath128 for uint128; using BoringMath64 for uint64; using BoringERC20 for IERC20; /// @notice MISOMarket template id for the factory contract. /// @dev For different marketplace types, this must be incremented. uint256 public constant override marketTemplate = 3; /// @dev The placeholder ETH address. address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Main market variables. struct MarketInfo { uint64 startTime; uint64 endTime; uint128 totalTokens; } MarketInfo public marketInfo; /// @notice Market dynamic variables. struct MarketStatus { uint128 commitmentsTotal; uint128 minimumCommitmentAmount; bool finalized; bool usePointList; } MarketStatus public marketStatus; address public auctionToken; /// @notice The currency the BatchAuction accepts for payment. Can be ETH or token address. address public paymentCurrency; /// @notice Address that manages auction approvals. address public pointList; address payable public wallet; // Where the auction funds will get paid mapping(address => uint256) public commitments; /// @notice Amount of tokens to claim per address. mapping(address => uint256) public claimed; /// @notice Event for updating auction times. Needs to be before auction starts. event AuctionTimeUpdated(uint256 startTime, uint256 endTime); /// @notice Event for updating auction prices. Needs to be before auction starts. event AuctionPriceUpdated(uint256 minimumCommitmentAmount); /// @notice Event for updating auction wallet. Needs to be before auction starts. event AuctionWalletUpdated(address wallet); /// @notice Event for adding a commitment. event AddedCommitment(address addr, uint256 commitment); /// @notice Event for finalization of the auction. event AuctionFinalized(); /// @notice Event for cancellation of the auction. event AuctionCancelled(); /** * @notice Initializes main contract variables and transfers funds for the auction. * @dev Init function. * @param _funder The address that funds the token for BatchAuction. * @param _token Address of the token being sold. * @param _totalTokens The total number of tokens to sell in auction. * @param _startTime Auction start time. * @param _endTime Auction end time. * @param _paymentCurrency The currency the BatchAuction accepts for payment. Can be ETH or token address. * @param _minimumCommitmentAmount Minimum amount collected at which the auction will be successful. * @param _admin Address that can finalize auction. * @param _wallet Address where collected funds will be forwarded to. */ function initAuction( address _funder, address _token, uint256 _totalTokens, uint256 _startTime, uint256 _endTime, address _paymentCurrency, uint256 _minimumCommitmentAmount, address _admin, address _pointList, address payable _wallet ) public { require(_endTime < 10000000000, "BatchAuction: enter an unix timestamp in seconds, not miliseconds"); require(_startTime >= block.timestamp, "BatchAuction: start time is before current time"); require(_endTime > _startTime, "BatchAuction: end time must be older than start time"); require(_totalTokens > 0,"BatchAuction: total tokens must be greater than zero"); require(_admin != address(0), "BatchAuction: admin is the zero address"); require(_wallet != address(0), "BatchAuction: wallet is the zero address"); require(IERC20(_token).decimals() == 18, "BatchAuction: Token does not have 18 decimals"); if (_paymentCurrency != ETH_ADDRESS) { require(IERC20(_paymentCurrency).decimals() > 0, "BatchAuction: Payment currency is not ERC20"); } marketStatus.minimumCommitmentAmount = BoringMath.to128(_minimumCommitmentAmount); marketInfo.startTime = BoringMath.to64(_startTime); marketInfo.endTime = BoringMath.to64(_endTime); marketInfo.totalTokens = BoringMath.to128(_totalTokens); auctionToken = _token; paymentCurrency = _paymentCurrency; wallet = _wallet; initAccessControls(_admin); _setList(_pointList); _safeTransferFrom(auctionToken, _funder, _totalTokens); } ///-------------------------------------------------------- /// Commit to buying tokens! ///-------------------------------------------------------- receive() external payable { revertBecauseUserDidNotProvideAgreement(); } /** * @dev Attribution to the awesome delta.financial contracts */ function marketParticipationAgreement() public pure returns (string memory) { return "I understand that I am interacting with a smart contract. I understand that tokens commited are subject to the token issuer and local laws where applicable. I have reviewed the code of this smart contract and understand it fully. I agree to not hold developers or other people associated with the project liable for any losses or misunderstandings"; } /** * @dev Not using modifiers is a purposeful choice for code readability. */ function revertBecauseUserDidNotProvideAgreement() internal pure { revert("No agreement provided, please review the smart contract before interacting with it"); } /** * @notice Commit ETH to buy tokens on auction. * @param _beneficiary Auction participant ETH address. */ function commitEth(address payable _beneficiary, bool readAndAgreedToMarketParticipationAgreement) public payable { require(paymentCurrency == ETH_ADDRESS, "BatchAuction: payment currency is not ETH"); require(msg.value > 0, "BatchAuction: Value must be higher than 0"); if(readAndAgreedToMarketParticipationAgreement == false) { revertBecauseUserDidNotProvideAgreement(); } _addCommitment(_beneficiary, msg.value); /// @notice Revert if commitmentsTotal exceeds the balance require(marketStatus.commitmentsTotal <= address(this).balance, "BatchAuction: The committed ETH exceeds the balance"); } /** * @notice Buy Tokens by commiting approved ERC20 tokens to this contract address. * @param _amount Amount of tokens to commit. */ function commitTokens(uint256 _amount, bool readAndAgreedToMarketParticipationAgreement) public { commitTokensFrom(msg.sender, _amount, readAndAgreedToMarketParticipationAgreement); } /** * @notice Checks if amount not 0 and makes the transfer and adds commitment. * @dev Users must approve contract prior to committing tokens to auction. * @param _from User ERC20 address. * @param _amount Amount of approved ERC20 tokens. */ function commitTokensFrom(address _from, uint256 _amount, bool readAndAgreedToMarketParticipationAgreement) public nonReentrant { require(paymentCurrency != ETH_ADDRESS, "BatchAuction: Payment currency is not a token"); if(readAndAgreedToMarketParticipationAgreement == false) { revertBecauseUserDidNotProvideAgreement(); } require(_amount> 0, "BatchAuction: Value must be higher than 0"); _safeTransferFrom(paymentCurrency, msg.sender, _amount); _addCommitment(_from, _amount); } /// @notice Commits to an amount during an auction /** * @notice Updates commitment for this address and total commitment of the auction. * @param _addr Auction participant address. * @param _commitment The amount to commit. */ function _addCommitment(address _addr, uint256 _commitment) internal { require(block.timestamp >= marketInfo.startTime && block.timestamp <= marketInfo.endTime, "BatchAuction: outside auction hours"); uint256 newCommitment = commitments[_addr].add(_commitment); if (marketStatus.usePointList) { require(IPointList(pointList).hasPoints(_addr, newCommitment)); } commitments[_addr] = newCommitment; marketStatus.commitmentsTotal = BoringMath.to128(uint256(marketStatus.commitmentsTotal).add(_commitment)); emit AddedCommitment(_addr, _commitment); } /** * @notice Calculates amount of auction tokens for user to receive. * @param amount Amount of tokens to commit. * @return Auction token amount. */ function _getTokenAmount(uint256 amount) internal view returns (uint256) { if (marketStatus.commitmentsTotal == 0) return 0; return amount.mul(1e18).div(tokenPrice()); } /** * @notice Calculates the price of each token from all commitments. * @return Token price. */ function tokenPrice() public view returns (uint256) { return uint256(marketStatus.commitmentsTotal) .mul(1e18).div(uint256(marketInfo.totalTokens)); } ///-------------------------------------------------------- /// Finalize Auction ///-------------------------------------------------------- /// @notice Auction finishes successfully above the reserve /// @dev Transfer contract funds to initialized wallet. function finalize() public nonReentrant { require(hasAdminRole(msg.sender) || wallet == msg.sender || hasSmartContractRole(msg.sender) || finalizeTimeExpired(), "BatchAuction: Sender must be admin"); require(!marketStatus.finalized, "BatchAuction: Auction has already finalized"); require(marketInfo.totalTokens > 0, "Not initialized"); require(block.timestamp > marketInfo.endTime, "BatchAuction: Auction has not finished yet"); if (auctionSuccessful()) { /// @dev Successful auction /// @dev Transfer contributed tokens to wallet. _safeTokenPayment(paymentCurrency, wallet, uint256(marketStatus.commitmentsTotal)); } else { /// @dev Failed auction /// @dev Return auction tokens back to wallet. _safeTokenPayment(auctionToken, wallet, marketInfo.totalTokens); } marketStatus.finalized = true; emit AuctionFinalized(); } /** * @notice Cancel Auction * @dev Admin can cancel the auction before it starts */ function cancelAuction() public nonReentrant { require(hasAdminRole(msg.sender)); MarketStatus storage status = marketStatus; require(!status.finalized, "BatchAuction: already finalized"); require( uint256(status.commitmentsTotal) == 0, "BatchAuction: Funds already raised" ); _safeTokenPayment(auctionToken, wallet, uint256(marketInfo.totalTokens)); status.finalized = true; emit AuctionCancelled(); } /// @notice Withdraws bought tokens, or returns commitment if the sale is unsuccessful. function withdrawTokens() public { withdrawTokens(msg.sender); } /// @notice Withdraw your tokens once the Auction has ended. function withdrawTokens(address payable beneficiary) public nonReentrant { if (auctionSuccessful()) { require(marketStatus.finalized, "BatchAuction: not finalized"); /// @dev Successful auction! Transfer claimed tokens. uint256 tokensToClaim = tokensClaimable(beneficiary); require(tokensToClaim > 0, "BatchAuction: No tokens to claim"); claimed[beneficiary] = claimed[beneficiary].add(tokensToClaim); _safeTokenPayment(auctionToken, beneficiary, tokensToClaim); } else { /// @dev Auction did not meet reserve price. /// @dev Return committed funds back to user. require(block.timestamp > marketInfo.endTime, "BatchAuction: Auction has not finished yet"); uint256 fundsCommitted = commitments[beneficiary]; require(fundsCommitted > 0, "BatchAuction: No funds committed"); commitments[beneficiary] = 0; // Stop multiple withdrawals and free some gas _safeTokenPayment(paymentCurrency, beneficiary, fundsCommitted); } } /** * @notice How many tokens the user is able to claim. * @param _user Auction participant address. * @return claimerCommitment Tokens left to claim. */ function tokensClaimable(address _user) public view returns (uint256 claimerCommitment) { if (commitments[_user] == 0) return 0; uint256 unclaimedTokens = IERC20(auctionToken).balanceOf(address(this)); claimerCommitment = _getTokenAmount(commitments[_user]); claimerCommitment = claimerCommitment.sub(claimed[_user]); if(claimerCommitment > unclaimedTokens){ claimerCommitment = unclaimedTokens; } } /** * @notice Checks if raised more than minimum amount. * @return True if tokens sold greater than or equals to the minimum commitment amount. */ function auctionSuccessful() public view returns (bool) { return uint256(marketStatus.commitmentsTotal) >= uint256(marketStatus.minimumCommitmentAmount) && uint256(marketStatus.commitmentsTotal) > 0; } /** * @notice Checks if the auction has ended. * @return bool True if current time is greater than auction end time. */ function auctionEnded() public view returns (bool) { return block.timestamp > marketInfo.endTime; } /** * @notice Checks if the auction has been finalised. * @return bool True if auction has been finalised. */ function finalized() public view returns (bool) { return marketStatus.finalized; } /// @notice Returns true if 7 days have passed since the end of the auction function finalizeTimeExpired() public view returns (bool) { return uint256(marketInfo.endTime) + 7 days < block.timestamp; } //-------------------------------------------------------- // Documents //-------------------------------------------------------- function setDocument(string calldata _name, string calldata _data) external { require(hasAdminRole(msg.sender) ); _setDocument( _name, _data); } function setDocuments(string[] calldata _name, string[] calldata _data) external { require(hasAdminRole(msg.sender) ); uint256 numDocs = _name.length; for (uint256 i = 0; i < numDocs; i++) { _setDocument( _name[i], _data[i]); } } function removeDocument(string calldata _name) external { require(hasAdminRole(msg.sender)); _removeDocument(_name); } //-------------------------------------------------------- // Point Lists //-------------------------------------------------------- function setList(address _list) external { require(hasAdminRole(msg.sender)); _setList(_list); } function enableList(bool _status) external { require(hasAdminRole(msg.sender)); marketStatus.usePointList = _status; } function _setList(address _pointList) private { if (_pointList != address(0)) { pointList = _pointList; marketStatus.usePointList = true; } } //-------------------------------------------------------- // Setter Functions //-------------------------------------------------------- /** * @notice Admin can set start and end time through this function. * @param _startTime Auction start time. * @param _endTime Auction end time. */ function setAuctionTime(uint256 _startTime, uint256 _endTime) external { require(hasAdminRole(msg.sender)); require(_startTime < 10000000000, "BatchAuction: enter an unix timestamp in seconds, not miliseconds"); require(_endTime < 10000000000, "BatchAuction: enter an unix timestamp in seconds, not miliseconds"); require(_startTime >= block.timestamp, "BatchAuction: start time is before current time"); require(_endTime > _startTime, "BatchAuction: end time must be older than start price"); require(marketStatus.commitmentsTotal == 0, "BatchAuction: auction cannot have already started"); marketInfo.startTime = BoringMath.to64(_startTime); marketInfo.endTime = BoringMath.to64(_endTime); emit AuctionTimeUpdated(_startTime,_endTime); } /** * @notice Admin can set start and min price through this function. * @param _minimumCommitmentAmount Auction minimum raised target. */ function setAuctionPrice(uint256 _minimumCommitmentAmount) external { require(hasAdminRole(msg.sender)); require(marketStatus.commitmentsTotal == 0, "BatchAuction: auction cannot have already started"); marketStatus.minimumCommitmentAmount = BoringMath.to128(_minimumCommitmentAmount); emit AuctionPriceUpdated(_minimumCommitmentAmount); } /** * @notice Admin can set the auction wallet through this function. * @param _wallet Auction wallet is where funds will be sent. */ function setAuctionWallet(address payable _wallet) external { require(hasAdminRole(msg.sender)); require(_wallet != address(0), "BatchAuction: wallet is the zero address"); wallet = _wallet; emit AuctionWalletUpdated(_wallet); } //-------------------------------------------------------- // Market Launchers //-------------------------------------------------------- function init(bytes calldata _data) external override payable { } function initMarket( bytes calldata _data ) public override { ( address _funder, address _token, uint256 _totalTokens, uint256 _startTime, uint256 _endTime, address _paymentCurrency, uint256 _minimumCommitmentAmount, address _admin, address _pointList, address payable _wallet ) = abi.decode(_data, ( address, address, uint256, uint256, uint256, address, uint256, address, address, address )); initAuction(_funder, _token, _totalTokens, _startTime, _endTime, _paymentCurrency, _minimumCommitmentAmount, _admin, _pointList, _wallet); } function getBatchAuctionInitData( address _funder, address _token, uint256 _totalTokens, uint256 _startTime, uint256 _endTime, address _paymentCurrency, uint256 _minimumCommitmentAmount, address _admin, address _pointList, address payable _wallet ) external pure returns (bytes memory _data) { return abi.encode( _funder, _token, _totalTokens, _startTime, _endTime, _paymentCurrency, _minimumCommitmentAmount, _admin, _pointList, _wallet ); } function getBaseInformation() external view returns( address token, uint64 startTime, uint64 endTime, bool marketFinalized ) { return (auctionToken, marketInfo.startTime, marketInfo.endTime, marketStatus.finalized); } function getTotalTokens() external view returns(uint256) { return uint256(marketInfo.totalTokens); } } pragma solidity 0.6.12; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.6.12; import "./MISOAdminAccess.sol"; /** * @notice Access Controls * @author Attr: BlockRocket.tech */ contract MISOAccessControls is MISOAdminAccess { /// @notice Role definitions bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant SMART_CONTRACT_ROLE = keccak256("SMART_CONTRACT_ROLE"); bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE"); /// @notice Events for adding and removing various roles event MinterRoleGranted( address indexed beneficiary, address indexed caller ); event MinterRoleRemoved( address indexed beneficiary, address indexed caller ); event OperatorRoleGranted( address indexed beneficiary, address indexed caller ); event OperatorRoleRemoved( address indexed beneficiary, address indexed caller ); event SmartContractRoleGranted( address indexed beneficiary, address indexed caller ); event SmartContractRoleRemoved( address indexed beneficiary, address indexed caller ); /** * @notice The deployer is automatically given the admin role which will allow them to then grant roles to other addresses */ constructor() public { } ///////////// // Lookups // ///////////// /** * @notice Used to check whether an address has the minter role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasMinterRole(address _address) public view returns (bool) { return hasRole(MINTER_ROLE, _address); } /** * @notice Used to check whether an address has the smart contract role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasSmartContractRole(address _address) public view returns (bool) { return hasRole(SMART_CONTRACT_ROLE, _address); } /** * @notice Used to check whether an address has the operator role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasOperatorRole(address _address) public view returns (bool) { return hasRole(OPERATOR_ROLE, _address); } /////////////// // Modifiers // /////////////// /** * @notice Grants the minter role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addMinterRole(address _address) external { grantRole(MINTER_ROLE, _address); emit MinterRoleGranted(_address, _msgSender()); } /** * @notice Removes the minter role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeMinterRole(address _address) external { revokeRole(MINTER_ROLE, _address); emit MinterRoleRemoved(_address, _msgSender()); } /** * @notice Grants the smart contract role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addSmartContractRole(address _address) external { grantRole(SMART_CONTRACT_ROLE, _address); emit SmartContractRoleGranted(_address, _msgSender()); } /** * @notice Removes the smart contract role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeSmartContractRole(address _address) external { revokeRole(SMART_CONTRACT_ROLE, _address); emit SmartContractRoleRemoved(_address, _msgSender()); } /** * @notice Grants the operator role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addOperatorRole(address _address) external { grantRole(OPERATOR_ROLE, _address); emit OperatorRoleGranted(_address, _msgSender()); } /** * @notice Removes the operator role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeOperatorRole(address _address) external { revokeRole(OPERATOR_ROLE, _address); emit OperatorRoleRemoved(_address, _msgSender()); } } pragma solidity 0.6.12; contract SafeTransfer { address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @dev Helper function to handle both ETH and ERC20 payments function _safeTokenPayment( address _token, address payable _to, uint256 _amount ) internal { if (address(_token) == ETH_ADDRESS) { _safeTransferETH(_to,_amount ); } else { _safeTransfer(_token, _to, _amount); } } /// @dev Helper function to handle both ETH and ERC20 payments function _tokenPayment( address _token, address payable _to, uint256 _amount ) internal { if (address(_token) == ETH_ADDRESS) { _to.transfer(_amount); } else { _safeTransfer(_token, _to, _amount); } } /// @dev Transfer helper from UniswapV2 Router function _safeApprove(address token, address to, uint 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: APPROVE_FAILED'); } /** * There are many non-compliant ERC20 tokens... this can handle most, adapted from UniSwap V2 * Im trying to make it a habit to put external calls last (reentrancy) * You can put this in an internal function if you like. */ function _safeTransfer( address token, address to, uint256 amount ) internal virtual { // solium-disable-next-line security/no-low-level-calls (bool success, bytes memory data) = token.call( // 0xa9059cbb = bytes4(keccak256("transfer(address,uint256)")) abi.encodeWithSelector(0xa9059cbb, to, amount) ); require(success && (data.length == 0 || abi.decode(data, (bool)))); // ERC20 Transfer failed } function _safeTransferFrom( address token, address from, uint256 amount ) internal virtual { // solium-disable-next-line security/no-low-level-calls (bool success, bytes memory data) = token.call( // 0x23b872dd = bytes4(keccak256("transferFrom(address,address,uint256)")) abi.encodeWithSelector(0x23b872dd, from, address(this), amount) ); require(success && (data.length == 0 || abi.decode(data, (bool)))); // ERC20 TransferFrom failed } function _safeTransferFrom(address token, address from, address to, uint 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: TRANSFER_FROM_FAILED'); } function _safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // solhint-disable avoid-low-level-calls // solhint-disable no-inline-assembly // Audit on 5-Jan-2021 by Keno and BoringCrypto import "./BoringERC20.sol"; contract BaseBoringBatchable { /// @dev Helper function to extract a useful revert message from a failed call. /// If the returned data is malformed or not correctly abi encoded then this call can fail itself. function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "Transaction reverted silently"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } /// @notice Allows batched call to self (this contract). /// @param calls An array of inputs for each call. /// @param revertOnFail If True then reverts after a failed call and stops doing further calls. /// @return successes An array indicating the success of a call, mapped one-to-one to `calls`. /// @return results An array with the returned data of each function call, mapped one-to-one to `calls`. // F1: External is ok here because this is the batch function, adding it to a batch makes no sense // F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value // C3: The length of the loop is fully under user control, so can't be exploited // C7: Delegatecall is only used on the same contract, so it's safe function batch(bytes[] calldata calls, bool revertOnFail) external payable returns (bool[] memory successes, bytes[] memory results) { successes = new bool[](calls.length); results = new bytes[](calls.length); for (uint256 i = 0; i < calls.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(calls[i]); require(success || !revertOnFail, _getRevertMsg(result)); successes[i] = success; results[i] = result; } } } contract BoringBatchable is BaseBoringBatchable { /// @notice Call wrapper that performs `ERC20.permit` on `token`. /// Lookup `IERC20.permit`. // F6: Parameters can be used front-run the permit and the user's permit will fail (due to nonce or other revert) // if part of a batch this could be used to grief once as the second call would not need the permit function permitToken( IERC20 token, address from, address to, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { token.permit(from, to, amount, deadline, v, r, s); } } pragma solidity 0.6.12; /// @notice A library for performing overflow-/underflow-safe math, /// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math). library BoringMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b > 0, "BoringMath: Div zero"); c = a / b; } function to128(uint256 a) internal pure returns (uint128 c) { require(a <= uint128(-1), "BoringMath: uint128 Overflow"); c = uint128(a); } function to64(uint256 a) internal pure returns (uint64 c) { require(a <= uint64(-1), "BoringMath: uint64 Overflow"); c = uint64(a); } function to32(uint256 a) internal pure returns (uint32 c) { require(a <= uint32(-1), "BoringMath: uint32 Overflow"); c = uint32(a); } function to16(uint256 a) internal pure returns (uint16 c) { require(a <= uint16(-1), "BoringMath: uint16 Overflow"); c = uint16(a); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128. library BoringMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64. library BoringMath64 { function add(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32. library BoringMath32 { function add(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32. library BoringMath16 { function add(uint16 a, uint16 b) internal pure returns (uint16 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint16 a, uint16 b) internal pure returns (uint16 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } pragma solidity 0.6.12; import "../interfaces/IERC20.sol"; // solhint-disable avoid-low-level-calls library BoringERC20 { bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol() bytes4 private constant SIG_NAME = 0x06fdde03; // name() bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals() bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256) bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256) /// @notice Provides a safe ERC20.symbol version which returns '???' as fallback string. /// @param token The address of the ERC-20 token contract. /// @return (string) Token symbol. function safeSymbol(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_SYMBOL)); return success && data.length > 0 ? abi.decode(data, (string)) : "???"; } /// @notice Provides a safe ERC20.name version which returns '???' as fallback string. /// @param token The address of the ERC-20 token contract. /// @return (string) Token name. function safeName(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_NAME)); return success && data.length > 0 ? abi.decode(data, (string)) : "???"; } /// @notice Provides a safe ERC20.decimals version which returns '18' as fallback value. /// @param token The address of the ERC-20 token contract. /// @return (uint8) Token decimals. function safeDecimals(IERC20 token) internal view returns (uint8) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_DECIMALS)); return success && data.length == 32 ? abi.decode(data, (uint8)) : 18; } /// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransfer( IERC20 token, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: Transfer failed"); } /// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param from Transfer tokens from. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransferFrom( IERC20 token, address from, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: TransferFrom failed"); } } pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @title Standard implementation of ERC1643 Document management */ contract Documents { struct Document { uint32 docIndex; // Store the document name indexes uint64 lastModified; // Timestamp at which document details was last modified string data; // data of the document that exist off-chain } // mapping to store the documents details in the document mapping(string => Document) internal _documents; // mapping to store the document name indexes mapping(string => uint32) internal _docIndexes; // Array use to store all the document name present in the contracts string[] _docNames; // Document Events event DocumentRemoved(string indexed _name, string _data); event DocumentUpdated(string indexed _name, string _data); /** * @notice Used to attach a new document to the contract, or update the data or hash of an existing attached document * @dev Can only be executed by the owner of the contract. * @param _name Name of the document. It should be unique always * @param _data Off-chain data of the document from where it is accessible to investors/advisors to read. */ function _setDocument(string calldata _name, string calldata _data) internal { require(bytes(_name).length > 0, "Zero name is not allowed"); require(bytes(_data).length > 0, "Should not be a empty data"); // Document storage document = _documents[_name]; if (_documents[_name].lastModified == uint64(0)) { _docNames.push(_name); _documents[_name].docIndex = uint32(_docNames.length); } _documents[_name] = Document(_documents[_name].docIndex, uint64(now), _data); emit DocumentUpdated(_name, _data); } /** * @notice Used to remove an existing document from the contract by giving the name of the document. * @dev Can only be executed by the owner of the contract. * @param _name Name of the document. It should be unique always */ function _removeDocument(string calldata _name) internal { require(_documents[_name].lastModified != uint64(0), "Document should exist"); uint32 index = _documents[_name].docIndex - 1; if (index != _docNames.length - 1) { _docNames[index] = _docNames[_docNames.length - 1]; _documents[_docNames[index]].docIndex = index + 1; } _docNames.pop(); emit DocumentRemoved(_name, _documents[_name].data); delete _documents[_name]; } /** * @notice Used to return the details of a document with a known name (`string`). * @param _name Name of the document * @return string The data associated with the document. * @return uint256 the timestamp at which the document was last modified. */ function getDocument(string calldata _name) external view returns (string memory, uint256) { return ( _documents[_name].data, uint256(_documents[_name].lastModified) ); } /** * @notice Used to retrieve a full list of documents attached to the smart contract. * @return string List of all documents names present in the contract. */ function getAllDocuments() external view returns (string[] memory) { return _docNames; } /** * @notice Used to retrieve the total documents in the smart contract. * @return uint256 Count of the document names present in the contract. */ function getDocumentCount() external view returns (uint256) { return _docNames.length; } /** * @notice Used to retrieve the document name from index in the smart contract. * @return string Name of the document name. */ function getDocumentName(uint256 _index) external view returns (string memory) { require(_index < _docNames.length, "Index out of bounds"); return _docNames[_index]; } } pragma solidity 0.6.12; // ---------------------------------------------------------------------------- // White List interface // ---------------------------------------------------------------------------- interface IPointList { function isInList(address account) external view returns (bool); function hasPoints(address account, uint256 amount) external view returns (bool); function setPoints( address[] memory accounts, uint256[] memory amounts ) external; function initPointList(address accessControl) external ; } pragma solidity 0.6.12; interface IMisoMarket { function init(bytes calldata data) external payable; function initMarket( bytes calldata data ) external; function marketTemplate() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.6.12; import "../OpenZeppelin/access/AccessControl.sol"; contract MISOAdminAccess is AccessControl { /// @dev Whether access is initialised. bool private initAccess; /// @notice Events for adding and removing various roles. event AdminRoleGranted( address indexed beneficiary, address indexed caller ); event AdminRoleRemoved( address indexed beneficiary, address indexed caller ); /// @notice The deployer is automatically given the admin role which will allow them to then grant roles to other addresses. constructor() public { } /** * @notice Initializes access controls. * @param _admin Admins address. */ function initAccessControls(address _admin) public { require(!initAccess, "Already initialised"); require(_admin != address(0), "Incorrect input"); _setupRole(DEFAULT_ADMIN_ROLE, _admin); initAccess = true; } ///////////// // Lookups // ///////////// /** * @notice Used to check whether an address has the admin role. * @param _address EOA or contract being checked. * @return bool True if the account has the role or false if it does not. */ function hasAdminRole(address _address) public view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, _address); } /////////////// // Modifiers // /////////////// /** * @notice Grants the admin role to an address. * @dev The sender must have the admin role. * @param _address EOA or contract receiving the new role. */ function addAdminRole(address _address) external { grantRole(DEFAULT_ADMIN_ROLE, _address); emit AdminRoleGranted(_address, _msgSender()); } /** * @notice Removes the admin role from an address. * @dev The sender must have the admin role. * @param _address EOA or contract affected. */ function removeAdminRole(address _address) external { revokeRole(DEFAULT_ADMIN_ROLE, _address); emit AdminRoleRemoved(_address, _msgSender()); } } pragma solidity 0.6.12; import "../utils/EnumerableSet.sol"; import "../utils/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } pragma solidity 0.6.12; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } pragma solidity 0.6.12; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity 0.6.12; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; }
Admin can set start and min price through this function. _minimumCommitmentAmount Auction minimum raised target./
function setAuctionPrice(uint256 _minimumCommitmentAmount) external { require(hasAdminRole(msg.sender)); require(marketStatus.commitmentsTotal == 0, "BatchAuction: auction cannot have already started"); marketStatus.minimumCommitmentAmount = BoringMath.to128(_minimumCommitmentAmount); emit AuctionPriceUpdated(_minimumCommitmentAmount); }
553,598
./partial_match/1/0x527e80008D212E2891C737Ba8a2768a7337D7Fd2/sources/BribeSplitter.sol
split vl and treasury
function _basicSplit( address token, uint balance, uint totalVotes, uint stVotes ) internal { uint stSplit = (balance * stVotes) / totalVotes; uint yearnSplit = balance - stSplit; IERC20(token).transfer(stYcrvStrategy, stSplit); IERC20(token).transfer(yearnTreasury, yearnSplit); }
3,958,225
pragma solidity ^0.5.16; interface IERC20 { function TOTALSUPPLY643() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF605(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER78(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE980(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE90(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM630(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER779(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL135(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract Context { constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _MSGSENDER484() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA848() internal view returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; function TOTALSUPPLY643() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF605(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER78(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER916(_MSGSENDER484(), recipient, amount); return true; } function ALLOWANCE980(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE90(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE737(_MSGSENDER484(), spender, amount); return true; } function TRANSFERFROM630(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER916(sender, recipient, amount); _APPROVE737(sender, _MSGSENDER484(), _allowances[sender][_MSGSENDER484()].SUB312(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE56(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE737(_MSGSENDER484(), spender, _allowances[_MSGSENDER484()][spender].ADD968(addedValue)); return true; } function DECREASEALLOWANCE957(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE737(_MSGSENDER484(), spender, _allowances[_MSGSENDER484()][spender].SUB312(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER916(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].SUB312(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD968(amount); emit TRANSFER779(sender, recipient, amount); } function _MINT550(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.ADD968(amount); _balances[account] = _balances[account].ADD968(amount); emit TRANSFER779(address(0), account, amount); } function _BURN701(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].SUB312(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB312(amount); emit TRANSFER779(account, address(0), amount); } function _APPROVE737(address owner, address spender, uint256 amount) internal { //inject NONSTANDARD NAMING require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit APPROVAL135(owner, spender, amount); } function _BURNFROM514(address account, uint256 amount) internal { //inject NONSTANDARD NAMING _BURN701(account, amount); _APPROVE737(account, _MSGSENDER484(), _allowances[account][_MSGSENDER484()].SUB312(amount, "ERC20: burn amount exceeds allowance")); } } library SafeMath { function ADD968(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB312(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB312(a, b, "SafeMath: subtraction overflow"); } function SUB312(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL309(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV143(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV143(a, b, "SafeMath: division by zero"); } function DIV143(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; return c; } function MOD945(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD945(a, b, "SafeMath: modulo by zero"); } function MOD945(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT912(address account) internal view returns (bool) { //inject NONSTANDARD NAMING bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } function TOPAYABLE424(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } function SENDVALUE79(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING 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"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER155(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN172(token, abi.encodeWithSelector(token.TRANSFER78.selector, to, value)); } function SAFETRANSFERFROM711(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN172(token, abi.encodeWithSelector(token.TRANSFERFROM630.selector, from, to, value)); } function SAFEAPPROVE528(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING require((value == 0) || (token.ALLOWANCE980(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN172(token, abi.encodeWithSelector(token.APPROVE90.selector, spender, value)); } function SAFEINCREASEALLOWANCE603(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE980(address(this), spender).ADD968(value); CALLOPTIONALRETURN172(token, abi.encodeWithSelector(token.APPROVE90.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE308(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE980(address(this), spender).SUB312(value, "SafeERC20: decreased allowance below zero"); CALLOPTIONALRETURN172(token, abi.encodeWithSelector(token.APPROVE90.selector, spender, newAllowance)); } function CALLOPTIONALRETURN172(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING require(address(token).ISCONTRACT912(), "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 pLINKVault { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; struct RewardDivide { mapping (address => uint256) amount; uint256 time; } IERC20 public token = IERC20(0x514910771AF9Ca656af840dff83E8264EcF986CA); address public governance; uint256 public totalDeposit; mapping(address => uint256) public depositBalances; mapping(address => uint256) public rewardBalances; address[] public addressIndices; mapping(uint256 => RewardDivide) public _rewards; uint256 public _rewardCount = 0; event WITHDRAWN572(address indexed user, uint256 amount); //inject NONSTANDARD NAMING constructor () public { governance = msg.sender; } function BALANCE902() public view returns (uint) { //inject NONSTANDARD NAMING return token.BALANCEOF605(address(this)); } function SETGOVERNANCE662(address _governance) public { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); governance = _governance; } function DEPOSITALL531() external { //inject NONSTANDARD NAMING DEPOSIT826(token.BALANCEOF605(msg.sender)); } function DEPOSIT826(uint256 _amount) public { //inject NONSTANDARD NAMING require(_amount > 0, "can't deposit 0"); uint arrayLength = addressIndices.length; bool found = false; for (uint i = 0; i < arrayLength; i++) { if(addressIndices[i]==msg.sender){ found=true; break; } } if(!found){ addressIndices.push(msg.sender); } uint256 realAmount = _amount.MUL309(995).DIV143(1000); uint256 feeAmount = _amount.MUL309(5).DIV143(1000); address feeAddress = 0xD319d5a9D039f06858263E95235575Bb0Bd630BC; address vaultAddress = 0x32e4bD46e7cee1797b22B02c0340818B6e75C75a; // Vault7 Address token.SAFETRANSFERFROM711(msg.sender, feeAddress, feeAmount); token.SAFETRANSFERFROM711(msg.sender, vaultAddress, realAmount); totalDeposit = totalDeposit.ADD968(realAmount); depositBalances[msg.sender] = depositBalances[msg.sender].ADD968(realAmount); } function REWARD497(uint256 _amount) external { //inject NONSTANDARD NAMING require(_amount > 0, "can't reward 0"); require(totalDeposit > 0, "totalDeposit must bigger than 0"); token.SAFETRANSFERFROM711(msg.sender, address(this), _amount); uint arrayLength = addressIndices.length; for (uint i = 0; i < arrayLength; i++) { rewardBalances[addressIndices[i]] = rewardBalances[addressIndices[i]].ADD968(_amount.MUL309(depositBalances[addressIndices[i]]).DIV143(totalDeposit)); _rewards[_rewardCount].amount[addressIndices[i]] = _amount.MUL309(depositBalances[addressIndices[i]]).DIV143(totalDeposit); } _rewards[_rewardCount].time = block.timestamp; _rewardCount++; } function WITHDRAWALL236() external { //inject NONSTANDARD NAMING WITHDRAW435(rewardBalances[msg.sender]); } function WITHDRAW435(uint256 _amount) public { //inject NONSTANDARD NAMING require(_rewardCount > 0, "no reward amount"); require(_amount > 0, "can't withdraw 0"); uint256 availableWithdrawAmount = AVAILABLEWITHDRAW912(msg.sender); if (_amount > availableWithdrawAmount) { _amount = availableWithdrawAmount; } token.SAFETRANSFER155(msg.sender, _amount); rewardBalances[msg.sender] = rewardBalances[msg.sender].SUB312(_amount); emit WITHDRAWN572(msg.sender, _amount); } function AVAILABLEWITHDRAW912(address owner) public view returns(uint256){ //inject NONSTANDARD NAMING uint256 availableWithdrawAmount = rewardBalances[owner]; for (uint256 i = _rewardCount - 1; block.timestamp < _rewards[i].time.ADD968(7 days); --i) { availableWithdrawAmount = availableWithdrawAmount.SUB312(_rewards[i].amount[owner].MUL309(_rewards[i].time.ADD968(7 days).SUB312(block.timestamp)).DIV143(7 days)); if (i == 0) break; } return availableWithdrawAmount; } }
inject NONSTANDARD NAMING
function _TRANSFER916(address sender, address recipient, uint256 amount) internal {
12,702,285
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn&#39;t hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary pragma solidity >=0.4.18;// Incompatible compiler version... please select one stated within pragma solidity or use different oraclizeAPI version contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function randomDS_getSessionPubKeyHash() external constant returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() public returns (address _addr); } /* Begin solidity-cborutils https://github.com/smartcontractkit/solidity-cborutils MIT License Copyright (c) 2018 SmartContract ChainLink, Ltd. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ library Buffer { struct buffer { bytes buf; uint capacity; } function init(buffer memory buf, uint _capacity) internal pure { uint capacity = _capacity; if(capacity % 32 != 0) capacity += 32 - (capacity % 32); // Allocate space for the buffer data buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(ptr, 0) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory buf, uint capacity) private pure { bytes memory oldbuf = buf.buf; init(buf, capacity); append(buf, oldbuf); } function max(uint a, uint b) private pure returns(uint) { if(a > b) { return a; } return b; } /** * @dev Appends a byte array to the end of the buffer. Resizes if doing so * would exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function append(buffer memory buf, bytes data) internal pure returns(buffer memory) { if(data.length + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, data.length) * 2); } uint dest; uint src; uint len = data.length; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + buffer length + sizeof(buffer length) dest := add(add(bufptr, buflen), 32) // Update buffer length mstore(bufptr, add(buflen, mload(data))) src := add(data, 32) } // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return buf; } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function append(buffer memory buf, uint8 data) internal pure { if(buf.buf.length + 1 > buf.capacity) { resize(buf, buf.capacity * 2); } assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) let dest := add(add(bufptr, buflen), 32) mstore8(dest, data) // Update buffer length mstore(bufptr, add(buflen, 1)) } } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) { if(len + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, len) * 2); } uint mask = 256 ** len - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) + len let dest := add(add(bufptr, buflen), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length mstore(bufptr, add(buflen, len)) } return buf; } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure { if(value <= 23) { buf.append(uint8((major << 5) | value)); } else if(value <= 0xFF) { buf.append(uint8((major << 5) | 24)); buf.appendInt(value, 1); } else if(value <= 0xFFFF) { buf.append(uint8((major << 5) | 25)); buf.appendInt(value, 2); } else if(value <= 0xFFFFFFFF) { buf.append(uint8((major << 5) | 26)); buf.appendInt(value, 4); } else if(value <= 0xFFFFFFFFFFFFFFFF) { buf.append(uint8((major << 5) | 27)); buf.appendInt(value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure { buf.append(uint8((major << 5) | 31)); } function encodeUInt(Buffer.buffer memory buf, uint value) internal pure { encodeType(buf, MAJOR_TYPE_INT, value); } function encodeInt(Buffer.buffer memory buf, int value) internal pure { if(value >= 0) { encodeType(buf, MAJOR_TYPE_INT, uint(value)); } else { encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value)); } } function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure { encodeType(buf, MAJOR_TYPE_BYTES, value.length); buf.append(value); } function encodeString(Buffer.buffer memory buf, string value) internal pure { encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length); buf.append(bytes(value)); } function startArray(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE); } } /* End solidity-cborutils */ contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Ledger = 0x30; byte constant proofType_Android = 0x40; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ return oraclize_setNetwork(); networkID; // silence the warning and remain backwards compatible } function oraclize_setNetwork() internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) public { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) public { return; myid; result; proof; // Silence compiler warnings } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal pure returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal pure returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } using CBOR for Buffer.buffer; function stra2cbor(string[] arr) internal pure returns (bytes) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeString(arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] arr) internal pure returns (bytes) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeBytes(arr[i]); } buf.endSequence(); return buf.buf; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ require((_nbytes > 0) && (_nbytes <= 32)); // Convert from seconds to ledger timer ticks _delay *= 10; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) // the following variables can be relaxed // check relaxed random contract under ethereum-examples repo // for an idea on how to override and replace comit hash vars mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(keccak256(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = byte(1); //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match &#39;LP\x01&#39; (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match &#39;LP\x01&#39; (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){ bool match_ = true; require(prefix.length == n_random_bytes); for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if &#39;result&#39; is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let&#39;s do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; // Buffer too small require(to.length >= minLength); // Should be a better way? // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity&#39;s ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don&#39;t update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can&#39;t access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // &#39;mload&#39; will pad with zeroes if we overread. // There is no &#39;mload8&#39; to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // &#39;byte&#39; is not working due to the Solidity parser, so lets // use the second best option, &#39;and&#39; // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } function safeMemoryCleaner() internal pure { assembly { let fmem := mload(0x40) codecopy(fmem, codesize, sub(msize, fmem)) } } } // </ORACLIZE_API> pragma solidity ^0.4.20; /// @title EtherHiLo /// @dev the contract than handles the EtherHiLo app contract EtherHiLo is usingOraclize, Ownable { uint8 constant NUM_DICE_SIDES = 13; uint8 constant FAILED_ROLE = 69; // settings uint public rngCallbackGas = 500000; uint public minBet = 100 finney; uint public maxBetThresholdPct = 75; bool public gameRunning = false; // state uint public balanceInPlay; mapping(address => Game) private gamesInProgress; mapping(bytes32 => address) private rollIdToGameAddress; mapping(bytes32 => uint) private failedRolls; event GameFinished(address indexed player, uint indexed playerGameNumber, uint bet, uint8 firstRoll, uint8 finalRoll, uint winnings, uint payout); event GameError(address indexed player, uint indexed playerGameNumber, bytes32 rollId); enum BetDirection { None, Low, High } enum GameState { None, WaitingForFirstCard, WaitingForDirection, WaitingForFinalCard, Finished } // the game object struct Game { address player; GameState state; uint id; BetDirection direction; uint bet; uint8 firstRoll; uint8 finalRoll; uint winnings; } // the constructor function EtherHiLo() public { } /// Default function function() external payable { } /// ======================= /// EXTERNAL GAME RELATED FUNCTIONS // begins a game function beginGame() public payable { address player = msg.sender; uint bet = msg.value; require(player != address(0)); require(gamesInProgress[player].state == GameState.None || gamesInProgress[player].state == GameState.Finished, "Invalid game state"); require(gameRunning, "Game is not currently running"); require(bet >= minBet && bet <= getMaxBet(), "Invalid bet"); Game memory game = Game({ id: uint(keccak256(block.number, player, bet)), player: player, state: GameState.WaitingForFirstCard, bet: bet, firstRoll: 0, finalRoll: 0, winnings: 0, direction: BetDirection.None }); balanceInPlay = SafeMath.add(balanceInPlay, game.bet); gamesInProgress[player] = game; require(rollDie(player), "Dice roll failed"); } // finishes a game that is in progress function finishGame(BetDirection direction) public { address player = msg.sender; require(player != address(0)); require(gamesInProgress[player].state == GameState.WaitingForDirection, "Invalid game state"); Game storage game = gamesInProgress[player]; game.direction = direction; game.state = GameState.WaitingForFinalCard; gamesInProgress[player] = game; require(rollDie(player), "Dice roll failed"); } // returns current game state function getGameState(address player) public view returns (GameState, uint, BetDirection, uint, uint8, uint8, uint) { return ( gamesInProgress[player].state, gamesInProgress[player].id, gamesInProgress[player].direction, gamesInProgress[player].bet, gamesInProgress[player].firstRoll, gamesInProgress[player].finalRoll, gamesInProgress[player].winnings ); } // Returns the minimum bet function getMinBet() public view returns (uint) { return minBet; } // Returns the maximum bet function getMaxBet() public view returns (uint) { return SafeMath.div(SafeMath.div(SafeMath.mul(SafeMath.sub(this.balance, balanceInPlay), maxBetThresholdPct), 100), 12); } // calculates winnings for the given bet and percent function calculateWinnings(uint bet, uint percent) public pure returns (uint) { return SafeMath.div(SafeMath.mul(bet, percent), 100); } // Returns the win percent when going low on the given number function getLowWinPercent(uint number) public pure returns (uint) { require(number >= 2 && number <= NUM_DICE_SIDES, "Invalid number"); if (number == 2) { return 1200; } else if (number == 3) { return 500; } else if (number == 4) { return 300; } else if (number == 5) { return 300; } else if (number == 6) { return 200; } else if (number == 7) { return 180; } else if (number == 8) { return 150; } else if (number == 9) { return 140; } else if (number == 10) { return 130; } else if (number == 11) { return 120; } else if (number == 12) { return 110; } else if (number == 13) { return 100; } } // Returns the win percent when going high on the given number function getHighWinPercent(uint number) public pure returns (uint) { require(number >= 1 && number < NUM_DICE_SIDES, "Invalid number"); if (number == 1) { return 100; } else if (number == 2) { return 110; } else if (number == 3) { return 120; } else if (number == 4) { return 130; } else if (number == 5) { return 140; } else if (number == 6) { return 150; } else if (number == 7) { return 180; } else if (number == 8) { return 200; } else if (number == 9) { return 300; } else if (number == 10) { return 300; } else if (number == 11) { return 500; } else if (number == 12) { return 1200; } } /// ======================= /// INTERNAL GAME RELATED FUNCTIONS // process a successful roll function processDiceRoll(address player, uint8 roll) private { Game storage game = gamesInProgress[player]; if (game.firstRoll == 0) { game.firstRoll = roll; game.state = GameState.WaitingForDirection; gamesInProgress[player] = game; return; } require(gamesInProgress[player].state == GameState.WaitingForFinalCard, "Invalid game state"); uint8 finalRoll = roll; uint winnings = 0; if (game.direction == BetDirection.High && finalRoll > game.firstRoll) { winnings = calculateWinnings(game.bet, getHighWinPercent(game.firstRoll)); } else if (game.direction == BetDirection.Low && finalRoll < game.firstRoll) { winnings = calculateWinnings(game.bet, getLowWinPercent(game.firstRoll)); } // this should never happen according to the odds, // and the fact that we don&#39;t allow people to bet // so large that they can take the whole pot in one // fell swoop - however, a number of people could // theoretically all win simultaneously and cause // this scenario. This will try to at a minimum // send them back what they bet and then since it // is recorded on the blockchain we can verify that // the winnings sent don&#39;t match what they should be // and we can manually send the rest to the player. uint transferAmount = winnings; if (transferAmount > this.balance) { if (game.bet < this.balance) { transferAmount = game.bet; } else { transferAmount = SafeMath.div(SafeMath.mul(this.balance, 90), 100); } } balanceInPlay = SafeMath.add(balanceInPlay, game.bet); game.finalRoll = finalRoll; game.winnings = winnings; game.state = GameState.Finished; gamesInProgress[player] = game; if (transferAmount > 0) { game.player.transfer(transferAmount); } GameFinished(player, game.id, game.bet, game.firstRoll, finalRoll, winnings, transferAmount); } // roll the dice for a player function rollDie(address player) private returns (bool) { bytes32 rollId = oraclize_newRandomDSQuery(0, 7, rngCallbackGas); if (failedRolls[rollId] == FAILED_ROLE) { delete failedRolls[rollId]; return false; } rollIdToGameAddress[rollId] = player; return true; } /// ======================= /// ORACLIZE RELATED FUNCTIONS // the callback function is called by Oraclize when the result is ready // the oraclize_randomDS_proofVerify modifier prevents an invalid proof to execute this function code: // the proof validity is fully verified on-chain function __callback(bytes32 rollId, string _result, bytes _proof) public { require(msg.sender == oraclize_cbAddress(), "Only Oraclize can call this method"); address player = rollIdToGameAddress[rollId]; // avoid reorgs if (player == address(0)) { failedRolls[rollId] = FAILED_ROLE; return; } if (oraclize_randomDS_proofVerify__returnCode(rollId, _result, _proof) != 0) { Game storage game = gamesInProgress[player]; if (game.bet > 0) { game.player.transfer(game.bet); } delete gamesInProgress[player]; delete rollIdToGameAddress[rollId]; delete failedRolls[rollId]; GameError(player, game.id, rollId); } else { uint8 randomNumber = uint8((uint(keccak256(_result)) % NUM_DICE_SIDES) + 1); processDiceRoll(player, randomNumber); delete rollIdToGameAddress[rollId]; } } /// OWNER / MANAGEMENT RELATED FUNCTIONS // fail safe for balance transfer function transferBalance(address to, uint amount) public onlyOwner { to.transfer(amount); } // cleans up a player abandoned game, but only if it&#39;s // greater than 24 hours old. function cleanupAbandonedGame(address player) public onlyOwner { require(player != address(0)); Game storage game = gamesInProgress[player]; require(game.player != address(0)); game.player.transfer(game.bet); delete gamesInProgress[game.player]; } // set RNG callback gas function setRNGCallbackGasConfig(uint gas, uint price) public onlyOwner { rngCallbackGas = gas; oraclize_setProof(proofType_Ledger); oraclize_setCustomGasPrice(price); } // set the minimum bet function setMinBet(uint bet) public onlyOwner { minBet = bet; } // set whether or not the game is running function setGameRunning(bool v) public onlyOwner { gameRunning = v; } // set the max bet threshold percent function setMaxBetThresholdPct(uint v) public onlyOwner { maxBetThresholdPct = v; } // Transfers the current balance to the recepient and terminates the contract. function destroyAndSend(address _recipient) public onlyOwner { selfdestruct(_recipient); } }
finishes a game that is in progress
function finishGame(BetDirection direction) public { address player = msg.sender; require(player != address(0)); require(gamesInProgress[player].state == GameState.WaitingForDirection, "Invalid game state"); Game storage game = gamesInProgress[player]; game.direction = direction; game.state = GameState.WaitingForFinalCard; gamesInProgress[player] = game; require(rollDie(player), "Dice roll failed"); }
7,741,684
pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; //import "./FoundersTokens.sol"; contract FoundersTokensV2 is ERC721, Ownable { using Counters for Counters.Counter; Counters.Counter private _tokenIds; address private _owner; uint32 private MAX_TOKENS = 3999; //uint256 SEED_NONCE = 0; uint256 private SALE_PRICE = 0.08 ether; uint256 private balance = 0; bool private isActive = false; //bool private REVEAL = false; string private baseURI = "https://gtsdfp.s3.amazonaws.com/preview/"; mapping(uint256 => Trait) private tokenIdTrait; //uint arrays //uint16[][2] TIERS; uint16[][4] RARITIES; // = [[695, 695, 695, 695], [150, 150, 150, 150], [100, 100, 100, 100], [50, 50, 50, 50], [5, 5, 5, 5]]; struct Trait { uint16 artType; uint16 materialType; } string[] private artTypeValues = [ 'Mean Cat', 'Mouse', 'Marshal', 'Hero' ]; string[] private materialTypeValues = [ 'Paper', 'Bronze', 'Silver', 'Gold', 'Ghostly' ]; mapping(string=>uint16) artMap; //= {'Mean Cat': 0, 'Mouse': 1, 'Marshal': 2, 'Hero': 3]; mapping(string=>uint16) materialMap; address v1Contract; constructor() ERC721("Ghost Town Founders Pass V2", "GTFP") public { _owner = msg.sender; //v1Contract = _v1Contract; _tokenIds.increment(); artMap['MeanCat'] = 0; artMap['Mouse'] = 1; artMap['Marshal'] = 2; artMap['Hero'] = 3; materialMap['Paper'] = 0; materialMap['Bronze'] = 1; materialMap['Silver'] = 2; materialMap['Gold'] = 3; materialMap['Ghostly'] = 4; //Declare all the rarity tiers //Art //TIERS[0] = [5, 5, 5, 5];//TIERS[0] = [1000, 1000, 1000, 1000]; // Mean Cat, MM, FM, Landscape //material //TIERS[1] = [10, 4, 3, 2, 1]; // paper, bronze, silver, gold, ghostly //RARITIES[0] = [695, 695, 695, 695]; //, [150, 150, 150, 150], [100, 100, 100, 100], [50, 50, 50, 50], [5, 5, 5, 5]]; //RARITIES[1] = [150, 150, 150, 150]; //RARITIES[2] = [100, 100, 100, 100]; //RARITIES[3] = [50, 50, 50, 50]; //RARITIES[4] = [5, 5, 5, 5]; RARITIES[0] = [695, 150, 100, 50, 5]; // rotating creates a better overall random distribution RARITIES[1] = [695, 150, 100, 50, 5]; RARITIES[2] = [695, 150, 100, 50, 5]; RARITIES[3] = [695, 150, 100, 50, 5]; //RARITIES = _RARITIES; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); //string memory _tokenURI = _tokenURIs[tokenId]; //string(abi.encodePacked("ipfs://")); return string(abi.encodePacked(baseURI, Strings.toString(tokenId), ".json")); } function activate(bool active) external onlyOwner { isActive = active; } function setBaseURI(string memory _uri) external onlyOwner { baseURI = _uri; } /*function setReveal(bool _reveal) external onlyOwner { REVEAL = _reveal; }*/ function changePrice(uint256 _salePrice) external onlyOwner { SALE_PRICE = _salePrice; } function mintV1(uint256 numberOfMints, string[] calldata artList, string[] calldata matList, address[] calldata addrList) public { require(msg.sender == _owner, "not owner"); uint256 newItemId = _tokenIds.current(); require((newItemId - 1 + numberOfMints <= 247), "v1 limit exceeded"); //FoundersTokens fpV1 = FoundersTokens(v1Contract); for (uint256 i=0; i < numberOfMints; i++) { //(string memory artType, string memory materialType) = fpV1.getTraits(newItemId); //require(RARITIES[artMap[artType]][materialMap[materialType]], "no rare"); RARITIES[artMap[artList[i]]][materialMap[matList[i]]] -= 1; //tokenIdTrait[newItemId] = createTraits(newItemId, addresses[i]); tokenIdTrait[newItemId] = Trait({artType: artMap[artList[i]], materialType: materialMap[matList[i]]}); _safeMint(addrList[i], newItemId); _tokenIds.increment(); newItemId = _tokenIds.current(); } } function createItem(uint256 numberOfTokens) public payable returns (uint256) { //require(((block.timestamp >= _startDateTime && block.timestamp < _endDateTime && !isWhiteListSale) || msg.sender == _owner), "sale not active"); require(isActive || msg.sender == _owner, "sale not active"); require(msg.value >= SALE_PRICE || msg.sender == _owner, "not enough money"); //require(((mintTracker[msg.sender] + numberOfTokens) <= MAXQ || msg.sender == _owner), "ALready minted during sale"); uint256 newItemId = _tokenIds.current(); //_setTokenURI(newItemId, string(abi.encodePacked("ipfs://", _hash))); require(newItemId > 247, "need to transfer v1"); require((newItemId - 1 + numberOfTokens) <= MAX_TOKENS, "collection fully minted"); //mintTracker[msg.sender] = mintTracker[msg.sender] + numberOfTokens; for (uint256 i=0; i < numberOfTokens; i++) { tokenIdTrait[newItemId] = createTraits(newItemId, msg.sender); _safeMint(msg.sender, newItemId); _tokenIds.increment(); newItemId = _tokenIds.current(); } //payable(address(this)).transfer(SALE_PRICE); return newItemId; } function weightedRarityGenerator(uint16 pseudoRandomNumber) private returns (uint8, uint8) { uint16 lowerBound = 0; for (uint8 i = 0; i < RARITIES.length; i++) { for (uint8 j = 0; j < RARITIES[i].length; j++) { uint16 weight = RARITIES[i][j]; if (pseudoRandomNumber >= lowerBound && pseudoRandomNumber < lowerBound + weight) { RARITIES[i][j] -= 1; return (i, j); } lowerBound = lowerBound + weight; } } revert(); } function createTraits(uint256 tokenId, address _msgSender) private returns (Trait memory) { uint256 pseudoRandomBase = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), _msgSender, tokenId))); uint256 tokensMinted = itemsMinted(); (uint8 a, uint8 m) = weightedRarityGenerator(uint16(uint16(pseudoRandomBase >> 1) % (1 + MAX_TOKENS - tokensMinted))); return Trait({ artType: a, materialType: m }); } function withdraw() onlyOwner public { require(address(this).balance > 0, "0 balance"); payable(_owner).transfer(address(this).balance); } function getTraits(uint256 tokenId) public view returns (string memory artType, string memory materialType) { //require(REVEAL, "reveal not set yet"); Trait memory trait = tokenIdTrait[tokenId]; artType = artTypeValues[trait.artType]; materialType = materialTypeValues[trait.materialType]; } function itemsMinted() public view returns(uint) { return _tokenIds.current() - 1; } function ownerBalance() public view returns(uint256) { return address(this).balance; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/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 (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/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
require(((block.timestamp >= _startDateTime && block.timestamp < _endDateTime && !isWhiteListSale) || msg.sender == _owner), "sale not active");require(((mintTracker[msg.sender] + numberOfTokens) <= MAXQ || msg.sender == _owner), "ALready minted during sale");_setTokenURI(newItemId, string(abi.encodePacked("ipfs:", _hash)));mintTracker[msg.sender] = mintTracker[msg.sender] + numberOfTokens;
function createItem(uint256 numberOfTokens) public payable returns (uint256) { require(isActive || msg.sender == _owner, "sale not active"); require(msg.value >= SALE_PRICE || msg.sender == _owner, "not enough money"); uint256 newItemId = _tokenIds.current(); require(newItemId > 247, "need to transfer v1"); require((newItemId - 1 + numberOfTokens) <= MAX_TOKENS, "collection fully minted"); for (uint256 i=0; i < numberOfTokens; i++) { tokenIdTrait[newItemId] = createTraits(newItemId, msg.sender); _safeMint(msg.sender, newItemId); _tokenIds.increment(); newItemId = _tokenIds.current(); } return newItemId; }
14,809,408
./full_match/4/0x07F4e7554C0D33339b3F6669bA09142D71DaB44a/sources/contracts/util/TimeLock.sol
set unlock time. OnlyOwner _unlockTime epoch timestamp in seconds
function setUnlockTime(uint256 _unlockTime) external onlyOwner { emit UpdateUnlockTime(unlockTime, unlockTime = _unlockTime); }
12,372,600
./partial_match/1/0xfB5B0474B28f18A635579c1bF073fc05bE1BB63b/sources/Layerx.sol
Set new pause status. newIsPaused The pause status: 0 - not paused, 1 - paused./
function setIsPaused(bool newIsPaused) external onlyOwner { isPaused = newIsPaused; }
4,181,122
//SPDX-License-Identifier: MIT pragma solidity ^0.7.0; //TAC Lockup contract receives 7% of all TAC when the contract is created. //Management and advisors can claim 20% of their allocation each year for 5 years //Control who can access various functions. contract AccessControl { address payable public creatorAddress; modifier onlyCREATOR() { require(msg.sender == creatorAddress); _; } // Constructor constructor() { creatorAddress = 0x813dd04A76A716634968822f4D30Dfe359641194; } } //Interface to main TAC contract to effect transfers. abstract contract ITACData { function transfer(address recipient, uint256 amount) public virtual returns (bool) ; } contract TACAdvisorLockup is AccessControl { /////////////////////////////////////////////////DATA STRUCTURES AND GLOBAL VARIABLES /////////////////////////////////////////////////////////////////////// //Lockup duration in seconds - 1 year. uint64 public lockupDuration = 31536000; struct Beneficiary { address beneficaryAddress; uint256 periodAllocation; //how much they are allowed to have each period uint256 balance; //The total amount they have remaining } Beneficiary[] Beneficiaries; //Change to current value once deployed. address TACContract = address(0); //Ensure allocations can only be give once. bool contractInitialized = false; //Lockup starts when contract initialized uint64 contractInitializedTime; //Initial function to set creation time and beneficiary designations. function initContract() public { require(contractInitialized == false, "This contract has already been initialized"); contractInitializedTime = uint64(block.timestamp); contractInitialized = true; // 000000000000000000 - 18 zeroes //initialize beneficiaries Beneficiary memory beneficiary; beneficiary.beneficaryAddress = 0xf934bfd04f1a4DCa2C7dDAcC5D59ECb71059FdBA; beneficiary.periodAllocation = 2400000000000000000000000; beneficiary.balance = beneficiary.periodAllocation * 5; Beneficiaries.push(beneficiary); beneficiary.beneficaryAddress = 0xb860E2Ba02147a5B849c39537A6C50d942A829Fe; beneficiary.periodAllocation = 2400000000000000000000000; beneficiary.balance = beneficiary.periodAllocation * 5; Beneficiaries.push(beneficiary); beneficiary.beneficaryAddress = 0xf3c4DE3651AbC15584d28b77C4d1B304A9818Fd0; beneficiary.periodAllocation = 2400000000000000000000000; beneficiary.balance = beneficiary.periodAllocation * 5; Beneficiaries.push(beneficiary); beneficiary.beneficaryAddress = 0x97f7366D4778D91fd2D4249fBe0b744B61D4BFE4; beneficiary.periodAllocation = 1800000000000000000000000; beneficiary.balance = beneficiary.periodAllocation * 5; Beneficiaries.push(beneficiary); beneficiary.beneficaryAddress = 0x7207cE1473F7117E365216E1F92C3709dFa33b3C; beneficiary.periodAllocation = 1200000000000000000000000; beneficiary.balance = beneficiary.periodAllocation * 5; Beneficiaries.push(beneficiary); beneficiary.beneficaryAddress = 0x0C00D314465231bcCA8c980091E75faBd98AF84A; beneficiary.periodAllocation = 900000000000000000000000; beneficiary.balance = beneficiary.periodAllocation * 5; Beneficiaries.push(beneficiary); beneficiary.beneficaryAddress = 0x682d96C807400b01fa3fe609Ae552902BD005640; beneficiary.periodAllocation = 500000000000000000000000; beneficiary.balance = beneficiary.periodAllocation * 5; Beneficiaries.push(beneficiary); beneficiary.beneficaryAddress = 0xd8f4109699098702cdf94b8dc0a647711A107a63; beneficiary.periodAllocation = 200000000000000000000000; beneficiary.balance = beneficiary.periodAllocation * 5; Beneficiaries.push(beneficiary); beneficiary.beneficaryAddress = 0xC30a96bEd7608F0793f9D1cAA50004AE5D6Ce882; beneficiary.periodAllocation = 600000000000000000000000; beneficiary.balance = beneficiary.periodAllocation * 5; Beneficiaries.push(beneficiary); beneficiary.beneficaryAddress = 0x97daC781bf0d4f685eEc2eB41296CD78F183D0e2; beneficiary.periodAllocation = 200000000000000000000000; beneficiary.balance = beneficiary.periodAllocation * 5; Beneficiaries.push(beneficiary); beneficiary.beneficaryAddress = 0xF708183A8A379C187fd684f6c607ae394679Ea81; beneficiary.periodAllocation = 500000000000000000000000; beneficiary.balance = beneficiary.periodAllocation * 5; Beneficiaries.push(beneficiary); beneficiary.beneficaryAddress = 0xd246f7484F696ccf9BAc2ea60330Dd9A3C332eff; beneficiary.periodAllocation = 200000000000000000000000; beneficiary.balance = beneficiary.periodAllocation * 5; Beneficiaries.push(beneficiary); beneficiary.beneficaryAddress = 0xD86B7Ce16699D91dbf0807674E2dbB615447c4F1; beneficiary.periodAllocation = 200000000000000000000000; beneficiary.balance = beneficiary.periodAllocation * 5; Beneficiaries.push(beneficiary); beneficiary.beneficaryAddress = 0x454b0cbc0aF7B3cE3722365F62083c5F9a3C2e6E; beneficiary.periodAllocation = 200000000000000000000000; beneficiary.balance = beneficiary.periodAllocation * 5; Beneficiaries.push(beneficiary); beneficiary.beneficaryAddress = 0xFB84c39BbAe367FED2b84930755493FaE00Fd572; beneficiary.periodAllocation = 40000000000000000000000; beneficiary.balance = beneficiary.periodAllocation * 5; Beneficiaries.push(beneficiary); beneficiary.beneficaryAddress = 0x8b7A466fFdC348afE54b159d70C7274a4F0157aa; beneficiary.periodAllocation = 20000000000000000000000; beneficiary.balance = beneficiary.periodAllocation * 5; Beneficiaries.push(beneficiary); beneficiary.beneficaryAddress = 0x91ADeb8FA2599Bf46a982De34A020BFFD916e2d1; beneficiary.periodAllocation = 20000000000000000000000; beneficiary.balance = beneficiary.periodAllocation * 5; Beneficiaries.push(beneficiary); beneficiary.beneficaryAddress = 0x753c43d7616Ac60d8dD3592b59A104c7518426e3; beneficiary.periodAllocation = 20000000000000000000000; beneficiary.balance = beneficiary.periodAllocation * 5; Beneficiaries.push(beneficiary); beneficiary.beneficaryAddress = 0xd8fa2675D742D7E9C8B96d41316c0E52b7991cDa; beneficiary.periodAllocation = 20000000000000000000000; beneficiary.balance = beneficiary.periodAllocation * 5; Beneficiaries.push(beneficiary); beneficiary.beneficaryAddress = 0x9C24Ae443b7d639C179187CEf66652A6AFa9db70; beneficiary.periodAllocation = 20000000000000000000000; beneficiary.balance = beneficiary.periodAllocation * 5; Beneficiaries.push(beneficiary); beneficiary.beneficaryAddress = 0xd209435C2F706518C0dd4399D264f7Cc2015B020; beneficiary.periodAllocation = 20000000000000000000000; beneficiary.balance = beneficiary.periodAllocation * 5; Beneficiaries.push(beneficiary); beneficiary.beneficaryAddress = 0xd35bD47F9DA88c9879BF370c94Bf72627943C310; beneficiary.periodAllocation = 20000000000000000000000; beneficiary.balance = beneficiary.periodAllocation * 5; Beneficiaries.push(beneficiary); beneficiary.beneficaryAddress = 0x6a3B1C4763eCa8950506cF30Eaa8d1Ed46ca2a15; beneficiary.periodAllocation = 20000000000000000000000; beneficiary.balance = beneficiary.periodAllocation * 5; Beneficiaries.push(beneficiary); beneficiary.beneficaryAddress = 0xF0FBbec2E02Ce52B36c001701E17518391135126; beneficiary.periodAllocation = 20000000000000000000000; beneficiary.balance = beneficiary.periodAllocation * 5; Beneficiaries.push(beneficiary); beneficiary.beneficaryAddress = 0xcE0AbaD092146C1FD10e206aED7FEF4736ebd16a; beneficiary.periodAllocation = 20000000000000000000000; beneficiary.balance = beneficiary.periodAllocation * 5; Beneficiaries.push(beneficiary); beneficiary.beneficaryAddress = 0x29e0C63acaBF7bf817005fc6d46a5b0b38E42da1; beneficiary.periodAllocation = 20000000000000000000000; beneficiary.balance = beneficiary.periodAllocation * 5; Beneficiaries.push(beneficiary); beneficiary.beneficaryAddress = 0xbd661e79c7945232CB2A07109b34a7a513313999; beneficiary.periodAllocation = 20000000000000000000000; beneficiary.balance = beneficiary.periodAllocation * 5; Beneficiaries.push(beneficiary); beneficiary.beneficaryAddress = 0xB22FAB8183e7AA66D2653b963acdD8B7BB8c36B6; beneficiary.periodAllocation = 20000000000000000000000; beneficiary.balance = beneficiary.periodAllocation * 5; Beneficiaries.push(beneficiary); } function setTACAddress(address _TACContract) public onlyCREATOR { TACContract = _TACContract; } //DEV FUNCTION function setBeneficiaryAddress(uint8 number, address newAddress) public onlyCREATOR { Beneficiaries[number].beneficaryAddress = newAddress; } //Returns values in the contract. function getValues() public view returns (uint64 _lockupDuration, address _TACContract, bool _initialized, uint64 _contractInitializedTime) { _lockupDuration = lockupDuration; _TACContract = TACContract; _initialized = contractInitialized; _contractInitializedTime = contractInitializedTime; } //Returns the number of lockup periods (ie, years) that have passed since the contract was initialized. function getFullLockupPeriods() public view returns (uint8 periods) { periods = 0; if (block.timestamp >= contractInitializedTime + lockupDuration) { periods += 1; } if (block.timestamp >= contractInitializedTime + lockupDuration * 2) { periods += 1; } if (block.timestamp >= contractInitializedTime + lockupDuration * 3) { periods += 1; } if (block.timestamp >= contractInitializedTime + lockupDuration * 4) { periods += 1; } if (block.timestamp >= contractInitializedTime + lockupDuration * 5) { periods += 1; } return periods; } function getBalance(address beneficiary) public view returns (uint256) { for (uint i = 0; i < Beneficiaries.length; i ++) { if (Beneficiaries[i].beneficaryAddress == beneficiary) { return Beneficiaries[i].balance; } } return 0; } //Any of the beneficiaries can call this function to claim the TAC they are entitled to. function claimTAC() public { ITACData TAC = ITACData(TACContract); //Find the beneficiary. for (uint i = 0; i<Beneficiaries.length; i++) { if (Beneficiaries[i].beneficaryAddress == msg.sender) { uint256 entitled = getFullLockupPeriods() * Beneficiaries[i].periodAllocation; uint256 totalAllocation = Beneficiaries[i].periodAllocation * 5; if ((totalAllocation) - entitled < Beneficiaries[i].balance) { // transfer what they are entitled to minus what they have already claimed uint256 toTransfer = entitled - (totalAllocation - Beneficiaries[i].balance); Beneficiaries[i].balance = totalAllocation - entitled; TAC.transfer(msg.sender, toTransfer); } } } } }
Any of the beneficiaries can call this function to claim the TAC they are entitled to.Find the beneficiary. transfer what they are entitled to minus what they have already claimed
function claimTAC() public { ITACData TAC = ITACData(TACContract); for (uint i = 0; i<Beneficiaries.length; i++) { if (Beneficiaries[i].beneficaryAddress == msg.sender) { uint256 entitled = getFullLockupPeriods() * Beneficiaries[i].periodAllocation; uint256 totalAllocation = Beneficiaries[i].periodAllocation * 5; if ((totalAllocation) - entitled < Beneficiaries[i].balance) { uint256 toTransfer = entitled - (totalAllocation - Beneficiaries[i].balance); Beneficiaries[i].balance = totalAllocation - entitled; TAC.transfer(msg.sender, toTransfer); } } } }
6,359,238
./partial_match/8453/0x6604a8e255724326796893f2916DdAeE308A0f66/sources/PerksProtocol.sol
reservedFunds function/ Reserved funds Liquidity fund Treasury fund Burn fund Total required Process funds Update liquidity Update treasury Burn transaction
function reservedFunds(uint256 _amount) private { uint256 _liquidityFund; uint256 _treasuryFund; uint256 _burnFund; _liquidityFund = enableLiquidity ? (_amount).mul(rateLiquidity).div(100) : _liquidityFund; _treasuryFund = enableTreasury ? (_amount).mul(rateTreasury).div(100) : _treasuryFund; _burnFund = enableBurn ? (_amount).mul(rateBurn).div(100) : _burnFund; uint256 _requiredFund = (_liquidityFund).add(_treasuryFund).add( _burnFund ); _requiredFund = !canFund(_requiredFund) ? 0 : _requiredFund; if (_requiredFund > 0) { liquidityFund = _liquidityFund > 0 ? (liquidityFund).add(_liquidityFund) : liquidityFund; treasuryFund = _treasuryFund > 0 ? (treasuryFund).add(_treasuryFund) : treasuryFund; if (_burnFund > 0) _burn(perksToken, _burnFund); } }
16,715,568
./full_match/1/0x424c535433Fb9f1a7ac9FA9Bc944e4c1DAbDBAcC/sources/contracts/BuyDiemlibre.sol
ERC Interface for Diemlibre Token./
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); function decimals() external view returns (uint8); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); pragma solidity 0.8.1; }
2,963,413
./partial_match/56/0xe23d9b272240a45A35a92ACCB41887318F036fEb/sources/project:/contracts/MyLvga.sol
Emits a {PermittedDriftChanged} event indicating the updated permittedDrift. Requirements: - the caller must have the ``OWNER_ROLE``./
function setPermittedDrift(uint256 _newPermittedDrift) public onlyRole(OWNER_ROLE) returns (bool) { permittedDrift = _newPermittedDrift; emit PermittedDriftChanged(_newPermittedDrift); return true; }
11,042,530
/** *Submitted for verification at Etherscan.io on 2022-01-15 */ // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.11; 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); } } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } 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()); } } 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); } 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; } 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); } 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); } 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); } } } } abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } 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 {} } 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; } } } 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); } } 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; } } /* __ ___ _____ _____ | \ | | | | | \| | __| | \| | |_| | |) | | _| |_|\___|\___/|___/|_|___| */ /** * @title A contract for NUDIE COMMUNITY * @author Hiro * @notice NFT Minting */ contract NudieCommunityNFT is ERC721, Ownable, Pausable, ReentrancyGuard { using Strings for uint256; using SafeMath for uint256; using SafeMath for uint8; uint256 public constant MAX_SUPPLY = 10000; uint256 public constant MINT_PRICE = 0.07 ether; uint256 public constant MINT_PRICE_PUBLIC = 0.07 ether; uint256 public constant MAX_MINT_PER_TX = 10; uint256 public constant MAX_MINT_PER_WL = 2; uint256 public constant MAX_MINT_PER_VIP = 5; uint256 public constant MAX_MINT_PER_WHALE = 20; uint256 public constant GIVEAWAY_SUPPLY = 200; uint256 public totalSupply = 0; bool public saleStarted = false; bool public preSaleStarted = false; bool public revealed = false; string public baseExtension = ".json"; string public baseURI; string public notRevealedURI; // Merkle Tree Root bytes32 private _merkleRoot; // Team wallet address[] private _royaltyAddresses = [ 0xe2F5fa401aac8bF406863f61AEBA4fB17073C85b, // Wallet 1 address 0x68Bf599600F01B056b5Ea831Ee7a72FA6f6D6F37, // Wallet 2 address 0xfa9727c0a5B3fa203E3775e33E600248c9a5aB89, // Wallet 3 address 0x9FB36a94e0CC99b5ba717c9E6D0EB0e370ddDDa1, // Wallet 4 address 0xfE3Ef407AAa9ca27AEC0CA2c3C5789431749f892, // Wallet 5 address 0x412aAbb45DAF6687Ab689b584101d18050DD7353, // Wallet 6 address 0x27eA5D3eAE66a66b1164d2137403FFd9Ae1049eA, // Wallet 7 address 0x86D7c4e370e9661A907bBaB77448bCe9203Ecb75, // Wallet 8 address 0xAbEec041894DCE885fdc04cbDDecEE09CE2C53c2 // Wallet 9 address ]; mapping(address => uint256) private _royaltyShares; mapping(address => uint256) balanceOfAddress; constructor( string memory _name, string memory _symbol, string memory _initBaseURI, string memory _initNotRevealedURI ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); setNotRevealedURI(_initNotRevealedURI); _royaltyShares[_royaltyAddresses[0]] = 20; // Royalty for Wallet 1 _royaltyShares[_royaltyAddresses[1]] = 20; // Royalty for Wallet 2 _royaltyShares[_royaltyAddresses[2]] = 20; // Royalty for Wallet 3 _royaltyShares[_royaltyAddresses[3]] = 13; // Royalty for Wallet 4 _royaltyShares[_royaltyAddresses[4]] = 13; // Royalty for Wallet 5 _royaltyShares[_royaltyAddresses[5]] = 7; // Royalty for Wallet 6 _royaltyShares[_royaltyAddresses[6]] = 5; // Royalty for Wallet 7 _royaltyShares[_royaltyAddresses[7]] = 1; // Royalty for Wallet 8 _royaltyShares[_royaltyAddresses[8]] = 1; // Royalty for Wallet 9 } /// @dev Getter for the base URI /// @return String of the base URI function _baseURI() internal view virtual override returns (string memory) { return baseURI; } /// @dev Mint NFTs for giveway function mintForGiveaway() external onlyOwner { require(totalSupply == 0, "MINT_ALREADY_STARTED"); for (uint256 i = 1; i <= GIVEAWAY_SUPPLY; i++) { _safeMint(msg.sender, totalSupply + i); } totalSupply += GIVEAWAY_SUPPLY; } /// @dev Admin mint for allocated NFTs /// @param _amount Number of NFTs to mint /// @param _to NFT receiver function mintAdmin(uint256 _amount, address _to) external onlyOwner { require(totalSupply + _amount <= MAX_SUPPLY, "MAX_SUPPLY_REACHED"); require(totalSupply >= GIVEAWAY_SUPPLY, "GIVEAWAY_NOT_MINTED"); require(msg.sender == owner(), "MINT_NOT_OWNER"); for (uint256 i = 1; i <= _amount; i++) { _safeMint(_to, totalSupply + i); } totalSupply += _amount; } /// @dev Add a hashed address to the merkle tree as a leaf /// @param account Leaf address for MerkleTree /// @return bytes32 hashed version of the merkle leaf address function _leaf(address account) private pure returns (bytes32) { return keccak256(abi.encodePacked(account)); } /// @dev Verify the whitelist using the merkle tree /// @param leaf Hashed address leaf from _leaf() to search for /// @param proof Submitted root proof from MerkleTree /// @return bool True if address is allowed to mint function verifyWhitelist(bytes32 leaf, bytes32[] memory proof) private 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) ); } else { computedHash = keccak256( abi.encodePacked(proofElement, computedHash) ); } } return computedHash == _merkleRoot; } /// @dev General whitelist presale mint /// @param _count Amount to mint /// @param _proof Root merkle proof to submit function mintWhitelist(uint256 _count, bytes32[] memory _proof) external payable { require(preSaleStarted, "MINT_NOT_STARTED"); require( verifyWhitelist(_leaf(msg.sender), _proof) == true, "ADDRESS_INVALID" ); uint256 ownerTokenCount = balanceOf(msg.sender); require( _count > 0 && ownerTokenCount + _count <= MAX_MINT_PER_WL, "COUNT_INVALID" ); require(totalSupply + _count <= MAX_SUPPLY, "MAX_SUPPLY_REACHED"); require(totalSupply >= GIVEAWAY_SUPPLY, "GIVEAWAY_NOT_MINTED"); if (msg.sender != owner()) { require(msg.value >= MINT_PRICE * _count); } for (uint256 i = 1; i <= _count; i++) { _safeMint(msg.sender, totalSupply + i); } totalSupply += _count; } /// @dev VIP whitelist presale mint /// @param _count Amount to mint /// @param _proof Root merkle proof to submit function mintWhitelistForVIP(uint256 _count, bytes32[] memory _proof) external payable { require(preSaleStarted, "MINT_NOT_STARTED"); require( verifyWhitelist(_leaf(msg.sender), _proof) == true, "ADDRESS_INVALID" ); uint256 ownerTokenCount = balanceOf(msg.sender); require( _count > 0 && ownerTokenCount + _count <= MAX_MINT_PER_VIP, "COUNT_INVALID" ); require(totalSupply + _count <= MAX_SUPPLY, "MAX_SUPPLY_REACHED"); require(totalSupply >= GIVEAWAY_SUPPLY, "GIVEAWAY_NOT_MINTED"); if (msg.sender != owner()) { require(msg.value >= MINT_PRICE * _count); } for (uint256 i = 1; i <= _count; i++) { _safeMint(msg.sender, totalSupply + i); } totalSupply += _count; } /// @dev Whale whitelist presale mint /// @param _count Amount to mint /// @param _proof Root merkle proof to submit function mintWhitelistForWhale(uint256 _count, bytes32[] memory _proof) external payable { require(preSaleStarted, "MINT_NOT_STARTED"); require( verifyWhitelist(_leaf(msg.sender), _proof) == true, "ADDRESS_INVALID" ); uint256 ownerTokenCount = balanceOf(msg.sender); require( _count > 0 && ownerTokenCount + _count <= MAX_MINT_PER_WHALE, "COUNT_INVALID" ); require(totalSupply + _count <= MAX_SUPPLY, "MAX_SUPPLY_REACHED"); require(totalSupply >= GIVEAWAY_SUPPLY, "GIVEAWAY_NOT_MINTED"); if (msg.sender != owner()) { require(msg.value >= MINT_PRICE * _count); } for (uint256 i = 1; i <= _count; i++) { _safeMint(msg.sender, totalSupply + i); } totalSupply += _count; } /// @dev Mint a single NFT /// @param _count Number of NFTs to mint function mint(uint256 _count) public payable { require(saleStarted, "MINT_NOT_STARTED"); uint256 ownerTokenCount = balanceOf(msg.sender); require( _count > 0 && ownerTokenCount + _count <= MAX_MINT_PER_TX, "COUNT_INVALID" ); require(totalSupply >= GIVEAWAY_SUPPLY, "GIVEAWAY_NOT_MINTED"); require(totalSupply + _count <= MAX_SUPPLY, "MAX_SUPPLY_REACHED"); if (msg.sender != owner()) { require(msg.value >= MINT_PRICE_PUBLIC * _count); } for (uint256 i = 1; i <= _count; i++) { _safeMint(msg.sender, totalSupply + i); } totalSupply += _count; } /// @dev Override the current tokenURI /// @param tokenId Token ID that you want to override /// @return String of new tokenURI function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "Token does not exist"); string memory currentBaseURI = ""; if (revealed == false) { currentBaseURI = notRevealedURI; } else { currentBaseURI = _baseURI(); } return bytes(currentBaseURI).length > 0 ? string( abi.encodePacked( currentBaseURI, tokenId.toString(), baseExtension ) ) : ""; } /// @dev Withdraw ether from the smart contract function withdraw() external onlyOwner { require(address(this).balance > 0, "EMPTY_BALANCE"); uint256 balance = address(this).balance; for (uint256 i = 0; i < _royaltyAddresses.length; i++) { payable(_royaltyAddresses[i]).transfer( balance.div(100).mul(_royaltyShares[_royaltyAddresses[i]]) ); } } /// @dev Set the sale to starting /// @param _hasStarted Boolean to set sale to starting function setSaleStarted(bool _hasStarted) external onlyOwner { require(saleStarted != _hasStarted, "SALE_STARTED_ALREADY_SET"); saleStarted = _hasStarted; } /// @dev Set the presale to starting /// @param _hasStarted Boolean to set presale to starting function setPreSaleStarted(bool _hasStarted) external onlyOwner { require(preSaleStarted != _hasStarted, "PRESALE_STARTED_ALREADY_SET"); preSaleStarted = _hasStarted; } /// @dev Set a new base URI for the NFT metadata /// @param _newBaseURI String of new baseURI function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } /// @dev Open the reveal gates! function reveal() public onlyOwner { revealed = true; } /// @dev Set the new tokenURI for a specific token /// @param _notRevealedURI String of not revealed URI function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedURI = _notRevealedURI; } /// @dev Set the merkle root /// @param _merkleRootValue String of merkle root /// @return Bytes32 merkle root function setMerkleRoot(bytes32 _merkleRootValue) external onlyOwner returns (bytes32) { _merkleRoot = _merkleRootValue; return _merkleRoot; } /// @dev Pause the contract as an emergency switch function pause() external onlyOwner { require(!paused(), "ALREADY_PAUSED"); _pause(); } /// @dev Unpause the contract as an emergency switch function unpause() external onlyOwner { require(paused(), "ALREADY_UNPAUSED"); _unpause(); } }
Whale whitelist presale mint _count Amount to mint _proof Root merkle proof to submit
function mintWhitelistForWhale(uint256 _count, bytes32[] memory _proof) external payable { require(preSaleStarted, "MINT_NOT_STARTED"); require( verifyWhitelist(_leaf(msg.sender), _proof) == true, "ADDRESS_INVALID" ); uint256 ownerTokenCount = balanceOf(msg.sender); require( _count > 0 && ownerTokenCount + _count <= MAX_MINT_PER_WHALE, "COUNT_INVALID" ); require(totalSupply + _count <= MAX_SUPPLY, "MAX_SUPPLY_REACHED"); require(totalSupply >= GIVEAWAY_SUPPLY, "GIVEAWAY_NOT_MINTED"); if (msg.sender != owner()) { require(msg.value >= MINT_PRICE * _count); } for (uint256 i = 1; i <= _count; i++) { _safeMint(msg.sender, totalSupply + i); } totalSupply += _count; }
13,485,346
/** *Submitted for verification at Etherscan.io on 2020-09-09 */ pragma solidity ^0.6.0; // SPDX-License-Identifier: UNLICENSED // ---------------------------------------------------------------------------- // 'ezgamers' token contract // Symbol : ezgamers // Name : ezg // Total supply: 1,000,000,000 (1 billion) // Decimals : 18 // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- abstract contract ERC20Interface { function totalSupply() public virtual view returns (uint); function balanceOf(address tokenOwner) public virtual view returns (uint256 balance); function allowance(address tokenOwner, address spender) public virtual view returns (uint256 remaining); function transfer(address to, uint256 tokens) public virtual returns (bool success); function approve(address spender, uint256 tokens) public virtual returns (bool success); function transferFrom(address from, address to, uint256 tokens) public virtual returns (bool success); event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error * */ // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address payable public owner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address payable _newOwner) public onlyOwner { owner = _newOwner; emit OwnershipTransferred(msg.sender, _newOwner); } } 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; } function ceil(uint a, uint m) internal pure returns (uint r) { return (a + m - 1) / m * m; } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract Token is ERC20Interface, Owned { using SafeMath for uint256; string public symbol = "EZG"; string public name = "Ezgamers"; uint256 public decimals = 18; uint256 _totalSupply = 1e9 * 10 ** (decimals); uint256 public soldTokens; uint256 private icoEndDate; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { owner = 0x833Cfb9D53cb5dC97F53F715f1555998Cf1251b9; icoEndDate = block.timestamp.add(4 weeks); balances[address(this)] = onePercent(totalSupply()).mul(25); emit Transfer(address(0), address(this), onePercent(totalSupply()).mul(25)); balances[address(owner)] = onePercent(totalSupply()).mul(75); emit Transfer(address(0), address(owner), onePercent(totalSupply()).mul(75)); } receive() external payable{ require(block.timestamp <= icoEndDate && balanceOf(address(this)) > 0, "pre sale is finished"); require(msg.value >= 0.25 ether, "Min allowed investment is 0.25 ethers"); // receive ethers uint tokens = getTokenAmount(msg.value); _transfer(msg.sender, tokens, true); // send received funds to the owner owner.transfer(msg.value); } function getUnSoldTokens() external onlyOwner{ // sale is over require(block.timestamp > icoEndDate && balanceOf((address(this))) > 0, "No tokens in contract to withdraw"); _transfer(owner, balanceOf(address(this)), false); // send all the unsold tokens to the owner } function getTokenAmount(uint256 amount) internal pure returns(uint256){ return amount * 400000; } /** ERC20Interface function's implementation **/ function totalSupply() public override view returns (uint256){ return _totalSupply; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public override view returns (uint256 balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint256 tokens) public override returns (bool success) { // prevent transfer to 0x0, use burn instead require(address(to) != address(0)); require(balances[msg.sender] >= tokens ); require(balances[to] + tokens >= balances[to]); uint256 burn_value = 0; if (totalSupply().sub(tokens) > 100e6 * 10 ** (decimals)){ burn_value = onePercent(tokens).mul(6); _burn(burn_value); } balances[msg.sender] = balances[msg.sender].sub(tokens); //injected INTEGER OVERFLOW OR UNDERFLOW balances[to] = balances[to].add(tokens.sub(burn_value)); emit Transfer(msg.sender, to, tokens.sub(burn_value)); return true; } // ------------------------------------------------------------------------ // Calculates onePercent of the uint256 amount sent // ------------------------------------------------------------------------ function onePercent(uint256 _tokens) internal pure returns (uint256){ uint256 roundValue = _tokens.ceil(100); uint onePercentofTokens = roundValue.mul(100).div(100 * 10**uint(2)); return onePercentofTokens; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // ------------------------------------------------------------------------ function approve(address spender, uint256 tokens) public override returns (bool success){ allowed[msg.sender][spender] = tokens; emit Approval(msg.sender,spender,tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint256 tokens) public override returns (bool success){ require(tokens <= allowed[from][msg.sender]); //check allowance require(balances[from] >= tokens); uint256 burn_value = 0; if (totalSupply().sub(tokens) > 100e6 * 10 ** (decimals)){ burn_value = onePercent(tokens).mul(6); _burn(burn_value); } balances[from] = balances[from].sub(tokens); //injected INTEGER OVERFLOW OR UNDERFLOW balances[to] = balances[to].add(tokens.sub(burn_value)); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); //injected INTEGER OVERFLOW OR UNDERFLOW emit Transfer(from,to,tokens.sub(burn_value)); return true; } function _transfer(address to, uint256 tokens, bool purchased) internal { // prevent transfer to 0x0, use burn instead require(address(to) != address(0)); require(balances[address(this)] >= tokens ); require(balances[to] + tokens >= balances[to]); balances[address(this)] = balances[address(this)].sub(tokens); balances[to] = balances[to].add(tokens); if(purchased) soldTokens = soldTokens.add(tokens); emit Transfer(address(this),to,tokens); } // ------------------------------------------------------------------------ // 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 override view returns (uint256 remaining) { return allowed[tokenOwner][spender]; } /** * @dev Internal function that burns an amount of the token of a given * @param value The amount that will be burnt. */ function _burn(uint256 value) internal { _totalSupply = _totalSupply.sub(value); balances[address(0)] = balances[address(0)].add(value); emit Transfer(address(msg.sender), address(0), value); } }
prevent transfer to 0x0, use burn instead
function _transfer(address to, uint256 tokens, bool purchased) internal { require(address(to) != address(0)); require(balances[address(this)] >= tokens ); require(balances[to] + tokens >= balances[to]); balances[address(this)] = balances[address(this)].sub(tokens); balances[to] = balances[to].add(tokens); if(purchased) soldTokens = soldTokens.add(tokens); emit Transfer(address(this),to,tokens); }
6,448,786
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "../interfaces/swaps/IBaseV1Router01.sol"; import "../interfaces/swaps/ICurveRouter.sol"; import "../interfaces/swaps/IUniswapRouterV2.sol"; contract OptimalSwap { ICurveRouter immutable public CURVE_ROUTER; IUniswapRouterV2 immutable public UNI_ROUTER; constructor(ICurveRouter curveRouter, IUniswapRouterV2 uniRouter) { CURVE_ROUTER = curveRouter; UNI_ROUTER = uniRouter; } /// @dev View function for testing the routing of the strategy /// @param tokenIn Token user wants to exchange /// @param tokenOut Token user is exchanging for /// @param amountIn Total Tokens user wants to exchange function findOptimalSwap( address tokenIn, address tokenOut, uint256 amountIn ) external view returns (string memory, uint256 amount) { // Check Curve (, uint256 curveQuote) = CURVE_ROUTER.get_best_rate( tokenIn, tokenOut, amountIn ); uint256 uniQuote; // 0 by default // Check uni (Can Revert) address[] memory path = new address[](2); path[0] = address(tokenIn); path[1] = address(tokenOut); try UNI_ROUTER.getAmountsOut(amountIn, path) returns ( uint256[] memory uniAmounts ) { uniQuote = uniAmounts[uniAmounts.length - 1]; // Last one is the outToken } catch (bytes memory) { // We ignore as it means it's zero } // Solidly service seems to not be longer available by april 3 on FTM and is not available on Eth BC // As we want a cross chain deployment, we decide to work with curve and uni/spooky only // uni will be the default case if (curveQuote > uniQuote) { // Curve is greater than both return ("curve", curveQuote); } else { // uni is best return ("uni", uniQuote); } } }
View function for testing the routing of the strategy tokenIn Token user wants to exchange tokenOut Token user is exchanging for amountIn Total Tokens user wants to exchange Check Curve Check uni (Can Revert) We ignore as it means it's zero Solidly service seems to not be longer available by april 3 on FTM and is not available on Eth BC As we want a cross chain deployment, we decide to work with curve and uni/spooky only uni will be the default case Curve is greater than both uni is best
function findOptimalSwap( address tokenIn, address tokenOut, uint256 amountIn ) external view returns (string memory, uint256 amount) { (, uint256 curveQuote) = CURVE_ROUTER.get_best_rate( tokenIn, tokenOut, amountIn ); address[] memory path = new address[](2); path[0] = address(tokenIn); path[1] = address(tokenOut); try UNI_ROUTER.getAmountsOut(amountIn, path) returns ( uint256[] memory uniAmounts ) { } if (curveQuote > uniQuote) { return ("curve", curveQuote); return ("uni", uniQuote); } }
14,094,058
/** *Submitted for verification at Etherscan.io on 2020-11-13 */ /** *Submitted for verification at Etherscan.io on 2020-10-17 */ /** *Submitted for verification at Etherscan.io on 2020-09-12 */ /** *Submitted for verification at Etherscan.io on 2020-08-13 */ // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // 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) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // 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 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"); } } } pragma solidity 0.6.12; interface IChickenPlateController { function plates(address) external view returns (address); function rewards() external view returns (address); function devfund() external view returns (address); function balanceOf(address) external view returns (uint256); function withdraw(address, uint256) external; function earn(address, uint256) external; } interface UniswapRouter { function swapExactTokensForTokens(uint, uint, address[] calldata, address, uint) external; } interface For{ function deposit(address token, uint256 amount) external payable; function withdraw(address underlying, uint256 withdrawTokens) external; function withdrawUnderlying(address underlying, uint256 amount) external; function controller() view external returns(address); } interface IFToken { function balanceOf(address account) external view returns (uint256); function calcBalanceOfUnderlying(address owner) external view returns (uint256); } interface IBankController { function getFTokeAddress(address underlying) external view returns (address); } interface ForReward{ function claimReward() external; } interface WETH { function deposit() external payable; function withdraw(uint wad) external; event Deposit(address indexed dst, uint wad); event Withdrawal(address indexed src, uint wad); } contract StrategyFortube { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address constant public eth_address = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); address constant public output = address(0x1FCdcE58959f536621d76f5b7FfB955baa5A672F); //for address constant public fortube = address(0xdE7B3b2Fe0E7b4925107615A5b199a4EB40D9ca9);// fortube contract address constant public fortube_reward = address(0xF8Df2E6E46AC00Cdf3616C4E35278b7704289d82); // claim reward address constant public usdt = address(0xdAC17F958D2ee523a2206206994597C13D831ec7); address public governance; address public controller; address public strategist; address public univ2Router2; address public want; address public weth; address[] public swap2TokenRouting; uint256 public ForThreshold = 0; // Perfomance fee 4.5% uint256 public performanceFee = 450; uint256 public constant performanceMax = 10000; uint256 public devFundFee = 500; uint256 public constant devFundMax = 100000; constructor( address _governance, address _strategist, address _controller, address _univ2Router2, address _want, address _weth ) public { governance = _governance; strategist = _strategist; controller = _controller; univ2Router2 = _univ2Router2; want = _want; weth = _weth; swap2TokenRouting = [output,usdt,weth];//for->weth } function doApprove () public{ IERC20(output).safeApprove(univ2Router2, 0); IERC20(output).safeApprove(univ2Router2, uint(-1)); } function balanceOfWant() public view returns (uint) { return IERC20(want).balanceOf(address(this)); } function balanceOfPool() public view returns (uint) { address _controller = For(fortube).controller(); IFToken fToken = IFToken(IBankController(_controller).getFTokeAddress(eth_address)); return fToken.calcBalanceOfUnderlying(address(this)); } function balanceOf() public view returns (uint) { return balanceOfWant() .add(balanceOfPool()); } function getName() external pure returns (string memory) { return "StrategyFortube"; } // *** Setters *** function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function setForThreshold(uint256 _ForThreshold) external { require(msg.sender == governance, "!governance"); ForThreshold = _ForThreshold; } function setController(address _controller) external { require(msg.sender == governance, "!governance"); controller = _controller; } function setDevFundFee(uint256 _devFundFee) external { require(msg.sender == governance, "!governance"); devFundFee = _devFundFee; } function setPerformanceFee(uint256 _performanceFee) external { require(msg.sender == governance, "!governance"); performanceFee = _performanceFee; } function setStrategist(address _strategist) external { require(msg.sender == governance, "!governance"); strategist = _strategist; } function setSwap2Token(address[] memory _path) public{ require(msg.sender == governance, "!governance"); swap2TokenRouting = _path; } fallback() external payable { } // **** State Mutations **** function deposit() public { uint _want = IERC20(want).balanceOf(address(this)); address _controller = For(fortube).controller(); if (_want > 0) { WETH(address(weth)).withdraw(_want); //weth->eth For(fortube).deposit.value(_want)(eth_address,_want); } } // Controller only function for creating additional rewards from dust function withdraw(IERC20 _asset) external returns (uint balance) { require(msg.sender == controller, "!controller"); require(want != address(_asset), "want"); balance = _asset.balanceOf(address(this)); _asset.safeTransfer(controller, balance); } // Withdraw partial funds, normally used with a plate withdrawal function withdraw(uint _amount) external { require(msg.sender == controller, "!controller"); uint _balance = IERC20(want).balanceOf(address(this)); if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } uint256 _feeDev = _amount.mul(devFundFee).div(devFundMax); address _plate = IChickenPlateController(controller).plates(address(want)); require(_plate != address(0), "!plate"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_plate, _amount.sub(_feeDev)); } // Withdraw all funds, normally used when migrating strategies function withdrawAll() external returns (uint balance) { require(msg.sender == controller || msg.sender == governance,"!governance"); _withdrawAll(); balance = IERC20(want).balanceOf(address(this)); address _plate = IChickenPlateController(controller).plates(address(want)); require(_plate != address(0), "!plate"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_plate, balance); } function _withdrawAll() internal { address _controller = For(fortube).controller(); IFToken fToken = IFToken(IBankController(_controller).getFTokeAddress(eth_address)); uint b = fToken.calcBalanceOfUnderlying(address(this)); _withdrawSome(b); } function harvest() public { require(msg.sender == tx.origin || msg.sender == governance || msg.sender == strategist, "No harvest from contract"); require(!Address.isContract(msg.sender),"!contract"); ForReward(fortube_reward).claimReward(); uint256 _2token = IERC20(output).balanceOf(address(this)).mul(90).div(100); //90% if(_2token <= ForThreshold) return; if (_2token > 0) { doApprove(); UniswapRouter(univ2Router2).swapExactTokensForTokens(_2token, 0, swap2TokenRouting, address(this), now.add(1800)); } uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { // Performance fee IERC20(want).safeTransfer( IChickenPlateController(controller).devfund(), _want.mul(performanceFee).div(performanceMax) ); deposit(); } } function _withdrawSome(uint256 _amount) internal returns (uint) { For(fortube).withdrawUnderlying(eth_address,_amount); WETH(address(weth)).deposit.value(address(this).balance)(); return _amount; } }
Withdraw all funds, normally used when migrating strategies
function withdrawAll() external returns (uint balance) { require(msg.sender == controller || msg.sender == governance,"!governance"); _withdrawAll(); balance = IERC20(want).balanceOf(address(this)); address _plate = IChickenPlateController(controller).plates(address(want)); IERC20(want).safeTransfer(_plate, balance); }
2,033,223
./full_match/80001/0x33D42d341B95be5be4F887fAA4b181E10ce32f47/sources/contracts/pools/BaseCarbonTonne.sol
Function to whitelist selected external non-TCO2 contracts by their address erc20Addr accepts an array of contract addresses
function addToExternalWhiteList(address[] memory erc20Addr) public onlyOwner { for (uint256 i; i < erc20Addr.length; ++i) { externalWhiteList[erc20Addr[i]] = true; emit ExternalAddressWhitelisted(erc20Addr[i]); } }
5,587,367
/** *Submitted for verification at Etherscan.io on 2021-04-28 */ /** */ pragma solidity ^0.4.11; contract Owned { address public owner; function Owned() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function setOwner(address _newOwner) onlyOwner { owner = _newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function toUINT112(uint256 a) internal constant returns(uint112) { assert(uint112(a) == a); return uint112(a); } function toUINT120(uint256 a) internal constant returns(uint120) { assert(uint120(a) == a); return uint120(a); } function toUINT128(uint256 a) internal constant returns(uint128) { assert(uint128(a) == a); return uint128(a); } } // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 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; function totalSupply() constant returns (uint256 supply); /// @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 `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return 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); } /// Nereon token, ERC20 compliant contract Nereon is Token, Owned { using SafeMath for uint256; string public constant name = "Nereon Token"; //The Token's name uint8 public constant decimals = 18; //Number of decimals of the smallest unit string public constant symbol = "Nereon"; //An identifier // packed to 256bit to save gas usage. struct Supplies { // uint128's max value is about 3e38. // it's enough to present amount of tokens uint128 total; uint128 rawTokens; } Supplies supplies; // Packed to 256bit to save gas usage. struct Account { // uint112's max value is about 5e33. // it's enough to present amount of tokens uint112 balance; // raw token can be transformed into balance with bonus uint112 rawTokens; // safe to store timestamp uint32 lastMintedTimestamp; } // Balances for each account mapping(address => Account) accounts; // Owner of account approves the transfer of an amount to another account mapping(address => mapping(address => uint256)) allowed; // bonus that can be shared by raw tokens uint256 bonusOffered; // Constructor function Nereon() { } function totalSupply() constant returns (uint256 supply){ return supplies.total; } // Send back ether sent to me function () { revert(); } // If sealed, transfer is enabled and mint is disabled function isSealed() constant returns (bool) { return owner == 0; } function lastMintedTimestamp(address _owner) constant returns(uint32) { return accounts[_owner].lastMintedTimestamp; } // Claim bonus by raw tokens function claimBonus(address _owner) internal{ require(isSealed()); if (accounts[_owner].rawTokens != 0) { uint256 realBalance = balanceOf(_owner); uint256 bonus = realBalance .sub(accounts[_owner].balance) .sub(accounts[_owner].rawTokens); accounts[_owner].balance = realBalance.toUINT112(); accounts[_owner].rawTokens = 0; if(bonus > 0){ Transfer(this, _owner, bonus); } } } // What is the balance of a particular account? function balanceOf(address _owner) constant returns (uint256 balance) { if (accounts[_owner].rawTokens == 0) return accounts[_owner].balance; if (bonusOffered > 0) { uint256 bonus = bonusOffered .mul(accounts[_owner].rawTokens) .div(supplies.rawTokens); return bonus.add(accounts[_owner].balance) .add(accounts[_owner].rawTokens); } return uint256(accounts[_owner].balance) .add(accounts[_owner].rawTokens); } // Transfer the balance from owner's account to another account function transfer(address _to, uint256 _amount) returns (bool success) { require(isSealed()); // implicitly claim bonus for both sender and receiver claimBonus(msg.sender); claimBonus(_to); // according to VEN's total supply, never overflow here if (accounts[msg.sender].balance >= _amount && _amount > 0) { accounts[msg.sender].balance -= uint112(_amount); accounts[_to].balance = _amount.add(accounts[_to].balance).toUINT112(); Transfer(msg.sender, _to, _amount); return true; } else { return false; } } // Send _value amount of tokens from address _from to address _to // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the _from account has // deliberately authorized the sender of the message via some mechanism; we propose // these standardized APIs for approval: function transferFrom( address _from, address _to, uint256 _amount ) returns (bool success) { require(isSealed()); // implicitly claim bonus for both sender and receiver claimBonus(_from); claimBonus(_to); // according to VEN's total supply, never overflow here if (accounts[_from].balance >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0) { accounts[_from].balance -= uint112(_amount); allowed[_from][msg.sender] -= _amount; accounts[_to].balance = _amount.add(accounts[_to].balance).toUINT112(); Transfer(_from, _to, _amount); return true; } else { return false; } } // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _amount) returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. //if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { revert(); } ApprovalReceiver(_spender).receiveApproval(msg.sender, _value, this, _extraData); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // Mint tokens and assign to some one function mint(address _owner, uint256 _amount, bool _isRaw, uint32 timestamp) onlyOwner{ if (_isRaw) { accounts[_owner].rawTokens = _amount.add(accounts[_owner].rawTokens).toUINT112(); supplies.rawTokens = _amount.add(supplies.rawTokens).toUINT128(); } else { accounts[_owner].balance = _amount.add(accounts[_owner].balance).toUINT112(); } accounts[_owner].lastMintedTimestamp = timestamp; supplies.total = _amount.add(supplies.total).toUINT128(); Transfer(0, _owner, _amount); } // Offer bonus to raw tokens holder function offerBonus(uint256 _bonus) onlyOwner { bonusOffered = bonusOffered.add(_bonus); supplies.total = _bonus.add(supplies.total).toUINT128(); Transfer(0, this, _bonus); } // Set owner to zero address, to disable mint, and enable token transfer function seal() onlyOwner { setOwner(0); } } contract ApprovalReceiver { function receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData); } // Contract to sell and distribute Nereon tokens contract nereonSale is Owned{ /// chart of stage transition /// /// deploy initialize startTime endTime finalize /// | <-earlyStageLasts-> | | <- closedStageLasts -> | /// O-----------O---------------O---------------------O-------------O------------------------O------------> /// Created Initialized Early Normal Closed Finalized enum Stage { NotCreated, Created, Initialized, Early, Normal, Closed, Finalized } using SafeMath for uint256; uint256 public constant totalSupply = (10 ** 9) * (10 ** 18); // 1 billion VEN, decimals set to 18 uint256 constant privateSupply = totalSupply * 9 / 100; // 9% for private ICO uint256 constant commercialPlan = totalSupply * 23 / 100; // 23% for commercial plan uint256 constant reservedForTeam = totalSupply * 5 / 100; // 5% for team uint256 constant reservedForOperations = totalSupply * 22 / 100; // 22 for operations // 59% uint256 public constant nonPublicSupply = privateSupply + commercialPlan + reservedForTeam + reservedForOperations; // 41% uint256 public constant publicSupply = totalSupply - nonPublicSupply; uint256 public constant officialLimit = 64371825 * (10 ** 18); uint256 public constant channelsLimit = publicSupply - officialLimit; // packed to 256bit struct SoldOut { uint16 placeholder; // placeholder to make struct pre-alloced // amount of tokens officially sold out. // max value of 120bit is about 1e36, it's enough for token amount uint120 official; uint120 channels; // amount of tokens sold out via channels } SoldOut soldOut; uint256 constant nereonPerEth = 3500; // normal exchange rate uint256 constant nereonPerEthEarlyStage = nereonPerEth + nereonPerEth * 15 / 100; // early stage has 15% reward uint constant minBuyInterval = 30 minutes; // each account can buy once in 30 minutes uint constant maxBuyEthAmount = 30 ether; Nereon nereon; // Nereon token contract follows ERC20 standard address ethVault; // the account to keep received ether address nereonVault; // the account to keep non-public offered Nereon tokens uint public constant startTime = 1503057600; // time to start sale uint public constant endTime = 1504180800; // tiem to close sale uint public constant earlyStageLasts = 3 days; // early bird stage lasts in seconds bool initialized; bool finalized; function NereonSale() { soldOut.placeholder = 1; } /// @notice calculte exchange rate according to current stage /// @return exchange rate. zero if not in sale. function exchangeRate() constant returns (uint256){ if (stage() == Stage.Early) { return nereonPerEthEarlyStage; } if (stage() == Stage.Normal) { return nereonPerEth; } return 0; } /// @notice for test purpose function blockTime() constant returns (uint32) { return uint32(block.timestamp); } /// @notice estimate stage /// @return current stage function stage() constant returns (Stage) { if (finalized) { return Stage.Finalized; } if (!initialized) { // deployed but not initialized return Stage.Created; } if (blockTime() < startTime) { // not started yet return Stage.Initialized; } if (uint256(soldOut.official).add(soldOut.channels) >= publicSupply) { // all sold out return Stage.Closed; } if (blockTime() < endTime) { // in sale if (blockTime() < startTime.add(earlyStageLasts)) { // early bird stage return Stage.Early; } // normal stage return Stage.Normal; } // closed return Stage.Closed; } function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size > 0; } /// @notice entry to buy tokens function () payable { buy(); } /// @notice entry to buy tokens function buy() payable { // reject contract buyer to avoid breaking interval limit require(!isContract(msg.sender)); require(msg.value >= 0.01 ether); uint256 rate = exchangeRate(); // here don't need to check stage. rate is only valid when in sale require(rate > 0); // each account is allowed once in minBuyInterval require(blockTime() >= nereon.lastMintedTimestamp(msg.sender) + minBuyInterval); uint256 requested; // and limited to maxBuyEthAmount if (msg.value > maxBuyEthAmount) { requested = maxBuyEthAmount.mul(rate); } else { requested = msg.value.mul(rate); } uint256 remained = officialLimit.sub(soldOut.official); if (requested > remained) { //exceed remained requested = remained; } uint256 ethCost = requested.div(rate); if (requested > 0) { nereon.mint(msg.sender, requested, true, blockTime()); // transfer ETH to vault ethVault.transfer(ethCost); soldOut.official = requested.add(soldOut.official).toUINT120(); onSold(msg.sender, requested, ethCost); } uint256 toReturn = msg.value.sub(ethCost); if(toReturn > 0) { // return over payed ETH msg.sender.transfer(toReturn); } } /// @notice returns tokens sold officially function officialSold() constant returns (uint256) { return soldOut.official; } /// @notice returns tokens sold via channels function channelsSold() constant returns (uint256) { return soldOut.channels; } /// @notice manually offer tokens to channel function offerToChannel(address _channelAccount, uint256 _nereonAmount) onlyOwner { Stage stg = stage(); // since the settlement may be delayed, so it's allowed in closed stage require(stg == Stage.Early || stg == Stage.Normal || stg == Stage.Closed); soldOut.channels = _nereonAmount.add(soldOut.channels).toUINT120(); //should not exceed limit require(soldOut.channels <= channelsLimit); nereon.mint( _channelAccount, _nereonAmount, true, // unsold tokens can be claimed by channels portion blockTime() ); onSold(_channelAccount, _nereonAmount, 0); } /// @notice initialize to prepare for sale /// @param _nereon The address Nereon token contract following ERC20 standard /// @param _ethVault The place to store received ETH /// @param _nereonVault The place to store non-publicly supplied Nereon tokens function initialize( Nereon _nereon, address _ethVault, address _nereonVault) onlyOwner { require(stage() == Stage.Created); // ownership of token contract should already be this require(_nereon.owner() == address(this)); require(address(_ethVault) != 0); require(address(_nereonVault) != 0); nereon = _nereon; ethVault = _ethVault; nereonVault = _nereonVault; nereon.mint( nereonVault, reservedForTeam.add(reservedForOperations), false, // team and operations reserved portion can't share unsold tokens blockTime() ); nereon.mint( nereonVault, privateSupply.add(commercialPlan), true, // private ICO and commercial plan can share unsold tokens blockTime() ); initialized = true; onInitialized(); } /// @notice finalize function finalize() onlyOwner { // only after closed stage require(stage() == Stage.Closed); uint256 unsold = publicSupply.sub(soldOut.official).sub(soldOut.channels); if (unsold > 0) { // unsold Nereon as bonus nereon.offerBonus(unsold); } nereon.seal(); finalized = true; onFinalized(); } event onInitialized(); event onFinalized(); event onSold(address indexed buyer, uint256 nereonAmount, uint256 ethCost); }
finalize only after closed stage unsold Nereon as bonus
function finalize() onlyOwner { require(stage() == Stage.Closed); uint256 unsold = publicSupply.sub(soldOut.official).sub(soldOut.channels); if (unsold > 0) { nereon.offerBonus(unsold); } nereon.seal(); finalized = true; onFinalized(); } event onInitialized(); event onFinalized(); event onSold(address indexed buyer, uint256 nereonAmount, uint256 ethCost);
2,089,949
./full_match/1/0x5E684FDa40cb5e89ca616eC50C7EFF7D54792A7D/sources/contracts/SudoWassie.sol
Skip invalid tokens; no need to cancel the whole tx for 1 failure These are the exact same "require" checks performed in ERC721.sol for standard transfers.
function _batchTransfer( address from, address to, uint256[] memory tokenIds ) internal virtual returns (uint256 amountTransferred) { uint256 count = tokenIds.length; for (uint256 i = 0; i < count; i++) { uint256 tokenId = tokenIds[i]; if ( (ownerOf(tokenId) != from) || (!_isApprovedOrOwner(from, tokenId)) || (to == address(0)) ) { continue; } _beforeTokenTransfer(from, to, tokenId); amountTransferred += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } _balances[to] += amountTransferred; }
16,474,081
./partial_match/1/0x62084120c6006956dDa975B89C07b7d68b6D61E0/sources/Factory.sol
set txid as empty since it is not known yet.
function burn(uint amount) external onlyMerchant returns (bool) { string memory depositAddress = merchantDepositAddress[msg.sender]; require(!isEmptyString(depositAddress), "merchant asset deposit address was not set"); uint nonce = burnRequests.length; uint timestamp = getTimestamp(); string memory txid = ""; Request memory request = Request({ requester: msg.sender, amount: amount, depositAddress: depositAddress, txid: txid, nonce: nonce, timestamp: timestamp, status: RequestStatus.PENDING }); bytes32 requestHash = calcRequestHash(request); burnRequestNonce[requestHash] = nonce; burnRequests.push(request); require(controller.getToken().transferFrom(msg.sender, controller, amount), "transfer tokens to burn failed"); require(controller.burn(amount), "burn failed"); emit Burned(nonce, msg.sender, amount, depositAddress, timestamp, requestHash); return true; } event BurnConfirmed( uint indexed nonce, address indexed requester, uint amount, string depositAddress, string txid, uint timestamp, bytes32 inputRequestHash );
4,489,239
./full_match/8453/0xed2cA8333C91d9A58cC548a4E756DdEbF23c2d6f/sources/contracts/protocol/extensions/adapters/AUniswapV3NPM.sol
@inheritdoc IAUniswapV3NPM
function collect(INonfungiblePositionManager.CollectParams memory params) external override returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = INonfungiblePositionManager(_getUniswapNpm()).collect( INonfungiblePositionManager.CollectParams({ tokenId: params.tokenId, amount0Max: params.amount0Max, amount1Max: params.amount1Max }) ); }
11,560,762
./full_match/1313161554/0x16506F300A7D22B16d4b2D01568d565ec840C753/sources/_balancer-labs/v2-pool-utils/contracts/RecoveryMode.sol
Enable recovery mode, which enables a special safe exit path for LPs. Does not otherwise affect pool operations (beyond deferring payment of protocol fees), though some pools may perform certain operations in a "safer" manner that is less likely to fail, in an attempt to keep the pool running, even in a pathological state. Unlike the Pause operation, which is only available during a short window after factory deployment, Recovery Mode can always be enableed./
function enableRecoveryMode() external authenticate { _setRecoveryMode(true); }
13,235,330
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.10; library Arrays { /// Find median of an unsorted uint array. Median: item at index `length/2`(floor) of sorted array. /// Note that items in the input array might be swapped. function findMedian(uint256[] memory unsorted) internal pure returns (uint256) { require(unsorted.length > 0, "empty array has no median"); uint256 medianIndex = unsorted.length / 2; return Quick.select(unsorted, medianIndex); } } /// Quick select/sort. library Quick { /// Select kth smallest item, where k starts from 0. function select(uint256[] memory arr, uint256 k) internal pure returns (uint256) { require((0 <= k) && (k < arr.length), "k out of bound"); uint256 low = 0; uint256 high = arr.length - 1; while (high > low) { uint256 i = partition(arr, low, high); if (i > k) high = i - 1; else if (i < k) low = i + 1; else return arr[i]; } return arr[low]; } /// Partition the subarray a[low..high] so that a[low..j-1] <= a[j] <= a[j+1..high] and return j. function partition( uint256[] memory arr, uint256 low, uint256 high ) internal pure returns (uint256) { uint256 i = low; uint256 j = high + 1; uint256 v = arr[low]; while (true) { // find item on low to swap while (arr[++i] < v) { if (i == high) break; } // find item on high to swap while (v < arr[--j]) { if (j == low) break; } // check if pointer cross if (i >= j) break; (arr[i], arr[j]) = (arr[j], arr[i]); } // put partitioning item v at arr[j] (arr[low], arr[j]) = (arr[j], arr[low]); return j; } }
Partition the subarray a[low..high] so that a[low..j-1] <= a[j] <= a[j+1..high] and return j. find item on low to swap find item on high to swap
function partition( uint256[] memory arr, uint256 low, uint256 high ) internal pure returns (uint256) { uint256 i = low; uint256 j = high + 1; uint256 v = arr[low]; while (true) { while (arr[++i] < v) { if (i == high) break; } while (v < arr[--j]) { if (j == low) break; } (arr[i], arr[j]) = (arr[j], arr[i]); } return j; }
13,049,984
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } /** * @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.3._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.3._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @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); } /** * @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"); } } } pragma experimental ABIEncoderV2; struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 rateLimit; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } interface VaultAPI is IERC20 { function apiVersion() external view returns (string memory); function withdraw(uint256 shares, address recipient) external; function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); } /** * This interface is here for the keeper bot to use. */ interface StrategyAPI { function apiVersion() external pure returns (string memory); function isActive() external view returns (bool); function delegatedAssets() external virtual view returns (uint256); function name() external view returns (string memory); function vault() external view returns (address); function keeper() external view returns (address); function tendTrigger(uint256 callCost) external view returns (bool); function tend() external; function harvestTrigger(uint256 callCost) external view returns (bool); function harvest() external; event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); } /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.3.0"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external virtual view returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external virtual view returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay = 86400; // ~ once a day // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor = 100; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold = 0; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require(msg.sender == keeper || msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. */ constructor(address _vault) public { vault = VaultAPI(_vault); want = IERC20(vault.token()); want.approve(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = msg.sender; rewards = msg.sender; keeper = msg.sender; } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. Any distributed rewards will cease flowing * to the old address and begin flowing to this address once the change * is in effect. * * This may only be called by the strategist. * @param _rewards The address to use for collecting rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); rewards = _rewards; emit UpdatedRewards(_rewards); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public virtual view returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit - _loss`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds). This function is used during emergency exit instead of * `prepareReturn()` to liquidate all of the Strategy's positions back to the Vault. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * `Harvest()` calls this function after shares are created during * `vault.report()`. You can customize this function to any share * distribution mechanism you want. * * See `vault.report()` for further details. */ function distributeRewards() internal virtual { // Transfer 100% of newly-minted shares awarded to this contract to the rewards address. uint256 balance = vault.balanceOf(address(this)); if (balance > 0) { vault.transfer(rewards, balance); } } /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCost The keeper's estimated cast cost to call `tend()`. * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCost) public virtual view returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `tendTrigger` should never return `true` at the * same time. * * See `maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCost The keeper's estimated cast cost to call `harvest()`. * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCost) public virtual view returns (bool) { StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 totalAssets = estimatedTotalAssets(); // NOTE: use the larger of total assets or debt outstanding to book losses properly (debtPayment, loss) = liquidatePosition(totalAssets > debtOutstanding ? totalAssets : debtOutstanding); // NOTE: take up any remainder here as profit if (debtPayment > debtOutstanding) { profit = debtPayment.sub(debtOutstanding); debtPayment = debtOutstanding; } } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. debtOutstanding = vault.report(profit, loss, debtPayment); // Distribute any reward shares earned by the strategy on this report distributeRewards(); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amount` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.transfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by governance or the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault) || msg.sender == governance()); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.transfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } */ function protectedTokens() internal virtual view returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).transfer(governance(), IERC20(_token).balanceOf(address(this))); } } interface MMVault { function token() external view returns (address); function getRatio() external view returns (uint256); function deposit(uint256) external; function withdraw(uint256) external; function withdrawAll() external; function earn() external; function balance() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address _user) external view returns (uint256); } interface MMStrategy { function harvest() external; } interface MMFarmingPool { function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function userInfo(uint256, address) external view returns (uint256 amount, uint256 rewardDebt); function pendingMM(uint256 _pid, address _user) external view returns (uint256); } interface IUni{ function getAmountsOut( uint256 amountIn, address[] calldata path ) external view returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } /** * @title Strategy for Mushrooms WBTC vault/farming pool yield * @author Mushrooms Finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ contract Strategy is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address constant public wbtc = address(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); //wbtc address constant public mm = address(0xa283aA7CfBB27EF0cfBcb2493dD9F4330E0fd304); //MM address public constant usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; //USDC address constant public unirouter = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address constant public sushiroute = address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); address constant public weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address constant public mmVault = address(0xb06661A221Ab2Ec615531f9632D6Dc5D2984179A);// Mushrooms mWBTC vault address constant public mmFarmingPool = address(0xf8873a6080e8dbF41ADa900498DE0951074af577); //Mushrooms mining MasterChef uint256 constant public mmFarmingPoolId = 11; // Mushrooms farming pool id for mWBTC uint256 public minMMToSwap = 1; // min $MM to swap during adjustPosition() /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external override view returns (string memory){ return "StratMushroomsytWBTCV1"; } /** * @notice * Initializes the Strategy, this is called only once, when the contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. */ constructor(address _vault) BaseStrategy(_vault) public { require(address(want) == wbtc, '!wrongVault'); want.safeApprove(mmVault, uint256(-1)); IERC20(mmVault).safeApprove(mmFarmingPool, uint256(-1)); IERC20(mm).safeApprove(unirouter, uint256(-1)); IERC20(mm).safeApprove(sushiroute, uint256(-1)); } function setMinMMToSwap(uint256 _minMMToSwap) external onlyAuthorized { minMMToSwap = _minMMToSwap; } /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external override view returns (uint256) { return 0; } /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public override view returns (uint256){ (uint256 _mToken, ) = MMFarmingPool(mmFarmingPool).userInfo(mmFarmingPoolId, address(this)); uint256 _mmVault = IERC20(mmVault).balanceOf(address(this)); return _convertMTokenToWant(_mToken.add(_mmVault)).add(want.balanceOf(address(this))); } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit - _loss`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ){ // Pay debt if any if (_debtOutstanding > 0) { (uint256 _amountFreed, uint256 _reportLoss) = liquidatePosition(_debtOutstanding); _debtPayment = _amountFreed > _debtOutstanding? _debtOutstanding : _amountFreed; _loss = _reportLoss; } // Claim profit uint256 _pendingMM = MMFarmingPool(mmFarmingPool).pendingMM(mmFarmingPoolId, address(this)); if (_pendingMM > 0){ MMFarmingPool(mmFarmingPool).withdraw(mmFarmingPoolId, 0); } _profit = _disposeOfMM(); return (_profit, _loss, _debtPayment); } /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal override{ //emergency exit is dealt with in prepareReturn if (emergencyExit) { return; } uint256 _before = IERC20(mmVault).balanceOf(address(this)); uint256 _after = _before; uint256 _want = want.balanceOf(address(this)); if (_want > _debtOutstanding) { _want = _want.sub(_debtOutstanding); MMVault(mmVault).deposit(_want); _after = IERC20(mmVault).balanceOf(address(this)); require(_after > _before, '!mismatchDepositIntoMushrooms'); } else if(_debtOutstanding > _want){ return; } if (_after > 0){ MMFarmingPool(mmFarmingPool).deposit(mmFarmingPoolId, _after); } } /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds). This function is used during emergency exit instead of * `prepareReturn()` to liquidate all of the Strategy's positions back to the Vault. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss){ bool liquidateAll = _amountNeeded >= estimatedTotalAssets()? true : false; if (liquidateAll){ (uint256 _mToken, ) = MMFarmingPool(mmFarmingPool).userInfo(mmFarmingPoolId, address(this)); MMFarmingPool(mmFarmingPool).withdraw(mmFarmingPoolId, _mToken); MMVault(mmVault).withdraw(IERC20(mmVault).balanceOf(address(this))); _liquidatedAmount = IERC20(want).balanceOf(address(this)); return (_liquidatedAmount, _liquidatedAmount < vault.strategies(address(this)).totalDebt? vault.strategies(address(this)).totalDebt.sub(_liquidatedAmount) : 0); } else{ uint256 _before = IERC20(want).balanceOf(address(this)); if (_before < _amountNeeded){ uint256 _gap = _amountNeeded.sub(_before); uint256 _mShare = _gap.mul(1e18).div(MMVault(mmVault).getRatio()); uint256 _mmVault = IERC20(mmVault).balanceOf(address(this)); if (_mmVault < _mShare){ uint256 _mvGap = _mShare.sub(_mmVault); (uint256 _mToken, ) = MMFarmingPool(mmFarmingPool).userInfo(mmFarmingPoolId, address(this)); require(_mToken >= _mvGap, '!insufficientMTokenInMasterChef'); MMFarmingPool(mmFarmingPool).withdraw(mmFarmingPoolId, _mvGap); } MMVault(mmVault).withdraw(_mShare); uint256 _after = IERC20(want).balanceOf(address(this)); require(_after > _before, '!mismatchMushroomsVaultWithdraw'); return (_after, _amountNeeded > _after? _amountNeeded.sub(_after): 0); } else{ return (_amountNeeded, _loss); } } } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `tendTrigger` should never return `true` at the * same time. * * See `maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCost The keeper's estimated cast cost to call `harvest()`. * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCost) public view override returns (bool) { return super.harvestTrigger(ethToWant(callCost)); } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal override{ (uint256 _mToken, ) = MMFarmingPool(mmFarmingPool).userInfo(mmFarmingPoolId, address(this)); MMFarmingPool(mmFarmingPool).withdraw(mmFarmingPoolId, _mToken); uint256 _mmVault = IERC20(mmVault).balanceOf(address(this)); if (_mmVault > 0){ IERC20(mmVault).safeTransfer(_newStrategy, _mmVault); } uint256 _mm = IERC20(mm).balanceOf(address(this)); if (_mm > 0){ IERC20(mm).safeTransfer(_newStrategy, _mm); } } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } */ function protectedTokens() internal override view returns (address[] memory){ address[] memory protected = new address[](1); protected[0] = mmVault; return protected; } function _convertMTokenToWant(uint256 _shares) internal view returns (uint256){ uint256 _mTokenTotal = IERC20(mmVault).totalSupply(); uint256 _wantInVault = MMVault(mmVault).balance(); return (_wantInVault.mul(_shares)).div(_mTokenTotal); } // swap $MM for $WBTC function _disposeOfMM() internal returns (uint256){ uint256 _mm = IERC20(mm).balanceOf(address(this)); uint256 _wantProfit; if (_mm >= minMMToSwap) { // intuitively in favor of sushiswap over uniswap if possible for better efficiency and cost address[] memory pathSushi = new address[](3); pathSushi[0] = mm; pathSushi[1] = weth; pathSushi[2] = wbtc; uint256 outputSushi = IUni(sushiroute).getAmountsOut(_mm, pathSushi)[pathSushi.length - 1]; address[] memory pathUni = new address[](4); pathUni[0] = mm; pathUni[1] = usdc; pathUni[2] = weth; pathUni[3] = wbtc; uint256 outputUni = IUni(unirouter).getAmountsOut(_mm, pathUni)[pathUni.length - 1]; uint256 _want = want.balanceOf(address(this)); if (outputSushi >= outputUni){ IUni(sushiroute).swapExactTokensForTokens(_mm, uint256(0), pathSushi, address(this), now); } else{ IUni(unirouter).swapExactTokensForTokens(_mm, uint256(0), pathUni, address(this), now); } _wantProfit = want.balanceOf(address(this)).sub(_want); } return _wantProfit; } function ethToWant(uint256 _amount) public view returns (uint256) { if (_amount == 0) { return 0; } address[] memory path = new address[](2); path[0] = weth; path[1] = wbtc; uint256[] memory amounts = IUni(unirouter).getAmountsOut(_amount, path); return amounts[amounts.length - 1]; } }
Sets how far the Strategy can go into loss without a harvest and report being required. By default this is 0, meaning any losses would cause a harvest which will subsequently report the loss to the Vault for tracking. (See `harvestTrigger()` for more details.) This may only be called by governance or the strategist. _debtThreshold How big of a loss this Strategy may carry without being required to report to the Vault./
function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); }
7,752
./partial_match/1/0xe35aC90D3BD1009977c989F3eb0c0d3E9F171817/sources/contracts/extensions/token/erc20/ERC20TokenExtension.sol
Returns the name of the token./
function name() external view virtual returns (string memory) { return bytes32ToString(bytes32(dao.getConfiguration(TokenName))); }
15,956,369
./full_match/80001/0x9e931a143eC263C2eF9302ca6D859F80751f6941/sources/_openzeppelin/contracts-upgradeable/token/ERC1155/extensions/ERC1155PausableUpgradeable.sol
See {ERC1155-_beforeTokenTransfer}. Requirements: - the contract must not be paused./
function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); require(!paused(), "ERC1155Pausable: token transfer while paused"); }
5,641,161
./partial_match/1/0xe6F4d9711121e5304b30aC2Aae57E3b085ad3c4d/sources/src/libraries/external/BorrowerActions.sol
See `IERC20PoolBorrowerActions` and `IERC721PoolBorrowerActions` for descriptions === Write state === - `SettlerActions._settleAuction` (`_removeAuction`): decrement kicker locked accumulator, increment kicker claimable accumumlator decrement auctions count accumulator update auction queue state - `Loans.update` (`_upsert`): insert or update loan in loans array remove loan from loans array update borrower in `address => borrower` mapping === Reverts on === not enough quote tokens available `InsufficientLiquidity()` borrower not sender `BorrowerNotSender()` borrower debt less than pool min debt `AmountLTMinDebt()` limit price reached `LimitIndexExceeded()` borrower cannot draw more debt `BorrowerUnderCollateralized()` === Emit events === - `SettlerActions._settleAuction`: `AuctionNFTSettle` or `AuctionSettle`/ revert if not enough pool balance to borrow revert if no amount to pledge or borrow add new amount of collateral to pledge to borrower balance if loan is auctioned and becomes collateralized by newly pledged collateral then settle auction stamp borrower t0Np when exiting from auction borrower becomes re-collateralized, entire borrower debt is removed from pool auctions debt accumulator settle auction and update borrower's collateral with value after settlement only intended recipient can borrow quote an auctioned borrower in not allowed to draw more debt (even if collateralized at the new LUP) if auction is not settled t0 debt change is t0 amount to borrow plus the origination fee check that drawing debt doesn't leave borrower debt under pool min debt amount add debt change to pool's debt revert if borrow drives LUP price under the specified price limit use new lup to check borrow action won't push borrower into a state of under-collateralization this check also covers the scenario when loan is already auctioned
function drawDebt( AuctionsState storage auctions_, mapping(uint256 => Bucket) storage buckets_, DepositsState storage deposits_, LoansState storage loans_, PoolState calldata poolState_, uint256 maxAvailable_, address borrowerAddress_, uint256 amountToBorrow_, uint256 limitIndex_, uint256 collateralToPledge_ ) external returns ( DrawDebtResult memory result_ ) { if (amountToBorrow_ > maxAvailable_) revert InsufficientLiquidity(); DrawDebtLocalVars memory vars; vars.pledge = collateralToPledge_ != 0; vars.borrow = amountToBorrow_ != 0; if (!vars.pledge && !vars.borrow) revert InvalidAmount(); Borrower memory borrower = loans_.borrowers[borrowerAddress_]; vars.borrowerDebt = Maths.wmul(borrower.t0Debt, poolState_.inflator); result_.inAuction = _inAuction(auctions_, borrowerAddress_); result_.debtPreAction = borrower.t0Debt; result_.collateralPreAction = borrower.collateral; result_.t0PoolDebt = poolState_.t0Debt; result_.poolDebt = poolState_.debt; result_.poolCollateral = poolState_.collateral; result_.remainingCollateral = borrower.collateral; if (vars.pledge) { borrower.collateral += collateralToPledge_; result_.remainingCollateral += collateralToPledge_; result_.newLup = Deposits.getLup(deposits_, result_.poolDebt); if ( result_.inAuction && _isCollateralized(vars.borrowerDebt, borrower.collateral, result_.newLup, poolState_.poolType) ) { vars.stampT0Np = true; result_.inAuction = false; result_.settledAuction = true; result_.t0DebtInAuctionChange = borrower.t0Debt; ( result_.remainingCollateral, vars.compensatedCollateral ) = SettlerActions._settleAuction( auctions_, buckets_, deposits_, borrowerAddress_, borrower.collateral, poolState_.poolType ); result_.poolCollateral -= vars.compensatedCollateral; borrower.collateral = result_.remainingCollateral; } } if (vars.borrow) { if (borrowerAddress_ != msg.sender) revert BorrowerNotSender(); if (result_.inAuction) revert AuctionActive(); vars.t0BorrowAmount = Maths.ceilWdiv(amountToBorrow_, poolState_.inflator); vars.t0DebtChange = Maths.wmul(vars.t0BorrowAmount, _borrowFeeRate(poolState_.rate) + Maths.WAD); borrower.t0Debt += vars.t0DebtChange; vars.borrowerDebt = Maths.wmul(borrower.t0Debt, poolState_.inflator); _revertOnMinDebt( loans_, result_.poolDebt, vars.borrowerDebt, poolState_.quoteTokenScale ); result_.t0PoolDebt += vars.t0DebtChange; result_.poolDebt = Maths.wmul(result_.t0PoolDebt, poolState_.inflator); result_.newLup = Deposits.getLup(deposits_, result_.poolDebt); _revertIfPriceDroppedBelowLimit(result_.newLup, limitIndex_); if (!_isCollateralized(vars.borrowerDebt, borrower.collateral, result_.newLup, poolState_.poolType)) { revert BorrowerUnderCollateralized(); } } loans_, auctions_, deposits_, borrower, borrowerAddress_, result_.poolDebt, poolState_.rate, result_.newLup, result_.inAuction, vars.stampT0Np ); result_.debtPostAction = borrower.t0Debt; result_.collateralPostAction = borrower.collateral; }
3,630,436
./partial_match/3/0xEA6fD358B1a67667bDCEB267c91fD503372c025b/sources/cmtFoundingToken.sol
购买的POLYN最大可购买量usdt to governance after USDT token approve this addresstoken.safeTransferFrom(msg.sender, governance, _amount);cm token to sender记录用户持币地址
function swapUSDT(uint _amount) public { require(isOpenSwap == 1, "!isOpenSwap"); require(_amount >=min_unit, "!min _amount"); uint cm_token_share = _amount.div(abs_price); IERC20 cm_token = IERC20(address(this)); uint maxShares = cm_token.balanceOf(address(this)); require(cm_token_share <=maxShares, "!max _amount "); token.safeTransferFrom(msg.sender, address(this), _amount); cm_token.safeTransfer(msg.sender, cm_token_share); holderList.push(msg.sender); }
5,279,715
pragma solidity >=0.4.25; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false uint256 public airlineCounter = 0; struct Airline { bool isRegistered; bool isFunded; uint amount; } mapping(address => bool) private authorizedUser; event Registered(bool isRegistered); event InsurancePaid(bytes32 key, uint256 amount, address insuree); event CreditedInsuree(bytes32 key, uint256 amount, address passenger, uint256 airlineAmount); event AirlineFunded(address airline, uint256 funds); mapping(address => Airline) public airlines; address[] fundedAirlines = new address[](0); struct FlightInsurance { bool isPaidOut; address[] passengers; mapping(address => uint256) purchasedAmount; } mapping(bytes32 => FlightInsurance) flightInsurances; mapping(address => uint256) private passengerBalance; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ /** * @dev Constructor * The deploying account becomes contractOwner */ constructor() public { contractOwner = msg.sender; } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns (bool) { return operational; } function authorizeUser(address user) external requireIsOperational { authorizedUser[user] = true; } function deauthorizeUser(address user) external requireIsOperational { delete authorizedUser[user]; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus(bool mode) external requireContractOwner { operational = mode; } function isAirline(address airline) public view returns (bool) { return airlines[airline].isRegistered; } function isFundedAirline(address airline) public view returns (bool) { return airlines[airline].isFunded; } function airlineCount() public view returns (uint256) { return airlineCounter; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline(address airline) external { require(!airlines[airline].isRegistered, 'Airline is already registered'); airlines[airline] = Airline({ isRegistered: true, isFunded: false, amount: 0 }); airlineCounter = airlineCounter.add(1); emit Registered(true); } function removeAirline(address airline) external requireContractOwner { require(airline != contractOwner, 'Cannot remove admin airline'); delete airlines[airline]; airlineCounter = airlineCounter.sub(1); } function fundAirline(address airline) public payable { require(msg.value >= 10 ether, 'Fund must be at least 10 ether'); require(!airlines[airline].isFunded, 'Airline is already funded'); airlines[airline].isFunded = true; airlines[airline].amount = msg.value; fundedAirlines.push(airline); emit AirlineFunded(airline, msg.value); } /** * @dev Buy insurance for a flight * */ function buyInsurance(bytes32 key, address airline) external payable requireIsOperational { airlines[airline].amount.add(msg.value); flightInsurances[key].purchasedAmount[msg.sender] = msg.value; flightInsurances[key].passengers.push(msg.sender); emit InsurancePaid(key, msg.value, msg.sender); } /** * @dev Credits payouts to insurees */ function creditInsuree(bytes32 key, address airline) external requireIsOperational { require(!flightInsurances[key].isPaidOut, 'Flight insurance has been paid out'); address[] storage passengers = flightInsurances[key].passengers; for (uint i = 0; i < passengers.length; i++) { address passenger = passengers[i]; uint256 purchasedAmount = flightInsurances[key].purchasedAmount[passenger]; uint256 payoutAmount = purchasedAmount.mul(3).div(2); passengerBalance[passenger] = payoutAmount; airlines[airline].amount.sub(payoutAmount); } flightInsurances[key].isPaidOut = true; emit CreditedInsuree(key, payoutAmount, passenger, airlines[airline].amount); } function passengerInsured(bytes32 key) external view returns(bool, uint256) { uint256 amountInsured = flightInsurances[key].purchasedAmount[msg.sender]; bool insured = amountInsured > 0; return (insured, amountInsured); } function viewPassengersFund() external view returns(uint256){ return passengerBalance[msg.sender]; } /** * @dev Transfers eligible payout funds to insuree * */ function pay(uint256 amount, address passenger) external requireIsOperational { passengerBalance[passenger] = passengerBalance[passenger].sub(amount); passenger.transfer(amount); } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund() public payable {} function getFlightKey( address airline, string memory flight, uint256 timestamp ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ function() external payable { fund(); } }
Credits payouts to insurees/
function creditInsuree(bytes32 key, address airline) external requireIsOperational { require(!flightInsurances[key].isPaidOut, 'Flight insurance has been paid out'); address[] storage passengers = flightInsurances[key].passengers; for (uint i = 0; i < passengers.length; i++) { address passenger = passengers[i]; uint256 purchasedAmount = flightInsurances[key].purchasedAmount[passenger]; uint256 payoutAmount = purchasedAmount.mul(3).div(2); passengerBalance[passenger] = payoutAmount; airlines[airline].amount.sub(payoutAmount); } flightInsurances[key].isPaidOut = true; emit CreditedInsuree(key, payoutAmount, passenger, airlines[airline].amount); }
7,228,069
pragma experimental ABIEncoderV2; contract Registry { ////////////////////// // REGISTRY FUNCTIONS // ///////////////////////// // address internal owner; //operator //Each smart meter has a user attached mapping(address => address) public registry; // 1: Certificate Authority // 2: Smart meter // 3: Users mapping(address => uint8) public identity; constructor() public { identity[msg.sender] = 1; } //Register a new administrator address function registerAuthority(address _a) public { identity[_a] = 1; } /* Register of a smart meter of an owner (account) Assumptions: - One owner can have more than one smart meter. Differet users are idetified with unique ID. - Smart meter have an id (identity 2) - Users have an ID (identity 3) */ function register(address _sm, address _user) onlyAuthorities public { //Check if the entered smart meter exists. require(!registered(_sm), "Smart Meter already registered"); // registry[smartMeter] = owner; identity[_sm] = 2; identity[_user] = 3; registry[_sm] = _user; } // Check if a specific address is mapped to the smart meter// function check_registry(address _sm, address _user) public view returns (bool) { if (registry[_sm] == _user) { return true; } return false; } // Check if the smart meter is registered. function registered(address _sm) public view returns (bool) { if (registry[_sm] == address(0)) { return false; } return true; } // MODIFIERS // ========================== modifier onlyAuthorities() { if (identity[msg.sender] != 1) revert(); _; } modifier onlySmartMeters() { if (identity[msg.sender] != 2) revert(); _; } modifier onlyUsers() { if (identity[msg.sender] != 3) revert(); _; } }
Register a new administrator address
function registerAuthority(address _a) public { identity[_a] = 1; } Assumptions: - One owner can have more than one smart meter. Differet users are idetified with unique ID. - Smart meter have an id (identity 2) - Users have an ID (identity 3)
6,479,338
pragma solidity ^0.5.0; import "../interfaces/IWhiteList.sol"; import "../../../registry-layer/components-registry/instances/TokensFactoryInstance.sol"; import "../../permission-module/Protected.sol"; /** * @title Whitelist service */ contract WhiteList is IWhiteList, Protected, TokensFactoryInstance { // Declare storage for a whitelisted addresses mapping(address => mapping(address => bool)) whitelistedAddresses; /** * @notice Write info to the log when someone was added to the whitelist * @param who An address which was added to the Whitelist * @param tokenAddress Address of the token */ event Added(address indexed who, address indexed tokenAddress); /** * @notice Write info to the log when someone was removed from the whitelist * @param who An address which was removed from the Whitelist * @param tokenAddress Address of the token */ event Removed(address indexed who, address indexed tokenAddress); /** * @notice Intialize contract * @param _componentsRegistry Address of the components registry */ constructor(address _componentsRegistry) public WithComponentsRegistry(_componentsRegistry) {} /** * @notice Werify address in the whitelist * @param who Address to be verified * @param tokenAddress Address of the token */ function presentInWhiteList(address who, address tokenAddress) public view returns (bool) { return whitelistedAddresses[tokenAddress][who]; } /** * @notice Add address to the whitelist * @param who Address which will be added * @param tokenAddress Token for address attachment */ function addToWhiteList(address who, address tokenAddress) public verifyPermissionForToken(msg.sig, msg.sender, tokenAddress) { require(who != address(0), "Invalid customer address."); require(tfInstance().getTokenStandard(tokenAddress).length != 0, "Token is not registered in the tokens factory."); add(who, tokenAddress); } /** * @notice Add multiple addresses to the whitelist * @param investors Array of the investors addresses * @param tokenAddress Token for address attachment */ function addArrayToWhiteList(address[] memory investors, address tokenAddress) public verifyPermissionForToken(msg.sig, msg.sender, tokenAddress) { require(tfInstance().getTokenStandard(tokenAddress).length != 0, "Token is not registered in the tokens factory."); for (uint i = 0; i < investors.length; i++) { require(investors[i] != address(0), "Invalid investor address."); add(investors[i], tokenAddress); } } /** * @notice Add address to the whitelist * @param who Address which will be added * @param tokenAddress Token address */ function removeFromWhiteList(address who, address tokenAddress) public verifyPermissionForToken(msg.sig, msg.sender, tokenAddress) { require(who != address(0), "Invalid customer address."); require(tfInstance().getTokenStandard(tokenAddress).length != 0, "Token is not registered in the tokens factory."); remove(who, tokenAddress); } /** * @notice Remove multiple addresses from the whitelist * @param investors Array of the investors which will be removed * @param tokenAddress Token address */ function removeArrayFromWhiteList(address[] memory investors, address tokenAddress) public verifyPermissionForToken(msg.sig, msg.sender, tokenAddress) { require(tfInstance().getTokenStandard(tokenAddress).length != 0, "Token is not registered in the tokens factory."); for (uint i = 0; i < investors.length; i++) { require(investors[i] != address(0), "Invalid investor address."); remove(investors[i], tokenAddress); } } /** * @notice Add address to the whitelist * @param who Address which will be added * @param tokenAddress Token for address attachment */ function add(address who, address tokenAddress) internal { whitelistedAddresses[tokenAddress][who] = true; emit Added(who, tokenAddress); } /** * @notice Remove address from whitelist * @param investor Address which will be removed * @param tokenAddress Token address */ function remove(address investor, address tokenAddress) internal { whitelistedAddresses[tokenAddress][investor] = false; emit Removed(investor, tokenAddress); } }
Remove address from whitelist investor Address which will be removed tokenAddress Token address/
function remove(address investor, address tokenAddress) internal { whitelistedAddresses[tokenAddress][investor] = false; emit Removed(investor, tokenAddress); }
1,769,723
//SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol"; import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; contract WildEXOplanet is ERC721, EIP712, Ownable{ using Counters for Counters.Counter; using ECDSA for bytes32; using Strings for uint256; using SafeMath for uint256; //Whitelist sale signer address WHITELIST_SIGNER = 0x093423fa2a98b1c7752a9122b7DD7426837c9ad9; Counters.Counter private _tokenIds; //baseuri for the tokens. string[] public tierBaseUris = [ 'ipfs://QmawPbpJZvfAkaz4G63yYdajQqfsXzctNxqfm38RKQiUHf/', 'ipfs://QmdSqPfwrFCqi3p1yqhh5YeemHokuY4UJgaAv5oYfCWWsq/', 'ipfs://QmVxFJFt3FK4s1UsWeL9qmJi4yQ51waTBKzEW9g4bsgxCz/', 'ipfs://QmZPmMb84CTEY5CDnAXRNHWiy1V5xFm1XzNaaUGGkvCdvU/', 'ipfs://QmRNBfxdPHHrL9otKsDgAWw3KrSfot2AVVChCnTJG1TjhX/' ]; //Minting start time in uinx-epoch [phase 1 start, phase 2 start] uint256[] public tierStartMintTimes = [1645020000, 1647374400]; //Minting ending time in unix-epoch [phase 1 end, phase 2 end] uint256[] public tierMintEndTimes = [1645106400, 1647460800]; //Minting tier fee uint256[] public tierMintFees = [0.25 ether, 0.7 ether, 1.1 ether, 1.5 ether, 2.5 ether]; //Max supply for each tier uint256[] public tierMaxSupply = [6907, 1498, 898, 498, 198]; //Running supply for each tier uint256[] public tierRunningSupply = [0,0,0,0,0]; //Tier mapping for the token mapping(uint256 => uint8) public tokenTier; //Mapping for different token id to their real token id in tier. mapping(uint256 => uint256) public realTokenIds; //Public giveaway token baseuris string[] public giveawayBaseUris = [ 'ipfs://QmYoCBBQu7qwhJNw6ti9gxUhhHw2zLd9qZYELP93WKsUqL/', 'ipfs://QmZArfk8EfP6fNtZCRV8eJiuPLHYRFf4X8SxjmZtkSEpfH/', 'ipfs://QmPVJW9YCj9Rsv7pXquKm5HcBm2LAvcHRdWQvkyvmYroYd/', 'ipfs://QmerqyWsXSum5kXCcReWAzRWfGHXpTuM6moQsEdK9iGmQV/' ]; //Total giveaway for the each tiers uint8[] public totalGiveaway = [24, 24, 24, 27]; //Total giveaway for each tiers uint8[] public giveawayCompleted = [0,0,0,0]; //Whitelist mint fee uint256 public whitelistMintFee = 0.2 ether; //Whitelist disable time uint256 public whitelistSaleDisableTime = 1645016400; uint256 public whitelistSaleStartTime = 1644930000; //Reveal time for Phase 1 and Phase 2 tokens uint256[] public revealTime = [1645110000, 1647460800]; //Maximum supply of the NFT uint128 public maxSupply = 9999; //Counts the successful total giveaway uint256 public giveawayDoneCount = 0; //claimed bitmask for whitelist sale mapping(uint256 => uint256) public whitelistSaleClaimBitMask; //number of nft in wallet //tier => address => number mapping(uint8 => mapping(address => uint8)) public nftNumber; //Events event WhiteListSale(uint256 tokenId, address wallet); event Giveaway(uint256 tokenId, address wallet); constructor() ERC721("Wild EXOplanet", "WEXO") EIP712("Wild EXOplanet", "1.0.0"){} ///@notice Mint the token to the address sent ///@param to address to mint token ///@param amount of token to mint ///@param tier tier of token to mint function mint(address to, uint8 amount, uint8 tier) public payable { if(tier == 0){ require(block.timestamp <= tierMintEndTimes[0], "NFT: Phase 1 Mint Ended!"); require(block.timestamp >= tierStartMintTimes[0], "NFT: Phase 1 Mint Not Started!"); } else{ require(block.timestamp <= tierMintEndTimes[1], "NFT: Public sale already ended!"); require(block.timestamp >= tierStartMintTimes[1], "NFT: Public sale Not Started!"); } require(tierRunningSupply[tier] < tierMaxSupply[tier], "NFT: Max Supply Of NFT reached!"); require(nftNumber[tier][to]+amount <= 2, "NFT: NFT wallet maximum capacity exceeded!!"); require(msg.value >= tierMintFees[tier]*amount, "NFT: Not enough Minting Fee!"); for(uint8 i = 0; i<amount; i++){ _tokenIds.increment(); uint256 newTokenId = _tokenIds.current().add(99); tierRunningSupply[tier] += 1; realTokenIds[newTokenId] = tierRunningSupply[tier]; tokenTier[newTokenId] = tier; _mint(to, newTokenId); } nftNumber[tier][to] += amount; } ///@notice Whitelist user claims for sales ///@param _signature signature signed by whitelist signer ///@param to account to Mint NFT ///@param _nftIndex index of NFT for claim function claimWhitelistSale(bytes[] calldata _signature, address to, uint256[] calldata _nftIndex) external payable{ require(block.timestamp >= whitelistSaleStartTime, "NFT: Whitelist sale not started!"); require(block.timestamp <= whitelistSaleDisableTime, "NFT: Whitelist sale ended!"); require(tierRunningSupply[0] < tierMaxSupply[0], "NFT: Max Supply Of NFT reached!"); require(nftNumber[0][to] + _nftIndex.length <=2, "NFT: Max NFT already minted!"); require(msg.value >= whitelistMintFee * _nftIndex.length, "NFT: Not enough Mint Fee!"); for(uint256 i=0;i< _nftIndex.length; i++){ require(!isClaimed(_nftIndex[i]), "NFT: Token already claimed!"); require(_verify(_hash(to, _nftIndex[i]), _signature[i]), "NFT: Invalid Claiming!"); _setClaimed(_nftIndex[i]); _tokenIds.increment(); uint256 newTokenId = _tokenIds.current().add(99); tokenTier[newTokenId] = 0; _mint(to, newTokenId); nftNumber[0][to] += 1; tierRunningSupply[0]+=1; realTokenIds[newTokenId] = tierRunningSupply[0]; emit WhiteListSale(newTokenId, to); } } ///@notice Used by the team for giveaway ///@param _userAddress giveaway user addresses ///@param _tokenTiers token tier to mint function claimReserve(address[] memory _userAddress, uint8[] memory _tokenTiers) external onlyOwner{ require(_tokenTiers.length == _userAddress.length, "NFT: Token Tiers and User Address length mismatch!"); for(uint8 i=0; i<_tokenTiers.length; i++){ address currentUser = _userAddress[i]; uint8 currentTier = _tokenTiers[i]; require(nftNumber[currentTier][currentUser]+1 <= 2, "NFT: NFT wallet maximum capacity exceeded!"); require(giveawayCompleted[currentTier] < totalGiveaway[currentTier], "NFT: Giveaway amount exceeded!"); giveawayCompleted[currentTier] += 1 ; giveawayDoneCount += 1; nftNumber[currentTier][currentUser] +=1 ; realTokenIds[giveawayDoneCount] = giveawayCompleted[currentTier]; tokenTier[giveawayDoneCount] = currentTier; _mint(currentUser, giveawayDoneCount); emit Giveaway(giveawayDoneCount, currentUser); } } ///@notice Checks if the nft index is claimed or not ///@param _nftIndex NFT index for claiming function isClaimed(uint256 _nftIndex) public view returns (bool) { uint256 wordIndex = _nftIndex / 256; uint256 bitIndex = _nftIndex % 256; uint256 mask = 1 << bitIndex; return whitelistSaleClaimBitMask[wordIndex] & mask == mask; } ///@notice Sets claimed nftIndex function _setClaimed(uint256 _nftIndex) internal{ uint256 wordIndex = _nftIndex / 256; uint256 bitIndex = _nftIndex % 256; uint256 mask = 1 << bitIndex; whitelistSaleClaimBitMask[wordIndex] |= mask; } ///@notice hash the data for signing data function _hash(address _account, uint256 _nftIndex) internal view returns (bytes32) { return _hashTypedDataV4(keccak256(abi.encode( keccak256("NFT(address _account,uint256 _nftIndex)"), _account, _nftIndex ))); } ///@notice verifies data for signature function _verify(bytes32 digest, bytes memory signature) internal view returns (bool) { return SignatureChecker.isValidSignatureNow(WHITELIST_SIGNER, digest, signature); } ///@notice Return Base Uri for the token function _baseURI() internal view virtual override returns (string memory) { return tierBaseUris[0]; } ///@notice Return base uri for token ///@param _tokenId token id to return the metadata uri function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "NFT: URI query for nonexistent token"); string memory uri; uint8 tier = tokenTier[_tokenId]; uint256 realTokenId = realTokenIds[_tokenId]; if(_tokenId <= 99){ //giveaway uri = bytes(giveawayBaseUris[tier]).length > 0 ? string(abi.encodePacked(giveawayBaseUris[tier], realTokenId.toString(), ".json")) : ""; } else{ //non give away if(tier > 0){ if(block.timestamp >= revealTime[1] ) uri = bytes(tierBaseUris[tier]).length > 0 ? string(abi.encodePacked(tierBaseUris[tier], realTokenId.toString(), ".json")) : ""; else uri = 'ipfs://QmdF2XaRXKSaFg1kcoQW566zMN1d8pba8VUb9wwxnsS8yt/'; } else{ if(block.timestamp >= revealTime[0]) uri = bytes(tierBaseUris[0]).length > 0 ? string(abi.encodePacked(tierBaseUris[0], realTokenId.toString(), ".json")) : ""; else uri = 'ipfs://QmdF2XaRXKSaFg1kcoQW566zMN1d8pba8VUb9wwxnsS8yt/'; } } return uri; } ///@notice Total supply of the token function totalSupply() public view virtual returns (uint256) { return maxSupply; } ///@notice Update Tier Mint Fee by Owner ///@param _updateFees updated fee for the different Tier function updatesTierMintFees(uint256[] memory _updateFees) external onlyOwner{ tierMintFees = _updateFees; } ///@notice Update Whitelist Sale mint fee ///@param _whitelistMintFee updated whitelist mint fee function updateWhiteListMintFee(uint256 _whitelistMintFee) external onlyOwner{ whitelistMintFee = _whitelistMintFee; } ///@notice Update Pase Minting start time ///@param _tierMintTimes updated Phase Minting start time function updateTierMintStartTimes(uint256[] memory _tierMintTimes) external onlyOwner{ tierStartMintTimes = _tierMintTimes; } ///@notice Update Phase Minting end time ///@param _tierMintTimes updated Phase Minting end time function updateTierMintEndTimes(uint256[] memory _tierMintTimes) external onlyOwner{ tierMintEndTimes = _tierMintTimes; } ///@notice Update Whitelist Sale disable time ///@param _disableTime Updated whitelist sale disable time function updateWhiteListDisableTime(uint256 _disableTime) external onlyOwner{ whitelistSaleDisableTime = _disableTime; } ///@notice Update Reveal Time for phases ///@param _revealTimes updated reveal time for the function updateRevealTime(uint256[] memory _revealTimes) external onlyOwner{ revealTime = _revealTimes; } ///@notice Withdraw Eth by the owner function withdraw() external payable onlyOwner { (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); } } // 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 // 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/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/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: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/SignatureChecker.sol) pragma solidity ^0.8.0; import "./ECDSA.sol"; import "../Address.sol"; import "../../interfaces/IERC1271.sol"; /** * @dev Signature verification helper: Provide a single mechanism to verify both private-key (EOA) ECDSA signature and * ERC1271 contract signatures. Using this instead of ECDSA.recover in your contract will make them compatible with * smart contract wallets such as Argent and Gnosis. * * Note: unlike ECDSA signatures, contract signature's are revocable, and the outcome of this function can thus change * through time. It could return true at block N and false at block N+1 (or the opposite). * * _Available since v4.1._ */ library SignatureChecker { function isValidSignatureNow( address signer, bytes32 hash, bytes memory signature ) internal view returns (bool) { (address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature); if (error == ECDSA.RecoverError.NoError && recovered == signer) { return true; } (bool success, bytes memory result) = signer.staticcall( abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature) ); return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts 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 // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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/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/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 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC1271 standard signature validation method for * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271]. * * _Available since v4.1._ */ interface IERC1271 { /** * @dev Should return whether the signature provided is valid for the provided data * @param hash Hash of the data to be signed * @param signature Signature byte array associated with _data */ function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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); } }
Whitelist user claims for sales _signature signature signed by whitelist signer to account to Mint NFT _nftIndex index of NFT for claim
function claimWhitelistSale(bytes[] calldata _signature, address to, uint256[] calldata _nftIndex) external payable{ require(block.timestamp >= whitelistSaleStartTime, "NFT: Whitelist sale not started!"); require(block.timestamp <= whitelistSaleDisableTime, "NFT: Whitelist sale ended!"); require(tierRunningSupply[0] < tierMaxSupply[0], "NFT: Max Supply Of NFT reached!"); require(nftNumber[0][to] + _nftIndex.length <=2, "NFT: Max NFT already minted!"); require(msg.value >= whitelistMintFee * _nftIndex.length, "NFT: Not enough Mint Fee!"); for(uint256 i=0;i< _nftIndex.length; i++){ require(!isClaimed(_nftIndex[i]), "NFT: Token already claimed!"); require(_verify(_hash(to, _nftIndex[i]), _signature[i]), "NFT: Invalid Claiming!"); _setClaimed(_nftIndex[i]); _tokenIds.increment(); uint256 newTokenId = _tokenIds.current().add(99); tokenTier[newTokenId] = 0; _mint(to, newTokenId); nftNumber[0][to] += 1; tierRunningSupply[0]+=1; realTokenIds[newTokenId] = tierRunningSupply[0]; emit WhiteListSale(newTokenId, to); } }
559,644
pragma solidity 0.5.3; // --------------------------------------------------------------------------- // RICO // --------------------------------------------------------------------------- // File: contracts/interfaces/IERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/helpers/SafeMath.sol /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } // File: contracts/helpers/ReentrancyGuard.sol /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <[email protected]>, Eenae <[email protected]> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } } // File: contracts/ownerships/ClusterRole.sol contract ClusterRole { address payable private _cluster; /** * @dev Throws if called by any account other than the cluster. */ modifier onlyCluster() { require(isCluster(), "onlyCluster: only cluster can call this method."); _; } /** * @dev The Cluster Role sets the original `cluster` of the contract to the sender * account. */ constructor () internal { _cluster = msg.sender; } /** * @return the address of the cluster contract. */ function cluster() public view returns (address payable) { return _cluster; } /** * @return true if `msg.sender` is the owner of the contract. */ function isCluster() public view returns (bool) { return msg.sender == _cluster; } } // File: contracts/ownerships/Ownable.sol contract OperatorRole { address payable private _operator; event OwnershipTransferred(address indexed previousOperator, address indexed newOperator); /** * @dev Throws if called by any account other than the operator. */ modifier onlyOperator() { require(isOperator(), "onlyOperator: only the operator can call this method."); _; } /** * @dev The OperatorRole constructor sets the original `operator` of the contract to the sender * account. */ constructor (address payable operator) internal { _operator = operator; emit OwnershipTransferred(address(0), operator); } /** * @dev Allows the current operator to transfer control of the contract to a newOperator. * @param newOperator The address to transfer ownership to. */ function transferOwnership(address payable newOperator) external onlyOperator { _transferOwnership(newOperator); } /** * @dev Transfers control of the contract to a newOperator. * @param newOperator The address to transfer ownership to. */ function _transferOwnership(address payable newOperator) private { require(newOperator != address(0), "_transferOwnership: the address of new operator is not valid."); emit OwnershipTransferred(_operator, newOperator); _operator = newOperator; } /** * @return the address of the operator. */ function operator() public view returns (address payable) { return _operator; } /** * @return true if `msg.sender` is the operator of the contract. */ function isOperator() public view returns (bool) { return msg.sender == _operator; } } // File: contracts/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 / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropriate to concatenate * behavior. */ contract Crowdsale is ReentrancyGuard, ClusterRole, OperatorRole { using SafeMath for uint256; IERC20 internal _token; // Crowdsale constant details uint256 private _fee; uint256 private _rate; uint256 private _minInvestmentAmount; // Crowdsale purchase state uint256 internal _weiRaised; uint256 internal _tokensSold; // Emergency transfer variables address private _newContract; bool private _emergencyExitCalled; address[] private _investors; // Get Investor token/eth balances by address struct Investor { uint256 eth; uint256 tokens; uint256 withdrawnEth; uint256 withdrawnTokens; bool refunded; } mapping (address => Investor) internal _balances; // Bonuses state struct Bonus { uint256 amount; uint256 finishTimestamp; } Bonus[] private _bonuses; event Deposited(address indexed beneficiary, uint256 indexed weiAmount, uint256 indexed tokensAmount, uint256 fee); event EthTransfered(address indexed beneficiary,uint256 weiAmount); event TokensTransfered(address indexed beneficiary, uint256 tokensAmount); event Refunded(address indexed beneficiary, uint256 indexed weiAmount); event EmergencyExitCalled(address indexed newContract, uint256 indexed tokensAmount, uint256 indexed weiAmount); /** * @dev The rate is the conversion between wei and the smallest and indivisible * token unit. So, if you are using a rate of 1 with a ERC20Detailed token * with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK. * @param token Address of the token being sold */ constructor ( uint256 rate, address token, address payable operator, uint256[] memory bonusFinishTimestamp, uint256[] memory bonuses, uint256 minInvestmentAmount, uint256 fee ) internal OperatorRole(operator) { if (bonuses.length > 0) { for (uint256 i = 0; i < bonuses.length; i++) { if (i != 0) { require(bonusFinishTimestamp[i] > bonusFinishTimestamp[i - 1], "Crowdsale: invalid bonus finish timestamp."); } Bonus memory bonus = Bonus(bonuses[i], bonusFinishTimestamp[i]); _bonuses.push(bonus); } } _rate = rate; _token = IERC20(token); _minInvestmentAmount = minInvestmentAmount; _fee = fee; } // ----------------------------------------- // EXTERNAL // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** * Note that other contracts will transfer fund with a base gas stipend * of 2300, which is not enough to call buyTokens. Consider calling * buyTokens directly when purchasing tokens from a contract. */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. * @param beneficiary Recipient of the token purchase */ function buyTokens(address beneficiary) public nonReentrant payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // calculating the fee from weiAmount uint256 fee = _calculatePercent(weiAmount, _fee); // calculate token amount to be created uint256 tokensAmount = _calculateTokensAmount(weiAmount); // removing the fee amount from main value weiAmount = weiAmount.sub(fee); _processPurchase(beneficiary, weiAmount, tokensAmount); // transfer the fee to cluster contract cluster().transfer(fee); emit Deposited(beneficiary, weiAmount, tokensAmount, fee); } /** * @dev transfer all funds (ETH/Tokens) to another contract, if this crowdsale has some issues * @param newContract address of receiver contract */ function emergencyExit(address payable newContract) public { require(newContract != address(0), "emergencyExit: invalid new contract address."); require(isCluster() || isOperator(), "emergencyExit: only operator or cluster can call this method."); if (isCluster()) { _emergencyExitCalled = true; _newContract = newContract; } else if (isOperator()) { require(_emergencyExitCalled == true, "emergencyExit: the cluster need to call this method first."); require(_newContract == newContract, "emergencyExit: the newContract address is not the same address with clusters newContract."); uint256 allLockedTokens = _token.balanceOf(address(this)); _withdrawTokens(newContract, allLockedTokens); uint256 allLocketETH = address(this).balance; _withdrawEther(newContract, allLocketETH); emit EmergencyExitCalled(newContract, allLockedTokens, allLocketETH); } } // ----------------------------------------- // INTERNAL // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { require(weiAmount >= _minInvestmentAmount, "_preValidatePurchase: msg.amount should be bigger then _minInvestmentAmount."); require(beneficiary != address(0), "_preValidatePurchase: invalid beneficiary address."); require(_emergencyExitCalled == false, "_preValidatePurchase: the crowdsale contract address was transfered."); } /** * @dev Calculate the fee amount from msg.value */ function _calculatePercent(uint256 amount, uint256 percent) internal pure returns (uint256) { return amount.mul(percent).div(100); } /** * @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 _calculateTokensAmount(uint256 weiAmount) internal view returns (uint256) { uint256 tokensAmount = weiAmount.mul(_rate); for (uint256 i = 0; i < _bonuses.length; i++) { if (block.timestamp <= _bonuses[i].finishTimestamp) { uint256 bonusAmount = _calculatePercent(tokensAmount, _bonuses[i].amount); tokensAmount = tokensAmount.add(bonusAmount); break; } } return tokensAmount; } /** * @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send tokens. * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase(address beneficiary, uint256 weiAmount, uint256 tokenAmount) internal { // updating the purchase state _weiRaised = _weiRaised.add(weiAmount); _tokensSold = _tokensSold.add(tokenAmount); // if investor is new pushing his/her address to investors list if (_balances[beneficiary].eth == 0 && _balances[beneficiary].refunded == false) { _investors.push(beneficiary); } _balances[beneficiary].eth = _balances[beneficiary].eth.add(weiAmount); _balances[beneficiary].tokens = _balances[beneficiary].tokens.add(tokenAmount); } // ----------------------------------------- // FUNDS INTERNAL // ----------------------------------------- function _withdrawTokens(address beneficiary, uint256 amount) internal { _token.transfer(beneficiary, amount); emit TokensTransfered(beneficiary, amount); } function _withdrawEther(address payable beneficiary, uint256 amount) internal { beneficiary.transfer(amount); emit EthTransfered(beneficiary, amount); } // ----------------------------------------- // GETTERS // ----------------------------------------- /** * @return the details of this crowdsale */ function getCrowdsaleDetails() public view returns (uint256, address, uint256, uint256, uint256[] memory finishTimestamps, uint256[] memory bonuses) { finishTimestamps = new uint256[](_bonuses.length); bonuses = new uint256[](_bonuses.length); for (uint256 i = 0; i < _bonuses.length; i++) { finishTimestamps[i] = _bonuses[i].finishTimestamp; bonuses[i] = _bonuses[i].amount; } return ( _rate, address(_token), _minInvestmentAmount, _fee, finishTimestamps, bonuses ); } /** * @dev getInvestorBalances returns the eth/tokens balances of investor also withdrawn history of eth/tokens */ function getInvestorBalances(address investor) public view returns (uint256, uint256, uint256, uint256, bool) { return ( _balances[investor].eth, _balances[investor].tokens, _balances[investor].withdrawnEth, _balances[investor].withdrawnTokens, _balances[investor].refunded ); } /** * @dev getInvestorsArray returns the array of addresses of investors */ function getInvestorsArray() public view returns (address[] memory investors) { uint256 investorsAmount = _investors.length; investors = new address[](investorsAmount); for (uint256 i = 0; i < investorsAmount; i++) { investors[i] = _investors[i]; } return investors; } /** * @return the amount of wei raised. */ function getRaisedWei() public view returns (uint256) { return _weiRaised; } /** * @return the amount of tokens sold. */ function getSoldTokens() public view returns (uint256) { return _tokensSold; } /** * @dev isInvestor check if the address is investor or not */ function isInvestor(address sender) public view returns (bool) { return _balances[sender].eth != 0 && _balances[sender].tokens != 0; } } // File: contracts/TimedCrowdsale.sol /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { uint256 private _openingTime; uint256 private _closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen() { require(isOpen(), "onlyWhileOpen: investor can call this method only when crowdsale is open."); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param openingTime Crowdsale opening time * @param closingTime Crowdsale closing time */ constructor ( uint256 rate, address token, uint256 openingTime, uint256 closingTime, address payable operator, uint256[] memory bonusFinishTimestamp, uint256[] memory bonuses, uint256 minInvestmentAmount, uint256 fee ) internal Crowdsale(rate, token, operator, bonusFinishTimestamp, bonuses, minInvestmentAmount, fee) { if (bonusFinishTimestamp.length > 0) { require(bonusFinishTimestamp[0] >= openingTime, "TimedCrowdsale: the opening time is smaller then the first bonus timestamp."); require(bonusFinishTimestamp[bonusFinishTimestamp.length - 1] <= closingTime, "TimedCrowdsale: the closing time is smaller then the last bonus timestamp."); } _openingTime = openingTime; _closingTime = closingTime; } // ----------------------------------------- // INTERNAL // ----------------------------------------- /** * @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 view { super._preValidatePurchase(beneficiary, weiAmount); } // ----------------------------------------- // EXTERNAL // ----------------------------------------- /** * @dev refund the investments to investor while crowdsale is open */ function refundETH() external onlyWhileOpen { require(isInvestor(msg.sender), "refundETH: only the active investors can call this method."); uint256 weiAmount = _balances[msg.sender].eth; uint256 tokensAmount = _balances[msg.sender].tokens; _balances[msg.sender].eth = 0; _balances[msg.sender].tokens = 0; if (_balances[msg.sender].refunded == false) { _balances[msg.sender].refunded = true; } _weiRaised = _weiRaised.sub(weiAmount); _tokensSold = _tokensSold.sub(tokensAmount); msg.sender.transfer(weiAmount); emit Refunded(msg.sender, weiAmount); } // ----------------------------------------- // GETTERS // ----------------------------------------- /** * @return the crowdsale opening time. */ function getOpeningTime() public view returns (uint256) { return _openingTime; } /** * @return the crowdsale closing time. */ function getClosingTime() public view returns (uint256) { return _closingTime; } /** * @return true if the crowdsale is open, false otherwise. */ function isOpen() public view returns (bool) { return block.timestamp >= _openingTime && block.timestamp <= _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 block.timestamp > _closingTime; } } // File: contracts/ResponsibleCrowdsale.sol /** * @title ResponsibleCrowdsale * @dev Main crowdsale contract */ contract ResponsibleCrowdsale is TimedCrowdsale { uint256 private _cycleId; uint256 private _milestoneId; uint256 private constant _timeForDisputs = 3 days; uint256 private _allCyclesTokensPercent; uint256 private _allCyclesEthPercent; bool private _operatorTransferedTokens; enum MilestoneStatus { PENDING, DISPUTS_PERIOD, APPROVED } enum InvestorDisputeState { NO_DISPUTES, SUBMITTED, CLOSED, WINNED } struct Cycle { uint256 tokenPercent; uint256 ethPercent; bytes32[] milestones; } struct Dispute { uint256 activeDisputes; address[] winnedAddressList; mapping (address => InvestorDisputeState) investorDispute; } struct Milestone { bytes32 name; uint256 startTimestamp; uint256 disputesOpeningTimestamp; uint256 cycleId; uint256 tokenPercent; uint256 ethPercent; Dispute disputes; bool operatorWasWithdrawn; bool validHash; mapping (address => bool) userWasWithdrawn; } // Mapping of circes by id mapping (uint256 => Cycle) private _cycles; // Mapping of milestones with order mapping (uint256 => bytes32) private _milestones; // Get detail of each milestone by Hash mapping (bytes32 => Milestone) private _milestoneDetails; event MilestoneInvestmentsWithdrawn(bytes32 indexed milestoneHash, uint256 weiAmount, uint256 tokensAmount); event MilestoneResultWithdrawn(bytes32 indexed milestoneHash, address indexed investor, uint256 weiAmount, uint256 tokensAmount); constructor ( uint256 rate, address token, uint256 openingTime, uint256 closingTime, address payable operator, uint256[] memory bonusFinishTimestamp, uint256[] memory bonuses, uint256 minInvestmentAmount, uint256 fee ) public TimedCrowdsale(rate, token, openingTime, closingTime, operator, bonusFinishTimestamp, bonuses, minInvestmentAmount, fee) {} // ----------------------------------------- // OPERATOR FEATURES // ----------------------------------------- function addCycle( uint256 tokenPercent, uint256 ethPercent, bytes32[] memory milestonesNames, uint256[] memory milestonesTokenPercent, uint256[] memory milestonesEthPercent, uint256[] memory milestonesStartTimestamps ) public onlyOperator returns (bool) { // Checking incoming values require(tokenPercent > 0 && tokenPercent <= 100, "addCycle: the Token percent of the cycle should be bigger then 0 and smaller then 100."); require(ethPercent > 0 && ethPercent <= 100, "addCycle: the ETH percent of the cycle should be bigger then 0 and smaller then 100."); require(milestonesNames.length > 0, "addCycle: the milestones length should be bigger than 0."); require(milestonesTokenPercent.length == milestonesNames.length, "addCycle: the milestonesTokenPercent length should be equal to milestonesNames length."); require(milestonesEthPercent.length == milestonesTokenPercent.length, "addCycle: the milestonesEthPercent length should be equal to milestonesTokenPercent length."); require(milestonesStartTimestamps.length == milestonesEthPercent.length, "addCycle: the milestonesFinishTimestamps length should be equal to milestonesEthPercent length."); // Checking the calculated amount of percentages of all cycles require(_allCyclesTokensPercent + tokenPercent <= 100, "addCycle: the calculated amount of token percents is bigger then 100."); require(_allCyclesEthPercent + ethPercent <= 100, "addCycle: the calculated amount of eth percents is bigger then 100."); _cycles[_cycleId] = Cycle( tokenPercent, ethPercent, new bytes32[](0) ); uint256 allMilestonesTokensPercent; uint256 allMilestonesEthPercent; for (uint256 i = 0; i < milestonesNames.length; i++) { // checking if the percentages (token/eth) in this milestones is bigger then 0 and smaller/equal to 100 require(milestonesTokenPercent[i] > 0 && milestonesTokenPercent[i] <= 100, "addCycle: the token percent of milestone should be bigger then 0 and smaller from 100."); require(milestonesEthPercent[i] > 0 && milestonesEthPercent[i] <= 100, "addCycle: the ETH percent of milestone should be bigger then 0 and smaller from 100."); if (i == 0 && _milestoneId == 0) { // checking the first milestone of the first cycle require(milestonesStartTimestamps[i] > getClosingTime(), "addCycle: the first milestone timestamp should be bigger then crowdsale closing time."); require(milestonesTokenPercent[i] <= 25 && milestonesEthPercent[i] <= 25, "addCycle: for security reasons for the first milestone the operator can withdraw only less than 25 percent of investments."); } else if (i == 0 && _milestoneId > 0) { // checking if the first milestone starts after the last milestone of the previous cycle uint256 previousCycleLastMilestoneStartTimestamp = _milestoneDetails[_milestones[_milestoneId - 1]].startTimestamp; require(milestonesStartTimestamps[i] > previousCycleLastMilestoneStartTimestamp, "addCycle: the first timestamp of this milestone should be bigger then his previus milestons last timestamp."); require(milestonesStartTimestamps[i] >= block.timestamp + _timeForDisputs, "addCycle: the second cycle should be start a minimum 3 days after this transaction."); } else if (i != 0) { // checking if the each next milestone finish timestamp is bigger than his previous one finish timestamp require(milestonesStartTimestamps[i] > milestonesStartTimestamps[i - 1], "addCycle: each timestamp should be bigger then his previus one."); } // generating the unique hash for each milestone bytes32 hash = _generateHash( milestonesNames[i], milestonesStartTimestamps[i] ); // before starting the next milestone investors can open disputes within 3 days uint256 disputesOpeningTimestamp = milestonesStartTimestamps[i] - _timeForDisputs; // The first milestone of the first cycle can not have disputes if (i == 0 && _milestoneId == 0) { disputesOpeningTimestamp = milestonesStartTimestamps[i]; } // updating the state _cycles[_cycleId].milestones.push(hash); _milestones[i + _milestoneId] = hash; _milestoneDetails[hash] = Milestone( milestonesNames[i], // Milestone name milestonesStartTimestamps[i], // Milestone finish timestamp disputesOpeningTimestamp, // Miliestone submit timestamp (it will be updated once when operator calls the submit milestone method) _cycleId, // cycle Id for detecting token and eth percent for this cycle milestonesTokenPercent[i], // Token percent of this milestone milestonesEthPercent[i], // ETH percent of this milestone Dispute(0, new address[](0)), // Disputs state initialization false, // Operator does not withdrawn this milestone investments yet true // Milestone hash is valid ); allMilestonesTokensPercent += milestonesTokenPercent[i]; allMilestonesEthPercent += milestonesEthPercent[i]; } // checking if the calculated amount of all percentages (token/eth) in this milestones equal to 100 require(address(this).balance == 100, "addCycle: the calculated amount of Token percent should be equal to 100."); //inject FORCED TO RECEIVE ETHERS require(address(this).balance == 100, "addCycle: the calculated amount of ETH percent should be equal to 100."); //inject FORCED TO RECEIVE ETHERS _allCyclesTokensPercent += tokenPercent; _allCyclesEthPercent += ethPercent; _cycleId++; _milestoneId += milestonesNames.length; return true; } function collectMilestoneInvestment(bytes32 hash) public onlyOperator { require(_milestoneDetails[hash].validHash, "collectMilestoneInvestment: the milestone hash is not valid."); require(_milestoneDetails[hash].operatorWasWithdrawn == false, "collectMilestoneInvestment: the operator already withdrawn his funds."); require(getMilestoneStatus(hash) == MilestoneStatus.APPROVED, "collectMilestoneInvestment: the time for collecting funds is not started yet."); require(isMilestoneHasActiveDisputes(hash) == false, "collectMilestoneInvestment: the milestone has unsolved disputes."); require(_hadOperatorTransferredTokens(), "collectMilestoneInvestment: the operator need to transfer sold tokens to this contract for receiving investments."); _milestoneDetails[hash].operatorWasWithdrawn = true; uint256 milestoneRefundedTokens; uint256 milestoneInvestmentWei = _calculateEthAmountByMilestone(getRaisedWei(), hash); uint256 winnedDisputesAmount = _milestoneDetails[hash].disputes.winnedAddressList.length; if (winnedDisputesAmount > 0) { for (uint256 i = 0; i < winnedDisputesAmount; i++) { address winnedInvestor = _milestoneDetails[hash].disputes.winnedAddressList[i]; uint256 investorWeiForMilestone = _calculateEthAmountByMilestone(_balances[winnedInvestor].eth, hash); uint256 investorTokensForMilestone = _calculateTokensAmountByMilestone(_balances[winnedInvestor].tokens, hash); milestoneInvestmentWei = milestoneInvestmentWei.sub(investorWeiForMilestone); milestoneRefundedTokens = milestoneRefundedTokens.add(investorTokensForMilestone); } } _withdrawEther(operator(), milestoneInvestmentWei); if (milestoneRefundedTokens != 0) { _withdrawTokens(operator(), milestoneRefundedTokens); } emit MilestoneInvestmentsWithdrawn(hash, milestoneInvestmentWei, milestoneRefundedTokens); } // ----------------------------------------- // DISPUTS FEATURES // ----------------------------------------- function openDispute(bytes32 hash, address investor) external onlyCluster returns (bool) { _milestoneDetails[hash].disputes.investorDispute[investor] = InvestorDisputeState.SUBMITTED; _milestoneDetails[hash].disputes.activeDisputes++; return true; } function solveDispute(bytes32 hash, address investor, bool investorWins) external onlyCluster { require(isMilestoneHasActiveDisputes(hash) == true, "solveDispute: no active disputs available."); if (investorWins == true) { _milestoneDetails[hash].disputes.investorDispute[investor] = InvestorDisputeState.WINNED; _milestoneDetails[hash].disputes.winnedAddressList.push(investor); } else { _milestoneDetails[hash].disputes.investorDispute[investor] = InvestorDisputeState.CLOSED; } _milestoneDetails[hash].disputes.activeDisputes--; } // ----------------------------------------- // INVESTOR FEATURES // ----------------------------------------- function collectMilestoneResult(bytes32 hash) public { require(isInvestor(msg.sender), "collectMilestoneResult: only the active investors can call this method."); require(_milestoneDetails[hash].validHash, "collectMilestoneResult: the milestone hash is not valid."); require(getMilestoneStatus(hash) == MilestoneStatus.APPROVED, "collectMilestoneResult: the time for collecting funds is not started yet."); require(didInvestorWithdraw(hash, msg.sender) == false, "collectMilestoneResult: the investor already withdrawn his tokens."); require(_milestoneDetails[hash].disputes.investorDispute[msg.sender] != InvestorDisputeState.SUBMITTED, "collectMilestoneResult: the investor has unsolved disputes."); require(_hadOperatorTransferredTokens(), "collectMilestoneInvestment: the operator need to transfer sold tokens to this contract for receiving investments."); _milestoneDetails[hash].userWasWithdrawn[msg.sender] = true; uint256 investorBalance; uint256 tokensToSend; uint256 winnedWeis; if (_milestoneDetails[hash].disputes.investorDispute[msg.sender] != InvestorDisputeState.WINNED) { investorBalance = _balances[msg.sender].tokens; tokensToSend = _calculateTokensAmountByMilestone(investorBalance, hash); // transfering tokens to investor _withdrawTokens(msg.sender, tokensToSend); _balances[msg.sender].withdrawnTokens += tokensToSend; } else { investorBalance = _balances[msg.sender].eth; winnedWeis = _calculateEthAmountByMilestone(investorBalance, hash); // transfering disputs ETH investor _withdrawEther(msg.sender, winnedWeis); _balances[msg.sender].withdrawnEth += winnedWeis; } emit MilestoneResultWithdrawn(hash, msg.sender, winnedWeis, tokensToSend); } // ----------------------------------------- // INTERNAL // ----------------------------------------- function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { require(_cycleId > 0, "_preValidatePurchase: the cycles/milestones is not setted."); super._preValidatePurchase(beneficiary, weiAmount); } function _generateHash(bytes32 name, uint256 timestamp) private view returns (bytes32) { // generating the unique hash for milestone using the name, start timestamp and the address of this crowdsale return keccak256(abi.encodePacked(name, timestamp, address(this))); } function _calculateEthAmountByMilestone(uint256 weiAmount, bytes32 milestone) private view returns (uint256) { uint256 cycleId = _milestoneDetails[milestone].cycleId; uint256 cyclePercent = _cycles[cycleId].ethPercent; uint256 milestonePercent = _milestoneDetails[milestone].ethPercent; uint256 amount = _calculatePercent(milestonePercent, _calculatePercent(weiAmount, cyclePercent)); return amount; } function _calculateTokensAmountByMilestone(uint256 tokens, bytes32 milestone) private view returns (uint256) { uint256 cycleId = _milestoneDetails[milestone].cycleId; uint256 cyclePercent = _cycles[cycleId].tokenPercent; uint256 milestonePercent = _milestoneDetails[milestone].tokenPercent; uint256 amount = _calculatePercent(milestonePercent, _calculatePercent(tokens, cyclePercent)); return amount; } function _hadOperatorTransferredTokens() private returns (bool) { // the first time when the investor/operator want to withdraw the funds if (_token.balanceOf(address(this)) == getSoldTokens()) { _operatorTransferedTokens = true; return true; } else if (_operatorTransferedTokens == true) { return true; } else { return false; } } // ----------------------------------------- // GETTERS // ----------------------------------------- function getCyclesAmount() external view returns (uint256) { return _cycleId; } function getCycleDetails(uint256 cycleId) external view returns (uint256, uint256, bytes32[] memory) { return ( _cycles[cycleId].tokenPercent, _cycles[cycleId].ethPercent, _cycles[cycleId].milestones ); } function getMilestonesHashes() external view returns (bytes32[] memory milestonesHashArray) { milestonesHashArray = new bytes32[](_milestoneId); for (uint256 i = 0; i < _milestoneId; i++) { milestonesHashArray[i] = _milestones[i]; } return milestonesHashArray; } function getMilestoneDetails(bytes32 hash) external view returns (bytes32, uint256, uint256, uint256, uint256, uint256, uint256, MilestoneStatus status) { Milestone memory mil = _milestoneDetails[hash]; status = getMilestoneStatus(hash); return ( mil.name, mil.startTimestamp, mil.disputesOpeningTimestamp, mil.cycleId, mil.tokenPercent, mil.ethPercent, mil.disputes.activeDisputes, status ); } function getMilestoneStatus(bytes32 hash) public view returns (MilestoneStatus status) { // checking if the time for collecting milestone funds was comes if (block.timestamp >= _milestoneDetails[hash].startTimestamp) { return MilestoneStatus.APPROVED; } else if (block.timestamp > _milestoneDetails[hash].disputesOpeningTimestamp) { return MilestoneStatus.DISPUTS_PERIOD; } else { return MilestoneStatus.PENDING; } } function getCycleTotalPercents() external view returns (uint256, uint256) { return ( _allCyclesTokensPercent, _allCyclesEthPercent ); } function canInvestorOpenNewDispute(bytes32 hash, address investor) public view returns (bool) { InvestorDisputeState state = _milestoneDetails[hash].disputes.investorDispute[investor]; return state == InvestorDisputeState.NO_DISPUTES || state == InvestorDisputeState.CLOSED; } function isMilestoneHasActiveDisputes(bytes32 hash) public view returns (bool) { return _milestoneDetails[hash].disputes.activeDisputes > 0; } function didInvestorOpenedDisputeBefore(bytes32 hash, address investor) public view returns (bool) { return _milestoneDetails[hash].disputes.investorDispute[investor] != InvestorDisputeState.NO_DISPUTES; } function didInvestorWithdraw(bytes32 hash, address investor) public view returns (bool) { return _milestoneDetails[hash].userWasWithdrawn[investor]; } } // File: contracts/deployers/CrowdsaleDeployer.sol library CrowdsaleDeployer { function addCrowdsale( uint256 rate, address token, uint256 openingTime, uint256 closingTime, address payable operator, uint256[] calldata bonusFinishTimestamp, uint256[] calldata bonuses, uint256 minInvestmentAmount, uint256 fee ) external returns (address) { return address(new ResponsibleCrowdsale(rate, token, openingTime, closingTime, operator, bonusFinishTimestamp, bonuses, minInvestmentAmount, fee)); } } // --------------------------------------------------------------------------- // ARBITERS POOL // --------------------------------------------------------------------------- // File: contracts/ownerships/Roles.sol library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } // File: contracts/ownerships/ArbiterRole.sol contract ArbiterRole is ClusterRole { using Roles for Roles.Role; uint256 private _arbitersAmount; event ArbiterAdded(address indexed arbiter); event ArbiterRemoved(address indexed arbiter); Roles.Role private _arbiters; modifier onlyArbiter() { require(isArbiter(msg.sender), "onlyArbiter: only arbiter can call this method."); _; } // ----------------------------------------- // EXTERNAL // ----------------------------------------- function addArbiter(address arbiter) public onlyCluster { _addArbiter(arbiter); _arbitersAmount++; } function removeArbiter(address arbiter) public onlyCluster { _removeArbiter(arbiter); _arbitersAmount--; } // ----------------------------------------- // INTERNAL // ----------------------------------------- function _addArbiter(address arbiter) private { _arbiters.add(arbiter); emit ArbiterAdded(arbiter); } function _removeArbiter(address arbiter) private { _arbiters.remove(arbiter); emit ArbiterRemoved(arbiter); } // ----------------------------------------- // GETTERS // ----------------------------------------- function isArbiter(address account) public view returns (bool) { return _arbiters.has(account); } function getArbitersAmount() external view returns (uint256) { return _arbitersAmount; } } // File: contracts/interfaces/ICluster.sol interface ICluster { function withdrawEth() external; function addArbiter(address newArbiter) external; function removeArbiter(address arbiter) external; function addCrowdsale( uint256 rate, address token, uint256 openingTime, uint256 closingTime, address payable operator, uint256[] calldata bonusFinishTimestamp, uint256[] calldata bonuses, uint256 minInvestmentAmount, uint256 fee ) external returns (address); function emergencyExit(address crowdsale, address payable newContract) external; function openDispute(address crowdsale, bytes32 hash, string calldata reason) external payable returns (uint256); function solveDispute(address crowdsale, bytes32 hash, address investor, bool investorWins) external; function getArbitersPoolAddress() external view returns (address); function getAllCrowdsalesAddresses() external view returns (address[] memory crowdsales); function getCrowdsaleMilestones(address crowdsale) external view returns(bytes32[] memory milestonesHashArray); function getOperatorCrowdsaleAddresses(address operator) external view returns (address[] memory crowdsales); function owner() external view returns (address payable); function isOwner() external view returns (bool); function transferOwnership(address payable newOwner) external; function isBackEnd(address account) external view returns (bool); function addBackEnd(address account) external; function removeBackEnd(address account) external; } // File: contracts/ArbitersPool.sol contract ArbitersPool is ArbiterRole { uint256 private _disputsAmount; uint256 private constant _necessaryVoices = 3; enum DisputeStatus { WAITING, SOLVED } enum Choice { OPERATOR_WINS, INVESTOR_WINS } ICluster private _clusterInterface; struct Vote { address arbiter; Choice choice; } struct Dispute { address investor; address crowdsale; bytes32 milestoneHash; string reason; uint256 votesAmount; DisputeStatus status; mapping (address => bool) hasVoted; mapping (uint256 => Vote) choices; } mapping (uint256 => Dispute) private _disputesById; mapping (address => uint256[]) private _disputesByInvestor; mapping (bytes32 => uint256[]) private _disputesByMilestone; event Voted(uint256 indexed disputeId, address indexed arbiter, Choice choice); event NewDisputeCreated(uint256 disputeId, address indexed crowdsale, bytes32 indexed hash, address indexed investor); event DisputeSolved(uint256 disputeId, Choice choice, address indexed crowdsale, bytes32 indexed hash, address indexed investor); constructor () public { _clusterInterface = ICluster(msg.sender); } function createDispute(bytes32 milestoneHash, address crowdsale, address investor, string calldata reason) external onlyCluster returns (uint256) { Dispute memory dispute = Dispute( investor, crowdsale, milestoneHash, reason, 0, DisputeStatus.WAITING ); uint256 thisDisputeId = _disputsAmount; _disputsAmount++; _disputesById[thisDisputeId] = dispute; _disputesByMilestone[milestoneHash].push(thisDisputeId); _disputesByInvestor[investor].push(thisDisputeId); emit NewDisputeCreated(thisDisputeId, crowdsale, milestoneHash, investor); return thisDisputeId; } function voteDispute(uint256 id, Choice choice) public onlyArbiter { require(_disputsAmount > id, "voteDispute: invalid number of dispute."); require(_disputesById[id].hasVoted[msg.sender] == false, "voteDispute: arbiter was already voted."); require(_disputesById[id].status == DisputeStatus.WAITING, "voteDispute: dispute was already closed."); require(_disputesById[id].votesAmount < _necessaryVoices, "voteDispute: dispute was already voted and finished."); _disputesById[id].hasVoted[msg.sender] = true; // updating the votes amount _disputesById[id].votesAmount++; // storing info about this vote uint256 votesAmount = _disputesById[id].votesAmount; _disputesById[id].choices[votesAmount] = Vote(msg.sender, choice); // checking, if the second arbiter voted the same result with the 1st voted arbiter, then dispute will be solved without 3rd vote if (_disputesById[id].votesAmount == 2 && _disputesById[id].choices[0].choice == choice) { _executeDispute(id, choice); } else if (_disputesById[id].votesAmount == _necessaryVoices) { Choice winner = _calculateWinner(id); _executeDispute(id, winner); } emit Voted(id, msg.sender, choice); } // ----------------------------------------- // INTERNAL // ----------------------------------------- function _calculateWinner(uint256 id) private view returns (Choice choice) { uint256 votesForInvestor = 0; for (uint256 i = 0; i < _necessaryVoices; i++) { if (_disputesById[id].choices[i].choice == Choice.INVESTOR_WINS) { votesForInvestor++; } } return votesForInvestor >= 2 ? Choice.INVESTOR_WINS : Choice.OPERATOR_WINS; } function _executeDispute(uint256 id, Choice choice) private { _disputesById[id].status = DisputeStatus.SOLVED; _clusterInterface.solveDispute( _disputesById[id].crowdsale, _disputesById[id].milestoneHash, _disputesById[id].investor, choice == Choice.INVESTOR_WINS ); emit DisputeSolved( id, choice, _disputesById[id].crowdsale, _disputesById[id].milestoneHash, _disputesById[id].investor ); } // ----------------------------------------- // GETTERS // ----------------------------------------- function getDisputesAmount() external view returns (uint256) { return _disputsAmount; } function getDisputeDetails(uint256 id) external view returns (bytes32, address, address, string memory, uint256, DisputeStatus status) { Dispute memory dispute = _disputesById[id]; return ( dispute.milestoneHash, dispute.crowdsale, dispute.investor, dispute.reason, dispute.votesAmount, dispute.status ); } function getMilestoneDisputes(bytes32 hash) external view returns (uint256[] memory disputesIDs) { uint256 disputesLength = _disputesByMilestone[hash].length; disputesIDs = new uint256[](disputesLength); for (uint256 i = 0; i < disputesLength; i++) { disputesIDs[i] = _disputesByMilestone[hash][i]; } return disputesIDs; } function getInvestorDisputes(address investor) external view returns (uint256[] memory disputesIDs) { uint256 disputesLength = _disputesByInvestor[investor].length; disputesIDs = new uint256[](disputesLength); for (uint256 i = 0; i < disputesLength; i++) { disputesIDs[i] = _disputesByInvestor[investor][i]; } return disputesIDs; } function getDisputeVotes(uint256 id) external view returns(address[] memory arbiters, Choice[] memory choices) { uint256 votedArbitersAmount = _disputesById[id].votesAmount; arbiters = new address[](votedArbitersAmount); choices = new Choice[](votedArbitersAmount); for (uint256 i = 0; i < votedArbitersAmount; i++) { arbiters[i] = _disputesById[id].choices[i].arbiter; choices[i] = _disputesById[id].choices[i].choice; } return ( arbiters, choices ); } function hasDisputeSolved(uint256 id) external view returns (bool) { return _disputesById[id].status == DisputeStatus.SOLVED; } function hasArbiterVoted(uint256 id, address arbiter) external view returns (bool) { return _disputesById[id].hasVoted[arbiter]; } } // --------------------------------------------------------------------------- // CLUSTER CONTRACT // --------------------------------------------------------------------------- // File: contracts/interfaces/IArbitersPool.sol interface IArbitersPool { enum DisputeStatus { WAITING, SOLVED } enum Choice { OPERATOR_WINS, INVESTOR_WINS } function createDispute(bytes32 milestoneHash, address crowdsale, address investor, string calldata reason) external returns (uint256); function voteDispute(uint256 id, Choice choice) external; function addArbiter(address newArbiter) external; function renounceArbiter(address arbiter) external; function getDisputesAmount() external view returns (uint256); function getDisputeDetails(uint256 id) external view returns (bytes32, address, address, string memory, uint256, DisputeStatus status); function getMilestoneDisputes(bytes32 hash) external view returns (uint256[] memory disputesIDs); function getInvestorDisputes(address investor) external view returns (uint256[] memory disputesIDs); function getDisputeVotes(uint256 id) external view returns(address[] memory arbiters, Choice[] memory choices); function getArbitersAmount() external view returns (uint256); function isArbiter(address account) external view returns (bool); function hasDisputeSolved(uint256 id) external view returns (bool); function hasArbiterVoted(uint256 id, address arbiter) external view returns (bool); function cluster() external view returns (address payable); function isCluster() external view returns (bool); } // File: contracts/interfaces/IRICO.sol interface IRICO { enum MilestoneStatus { PENDING, DISPUTS_PERIOD, APPROVED } function addCycle( uint256 tokenPercent, uint256 ethPercent, bytes32[] calldata milestonesNames, uint256[] calldata milestonesTokenPercent, uint256[] calldata milestonesEthPercent, uint256[] calldata milestonesStartTimestamps ) external returns (bool); function collectMilestoneInvestment(bytes32 hash) external; function collectMilestoneResult(bytes32 hash) external; function getCyclesAmount() external view returns (uint256); function getCycleDetails(uint256 cycleId) external view returns (uint256, uint256, bytes32[] memory); function getMilestonesHashes() external view returns (bytes32[] memory milestonesHashArray); function getMilestoneDetails(bytes32 hash) external view returns (bytes32, uint256, uint256, uint256, uint256, uint256, uint256, MilestoneStatus status); function getMilestoneStatus(bytes32 hash) external view returns (MilestoneStatus status); function getCycleTotalPercents() external view returns (uint256, uint256); function canInvestorOpenNewDispute(bytes32 hash, address investor) external view returns (bool); function isMilestoneHasActiveDisputes(bytes32 hash) external view returns (bool); function didInvestorOpenedDisputeBefore(bytes32 hash, address investor) external view returns (bool); function didInvestorWithdraw(bytes32 hash, address investor) external view returns (bool); function buyTokens(address beneficiary) external payable; function isInvestor(address sender) external view returns (bool); function openDispute(bytes32 hash, address investor) external returns (bool); function solveDispute(bytes32 hash, address investor, bool investorWins) external; function emergencyExit(address payable newContract) external; function getCrowdsaleDetails() external view returns (uint256, address, uint256, uint256, uint256[] memory finishTimestamps, uint256[] memory bonuses); function getInvestorBalances(address investor) external view returns (uint256, uint256, uint256, uint256, bool); function getInvestorsArray() external view returns (address[] memory investors); function getRaisedWei() external view returns (uint256); function getSoldTokens() external view returns (uint256); function refundETH() external; function getOpeningTime() external view returns (uint256); function getClosingTime() external view returns (uint256); function isOpen() external view returns (bool); function hasClosed() external view returns (bool); function cluster() external view returns (address payable); function isCluster() external view returns (bool); function operator() external view returns (address payable); function isOperator() external view returns (bool); } // File: contracts/ownerships/Ownable.sol contract Ownable { address payable private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address payable) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "onlyOwner: only the owner can call this method."); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address payable newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address payable newOwner) private { require(newOwner != address(0), "_transferOwnership: the address of new operator is not valid."); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/ownerships/BackEndRole.sol contract BackEndRole is Ownable { using Roles for Roles.Role; event BackEndAdded(address indexed account); event BackEndRemoved(address indexed account); Roles.Role private _backEnds; modifier onlyBackEnd() { require(isBackEnd(msg.sender), "onlyBackEnd: only back end address can call this method."); _; } function isBackEnd(address account) public view returns (bool) { return _backEnds.has(account); } function addBackEnd(address account) public onlyOwner { _addBackEnd(account); } function removeBackEnd(address account) public onlyOwner { _removeBackEnd(account); } function _addBackEnd(address account) private { _backEnds.add(account); emit BackEndAdded(account); } function _removeBackEnd(address account) private { _backEnds.remove(account); emit BackEndRemoved(account); } } // File: contracts/Cluster.sol contract Cluster is BackEndRole { uint256 private constant _feeForMoreDisputes = 1 ether; address private _arbitersPoolAddress; address[] private _crowdsales; mapping (address => address[]) private _operatorsContracts; IArbitersPool private _arbitersPool; event WeiFunded(address indexed sender, uint256 indexed amount); event CrowdsaleCreated( address crowdsale, uint256 rate, address token, uint256 openingTime, uint256 closingTime, address operator, uint256[] bonusFinishTimestamp, uint256[] bonuses, uint256 minInvestmentAmount, uint256 fee ); // ----------------------------------------- // CONSTRUCTOR // ----------------------------------------- constructor () public { _arbitersPoolAddress = address(new ArbitersPool()); _arbitersPool = IArbitersPool(_arbitersPoolAddress); } function() external payable { emit WeiFunded(msg.sender, msg.value); } // ----------------------------------------- // OWNER FEATURES // ----------------------------------------- function withdrawEth() external onlyOwner { owner().transfer(address(this).balance); } function addArbiter(address newArbiter) external onlyBackEnd { require(newArbiter != address(0), "addArbiter: invalid type of address."); _arbitersPool.addArbiter(newArbiter); } function removeArbiter(address arbiter) external onlyBackEnd { require(arbiter != address(0), "removeArbiter: invalid type of address."); _arbitersPool.renounceArbiter(arbiter); } function addCrowdsale( uint256 rate, address token, uint256 openingTime, uint256 closingTime, address payable operator, uint256[] calldata bonusFinishTimestamp, uint256[] calldata bonuses, uint256 minInvestmentAmount, uint256 fee ) external onlyBackEnd returns (address) { require(rate != 0, "addCrowdsale: the rate should be bigger then 0."); require(token != address(0), "addCrowdsale: invalid token address."); require(openingTime >= block.timestamp, "addCrowdsale: invalid opening time."); require(closingTime > openingTime, "addCrowdsale: invalid closing time."); require(operator != address(0), "addCrowdsale: the address of operator is not valid."); require(bonusFinishTimestamp.length == bonuses.length, "addCrowdsale: the length of bonusFinishTimestamp and bonuses is not equal."); address crowdsale = CrowdsaleDeployer.addCrowdsale( rate, token, openingTime, closingTime, operator, bonusFinishTimestamp, bonuses, minInvestmentAmount, fee ); // Updating the state _crowdsales.push(crowdsale); _operatorsContracts[operator].push(crowdsale); emit CrowdsaleCreated( crowdsale, rate, token, openingTime, closingTime, operator, bonusFinishTimestamp, bonuses, minInvestmentAmount, fee ); return crowdsale; } // ----------------------------------------- // OPERATOR FEATURES // ----------------------------------------- function emergencyExit(address crowdsale, address payable newContract) external onlyOwner { IRICO(crowdsale).emergencyExit(newContract); } // ----------------------------------------- // INVESTOR FEATURES // ----------------------------------------- function openDispute(address crowdsale, bytes32 hash, string calldata reason) external payable returns (uint256) { require(IRICO(crowdsale).isInvestor(msg.sender) == true, "openDispute: sender is not an investor."); require(IRICO(crowdsale).canInvestorOpenNewDispute(hash, msg.sender) == true, "openDispute: investor cannot open a new dispute."); require(IRICO(crowdsale).getMilestoneStatus(hash) == IRICO.MilestoneStatus.DISPUTS_PERIOD, "openDispute: the period for opening new disputes was finished."); if (IRICO(crowdsale).didInvestorOpenedDisputeBefore(hash, msg.sender) == true) { require(msg.value == _feeForMoreDisputes, "openDispute: for the second and other disputes investor need to pay 1 ETH fee."); } IRICO(crowdsale).openDispute(hash, msg.sender); uint256 disputeID = _arbitersPool.createDispute(hash, crowdsale, msg.sender, reason); return disputeID; } // ----------------------------------------- // ARBITERSPOOL FEATURES // ----------------------------------------- function solveDispute(address crowdsale, bytes32 hash, address investor, bool investorWins) external { require(msg.sender == _arbitersPoolAddress, "solveDispute: the sender is not arbiters pool contract."); IRICO(crowdsale).solveDispute(hash, investor, investorWins); } // ----------------------------------------- // GETTERS // ----------------------------------------- function getArbitersPoolAddress() external view returns (address) { return _arbitersPoolAddress; } function getAllCrowdsalesAddresses() external view returns (address[] memory crowdsales) { crowdsales = new address[](_crowdsales.length); for (uint256 i = 0; i < _crowdsales.length; i++) { crowdsales[i] = _crowdsales[i]; } return crowdsales; } function getCrowdsaleMilestones(address crowdsale) external view returns(bytes32[] memory milestonesHashArray) { return IRICO(crowdsale).getMilestonesHashes(); } function getOperatorCrowdsaleAddresses(address operator) external view returns (address[] memory crowdsales) { crowdsales = new address[](_operatorsContracts[operator].length); for (uint256 i = 0; i < _operatorsContracts[operator].length; i++) { crowdsales[i] = _operatorsContracts[operator][i]; } return crowdsales; } }
return true if `msg.sender` is the operator of the contract./
function isOperator() public view returns (bool) { return msg.sender == _operator; }
6,359,823
./full_match/41/0xC450EdCeD6b99Ac4b2B0D3A62a67f119Af631629/sources/project_/contracts/libraries/WhaleLibrary.sol
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, 'WhaleLibrary: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'WhaleLibrary: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(9975); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(10000).add(amountInWithFee); amountOut = numerator / denominator; }
16,374,245
./full_match/11155111/0xB925899Df589e10c71F540eA92F5fC7b98552AAb/sources/src/upgradeable/SafeUUPSUpgradeable.sol
solhint-disable-line no-empty-blocks
function _authorizeUpgrade(address newImplementation) internal onlyOwner override {}
3,820,594
pragma solidity >=0.5.10; /// @title Simplified ERC1319 Registry for Brownie testing, based on ethpm/solidity-registry /// @author original version written by Nick Gheorghita <[email protected]> /// @notice DO NOT USE THIS IN PRODUCTION contract PackageRegistry { struct Package { bool exists; uint createdAt; uint updatedAt; uint releaseCount; string name; } struct Release { bool exists; uint createdAt; bytes32 packageId; string version; string manifestURI; } mapping (bytes32 => Package) public packages; mapping (bytes32 => Release) public releases; // package_id#release_count => release_id mapping (bytes32 => bytes32) packageReleaseIndex; // Total package number (int128) => package_id (bytes32) mapping (uint => bytes32) allPackageIds; // Total release number (int128) => release_id (bytes32) mapping (uint => bytes32) allReleaseIds; // Total number of packages in registry uint public packageCount; // Total number of releases in registry uint public releaseCount; // Events event VersionRelease(string packageName, string version, string manifestURI); event PackageTransfer(address indexed oldOwner, address indexed newOwner); // Modifiers modifier onlyIfPackageExists(string memory packageName) { require(packageExists(packageName), "package-does-not-exist"); _; } modifier onlyIfReleaseExists(string memory packageName, string memory version) { require (releaseExists(packageName, version), "release-does-not-exist"); _; } // // =============== // | Write API | // =============== // /// @dev Creates a new release for the named package. If this is the first release for the given /// package then this will also create and store the package. Returns releaseID if successful. /// @notice Will create a new release the given package with the given release information. /// @param packageName Package name /// @param version Version string (ex: '1.0.0') /// @param manifestURI The URI for the release manifest for this release. function release( string memory packageName, string memory version, string memory manifestURI ) public returns (bytes32) { validatePackageName(packageName); validateStringIdentifier(version); validateStringIdentifier(manifestURI); // Compute hashes bytes32 packageId = generatePackageId(packageName); bytes32 releaseId = generateReleaseId(packageName, version); Package storage package = packages[packageId]; // If the package does not yet exist create it if (package.exists == false) { package.exists = true; package.createdAt = block.timestamp; package.updatedAt = block.timestamp; package.name = packageName; package.releaseCount = 0; allPackageIds[packageCount] = packageId; packageCount++; } else { package.updatedAt = block.timestamp; } _cutRelease(packageId, releaseId, packageName, version, manifestURI); return releaseId; } function _cutRelease( bytes32 packageId, bytes32 releaseId, string memory packageName, string memory version, string memory manifestURI ) private { Release storage newRelease = releases[releaseId]; require(newRelease.exists == false, "release-already-exists"); // Store new release data newRelease.exists = true; newRelease.createdAt = block.timestamp; newRelease.packageId = packageId; newRelease.version = version; newRelease.manifestURI = manifestURI; releases[releaseId] = newRelease; allReleaseIds[releaseCount] = releaseId; releaseCount++; // Update package's release count Package storage package = packages[packageId]; bytes32 packageReleaseId = generatePackageReleaseId(packageId, package.releaseCount); packageReleaseIndex[packageReleaseId] = releaseId; package.releaseCount++; // Log the release. emit VersionRelease(packageName, version, manifestURI); } // // ============== // | Read API | // ============== // /// @dev Returns the string name of the package associated with a package id /// @param packageId The package id to look up function getPackageName(bytes32 packageId) public view returns (string memory packageName) { Package memory targetPackage = packages[packageId]; require (targetPackage.exists == true, "package-does-not-exist"); return targetPackage.name; } /// @dev Returns a slice of the array of all package ids for the named package. /// @param offset The starting index for the slice. /// @param limit The length of the slice function getAllPackageIds(uint offset, uint limit) public view returns ( bytes32[] memory packageIds, uint pointer ) { bytes32[] memory hashes; // Array of package ids to return uint cursor = offset; // Index counter to traverse DB array uint remaining; // Counter to collect `limit` packages // Is request within range? if (cursor < packageCount){ // Get total remaining records remaining = packageCount - cursor; // Number of records to collect is lesser of `remaining` and `limit` if (remaining > limit ){ remaining = limit; } // Allocate return array hashes = new bytes32[](remaining); // Collect records. while(remaining > 0){ bytes32 hash = allPackageIds[cursor]; hashes[remaining - 1] = hash; remaining--; cursor++; } } return (hashes, cursor); } /// @dev Returns a slice of the array of all release hashes for the named package. /// @param packageName Package name /// @param offset The starting index for the slice. /// @param limit The length of the slice function getAllReleaseIds(string memory packageName, uint offset, uint limit) public view onlyIfPackageExists(packageName) returns ( bytes32[] memory releaseIds, uint pointer ) { bytes32 packageId = generatePackageId(packageName); Package storage package = packages[packageId]; bytes32[] memory hashes; // Release ids to return uint cursor = offset; // Index counter to traverse DB array uint remaining; // Counter to collect `limit` packages uint numPackageReleases = package.releaseCount; // Total number of packages in registry // Is request within range? if (cursor < numPackageReleases){ // Get total remaining records remaining = numPackageReleases - cursor; // Number of records to collect is lesser of `remaining` and `limit` if (remaining > limit ){ remaining = limit; } // Allocate return array hashes = new bytes32[](remaining); // Collect records. while(remaining > 0){ bytes32 packageReleaseId = generatePackageReleaseId(packageId, cursor); bytes32 hash = packageReleaseIndex[packageReleaseId]; hashes[remaining - 1] = hash; remaining--; cursor++; } } return (hashes, cursor); } /// @dev Returns the package data for a release. /// @param releaseId Release id function getReleaseData(bytes32 releaseId) public view returns ( string memory packageName, string memory version, string memory manifestURI ) { Release memory targetRelease = releases[releaseId]; Package memory targetPackage = packages[targetRelease.packageId]; return (targetPackage.name, targetRelease.version, targetRelease.manifestURI); } /// @dev Returns the release id for a given name and version pair if present on registry. /// @param packageName Package name /// @param version Version string(ex: '1.0.0') function getReleaseId(string memory packageName, string memory version) public view onlyIfPackageExists(packageName) onlyIfReleaseExists(packageName, version) returns (bytes32 releaseId) { return generateReleaseId(packageName, version); } /// @dev Returns the number of packages stored on the registry function numPackageIds() public view returns (uint totalCount) { return packageCount; } /// @dev Returns the number of releases for a given package name on the registry /// @param packageName Package name function numReleaseIds(string memory packageName) public view onlyIfPackageExists(packageName) returns (uint totalCount) { bytes32 packageId = generatePackageId(packageName); Package storage package = packages[packageId]; return package.releaseCount; } /// @dev Returns a bool indicating whether the given release exists in this registry. /// @param packageName Package Name /// @param version version function releaseExists(string memory packageName, string memory version) public view onlyIfPackageExists(packageName) returns (bool) { bytes32 releaseId = generateReleaseId(packageName, version); Release storage targetRelease = releases[releaseId]; return targetRelease.exists; } /// @dev Returns a bool indicating whether the given package exists in this registry. /// @param packageName Package Name function packageExists(string memory packageName) public view returns (bool) { bytes32 packageId = generatePackageId(packageName); return packages[packageId].exists; } // // ==================== // | Hash Functions | // ==================== // /// @dev Returns name hash for a given package name. /// @param name Package name function generatePackageId(string memory name) public pure returns (bytes32) { return keccak256(abi.encodePacked(name)); } // @dev Returns release id that *would* be generated for a name and version pair on `release`. // @param packageName Package name // @param version Version string (ex: '1.0.0') function generateReleaseId( string memory packageName, string memory version ) public view returns (bytes32) { return keccak256(abi.encodePacked(packageName, version)); } function generatePackageReleaseId( bytes32 packageId, uint packageReleaseCount ) private pure returns (bytes32) { return keccak256(abi.encodePacked(packageId, packageReleaseCount)); } // // ================ // | Validation | // ================ // /// @dev Returns boolean whether the provided package name is valid. /// @param name The name of the package. function validatePackageName(string memory name) public pure returns (bool) { require (bytes(name).length > 2 && bytes(name).length < 255, "invalid-package-name"); } /// @dev Returns boolean whether the input string has a length /// @param value The string to validate. function validateStringIdentifier(string memory value) public pure returns (bool) { require (bytes(value).length != 0, "invalid-string-identifier"); } }
Returns the string name of the package associated with a package id packageId The package id to look up
function getPackageName(bytes32 packageId) public view returns (string memory packageName) { Package memory targetPackage = packages[packageId]; require (targetPackage.exists == true, "package-does-not-exist"); return targetPackage.name; }
14,016,951
// SPDX-License-Identifier: MIT pragma solidity >=0.6.11; pragma experimental ABIEncoderV2; import "../StakingRewardsDualV3.sol"; contract StakingRewardsDualV3_FRAX_IQ is StakingRewardsDualV3 { constructor( address _owner, address _rewardsToken0, address _rewardsToken1, address _stakingToken, address _frax_address, address _timelock_address, address _veFXS_address ) StakingRewardsDualV3(_owner, _rewardsToken0, _rewardsToken1, _stakingToken, _frax_address, _timelock_address, _veFXS_address ) {} } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; pragma experimental ABIEncoderV2; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ======================= StakingRewardsDualV3 ======================= // ==================================================================== // Includes veFXS boost logic // Unlocked deposits are removed to free up space // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Reviewer(s) / Contributor(s) // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian // Sam Sun: https://github.com/samczsun // Modified originally from Synthetixio // https://raw.githubusercontent.com/Synthetixio/synthetix/develop/contracts/StakingRewards.sol import "../Math/Math.sol"; import "../Math/SafeMath.sol"; import "../Curve/IveFXS.sol"; import "../ERC20/ERC20.sol"; import '../Uniswap/TransferHelper.sol'; import "../ERC20/SafeERC20.sol"; import "../Frax/Frax.sol"; import "../Uniswap/Interfaces/IUniswapV2Pair.sol"; import "../Utils/ReentrancyGuard.sol"; // Inheritance import "./Owned.sol"; contract StakingRewardsDualV3 is Owned, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for ERC20; /* ========== STATE VARIABLES ========== */ // Instances IveFXS private veFXS; ERC20 private rewardsToken0; ERC20 private rewardsToken1; IUniswapV2Pair private stakingToken; // Constant for various precisions uint256 private constant MULTIPLIER_PRECISION = 1e18; // Admin addresses address public timelock_address; // Governance timelock address // Time tracking uint256 public periodFinish; uint256 public lastUpdateTime; // Lock time and multiplier settings uint256 public lock_max_multiplier = uint256(3e18); // E18. 1x = e18 uint256 public lock_time_for_max_multiplier = 3 * 365 * 86400; // 3 years uint256 public lock_time_min = 86400; // 1 * 86400 (1 day) // veFXS related uint256 public vefxs_per_frax_for_max_boost = uint256(4e18); // E18. 4e18 means 4 veFXS must be held by the staker per 1 FRAX uint256 public vefxs_max_multiplier = uint256(25e17); // E18. 1x = 1e18 // mapping(address => uint256) private _vefxsMultiplierStoredOld; mapping(address => uint256) private _vefxsMultiplierStored; // Max reward per second uint256 public rewardRate0; uint256 public rewardRate1; // Reward period uint256 public rewardsDuration = 604800; // 7 * 86400 (7 days) // Reward tracking uint256 public rewardPerTokenStored0 = 0; uint256 public rewardPerTokenStored1 = 0; mapping(address => uint256) public userRewardPerTokenPaid0; mapping(address => uint256) public userRewardPerTokenPaid1; mapping(address => uint256) public rewards0; mapping(address => uint256) public rewards1; // Balance tracking uint256 private _total_liquidity_locked = 0; uint256 private _total_combined_weight = 0; mapping(address => uint256) private _locked_liquidity; mapping(address => uint256) private _combined_weights; // Uniswap related bool frax_is_token0; // Stake tracking mapping(address => LockedStake[]) private lockedStakes; // List of valid migrators (set by governance) mapping(address => bool) public valid_migrators; address[] public valid_migrators_array; // Stakers set which migrator(s) they want to use mapping(address => mapping(address => bool)) public staker_allowed_migrators; // Greylisting of bad addresses mapping(address => bool) public greylist; // Administrative booleans bool public token1_rewards_on = true; bool public migrationsOn = false; // Used for migrations. Prevents new stakes, but allows LP and reward withdrawals bool public stakesUnlocked = false; // Release locked stakes in case of system migration or emergency bool public withdrawalsPaused = false; // For emergencies bool public rewardsCollectionPaused = false; // For emergencies bool public stakingPaused = false; // For emergencies /* ========== STRUCTS ========== */ struct LockedStake { bytes32 kek_id; uint256 start_timestamp; uint256 liquidity; uint256 ending_timestamp; uint256 lock_multiplier; // 6 decimals of precision. 1x = 1000000 } /* ========== MODIFIERS ========== */ modifier onlyByOwnerOrGovernance() { require(msg.sender == owner || msg.sender == timelock_address, "You are not the owner or the governance timelock"); _; } modifier onlyByOwnerOrGovernanceOrMigrator() { require(msg.sender == owner || msg.sender == timelock_address || valid_migrators[msg.sender] == true, "You are not the owner, governance timelock, or a migrator"); _; } modifier isMigrating() { require(migrationsOn == true, "Contract is not in migration"); _; } modifier notStakingPaused() { require(stakingPaused == false, "Staking is paused"); _; } modifier notWithdrawalsPaused() { require(withdrawalsPaused == false, "Withdrawals are paused"); _; } modifier notRewardsCollectionPaused() { require(rewardsCollectionPaused == false, "Rewards collection is paused"); _; } modifier updateRewardAndBalance(address account, bool sync_too) { _updateRewardAndBalance(account, sync_too); _; } /* ========== CONSTRUCTOR ========== */ constructor( address _owner, address _rewardsToken0, address _rewardsToken1, address _stakingToken, address _frax_address, address _timelock_address, address _veFXS_address ) Owned(_owner){ rewardsToken0 = ERC20(_rewardsToken0); rewardsToken1 = ERC20(_rewardsToken1); stakingToken = IUniswapV2Pair(_stakingToken); veFXS = IveFXS(_veFXS_address); lastUpdateTime = block.timestamp; timelock_address = _timelock_address; // 10 FXS a day rewardRate0 = (uint256(3650e18)).div(365 * 86400); // 1 token1 a day rewardRate1 = (uint256(365e18)).div(365 * 86400); // Uniswap related. Need to know which token frax is (0 or 1) address token0 = stakingToken.token0(); if (token0 == _frax_address) frax_is_token0 = true; else frax_is_token0 = false; // Other booleans migrationsOn = false; stakesUnlocked = false; } /* ========== VIEWS ========== */ function totalLiquidityLocked() external view returns (uint256) { return _total_liquidity_locked; } function totalCombinedWeight() external view returns (uint256) { return _total_combined_weight; } function lockMultiplier(uint256 secs) public view returns (uint256) { uint256 lock_multiplier = uint256(MULTIPLIER_PRECISION).add( secs .mul(lock_max_multiplier.sub(MULTIPLIER_PRECISION)) .div(lock_time_for_max_multiplier) ); if (lock_multiplier > lock_max_multiplier) lock_multiplier = lock_max_multiplier; return lock_multiplier; } // Total locked liquidity tokens function lockedLiquidityOf(address account) public view returns (uint256) { return _locked_liquidity[account]; } // Total 'balance' used for calculating the percent of the pool the account owns // Takes into account the locked stake time multiplier and veFXS multiplier function combinedWeightOf(address account) external view returns (uint256) { return _combined_weights[account]; } function lockedStakesOf(address account) external view returns (LockedStake[] memory) { return lockedStakes[account]; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function fraxPerLPToken() public view returns (uint256) { // Get the amount of FRAX 'inside' of the lp tokens uint256 frax_per_lp_token; { uint256 total_frax_reserves; (uint256 reserve0, uint256 reserve1, ) = (stakingToken.getReserves()); if (frax_is_token0) total_frax_reserves = reserve0; else total_frax_reserves = reserve1; frax_per_lp_token = total_frax_reserves.mul(1e18).div(stakingToken.totalSupply()); } return frax_per_lp_token; } function userStakedFrax(address account) public view returns (uint256) { return (fraxPerLPToken()).mul(_locked_liquidity[account]).div(1e18); } function minVeFXSForMaxBoost(address account) public view returns (uint256) { return (userStakedFrax(account)).mul(vefxs_per_frax_for_max_boost).div(MULTIPLIER_PRECISION); } function veFXSMultiplier(address account) public view returns (uint256) { // The claimer gets a boost depending on amount of veFXS they have relative to the amount of FRAX 'inside' // of their locked LP tokens uint256 veFXS_needed_for_max_boost = minVeFXSForMaxBoost(account); if (veFXS_needed_for_max_boost > 0){ uint256 user_vefxs_fraction = (veFXS.balanceOf(account)).mul(MULTIPLIER_PRECISION).div(veFXS_needed_for_max_boost); uint256 vefxs_multiplier = uint256(MULTIPLIER_PRECISION).add( (user_vefxs_fraction) .mul(vefxs_max_multiplier.sub(MULTIPLIER_PRECISION)) .div(MULTIPLIER_PRECISION) ); // Cap the boost to the vefxs_max_multiplier if (vefxs_multiplier > vefxs_max_multiplier) vefxs_multiplier = vefxs_max_multiplier; return vefxs_multiplier; } else return MULTIPLIER_PRECISION; // This will happen with the first stake, when user_staked_frax is 0 } function calcCurCombinedWeight(address account) public view returns ( uint256 old_combined_weight, uint256 new_vefxs_multiplier, uint256 new_combined_weight ) { // Get the old combined weight old_combined_weight = _combined_weights[account]; // Get the veFXS multipliers // For the calculations, use the midpoint (analogous to midpoint Riemann sum) new_vefxs_multiplier = veFXSMultiplier(account); uint256 midpoint_vefxs_multiplier = ((new_vefxs_multiplier).add(_vefxsMultiplierStored[account])).div(2); // Loop through the locked stakes, first by getting the liquidity * lock_multiplier portion new_combined_weight = 0; for (uint256 i = 0; i < lockedStakes[account].length; i++) { LockedStake memory thisStake = lockedStakes[account][i]; uint256 lock_multiplier = thisStake.lock_multiplier; // If the lock period is over, drop the lock multiplier to 1x for the weight calculations if (thisStake.ending_timestamp <= block.timestamp){ lock_multiplier = MULTIPLIER_PRECISION; } uint256 liquidity = thisStake.liquidity; uint256 extra_vefxs_boost = midpoint_vefxs_multiplier.sub(MULTIPLIER_PRECISION); // Multiplier - 1, because it is additive uint256 combined_boosted_amount = liquidity.mul(lock_multiplier.add(extra_vefxs_boost)).div(MULTIPLIER_PRECISION); new_combined_weight = new_combined_weight.add(combined_boosted_amount); } } function rewardPerToken() public view returns (uint256, uint256) { if (_total_liquidity_locked == 0 || _total_combined_weight == 0) { return (rewardPerTokenStored0, rewardPerTokenStored1); } else { return ( rewardPerTokenStored0.add( lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate0).mul(1e18).div(_total_combined_weight) ), rewardPerTokenStored1.add( lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate1).mul(1e18).div(_total_combined_weight) ) ); } } function earned(address account) public view returns (uint256, uint256) { (uint256 reward0, uint256 reward1) = rewardPerToken(); if (_combined_weights[account] == 0){ return (0, 0); } return ( (_combined_weights[account].mul(reward0.sub(userRewardPerTokenPaid0[account]))).div(1e18).add(rewards0[account]), (_combined_weights[account].mul(reward1.sub(userRewardPerTokenPaid1[account]))).div(1e18).add(rewards1[account]) ); } function getRewardForDuration() external view returns (uint256, uint256) { return ( rewardRate0.mul(rewardsDuration), rewardRate1.mul(rewardsDuration) ); } function migratorApprovedForStaker(address staker_address, address migrator_address) public view returns (bool) { // Migrator is not a valid one if (valid_migrators[migrator_address] == false) return false; // Staker has to have approved this particular migrator if (staker_allowed_migrators[staker_address][migrator_address] == true) return true; // Otherwise, return false return false; } /* ========== MUTATIVE FUNCTIONS ========== */ function _updateRewardAndBalance(address account, bool sync_too) internal { // Need to retro-adjust some things if the period hasn't been renewed, then start a new one if (sync_too){ sync(); } if (account != address(0)) { // To keep the math correct, the user's combined weight must be recomputed to account for their // ever-changing veFXS balance. ( uint256 old_combined_weight, uint256 new_vefxs_multiplier, uint256 new_combined_weight ) = calcCurCombinedWeight(account); // Calculate the earnings first _syncEarned(account); // Update the user's stored veFXS multipliers _vefxsMultiplierStored[account] = new_vefxs_multiplier; // Update the user's and the global combined weights if (new_combined_weight >= old_combined_weight) { uint256 weight_diff = new_combined_weight.sub(old_combined_weight); _total_combined_weight = _total_combined_weight.add(weight_diff); _combined_weights[account] = old_combined_weight.add(weight_diff); } else { uint256 weight_diff = old_combined_weight.sub(new_combined_weight); _total_combined_weight = _total_combined_weight.sub(weight_diff); _combined_weights[account] = old_combined_weight.sub(weight_diff); } } } function _syncEarned(address account) internal { if (account != address(0)) { // Calculate the earnings (uint256 earned0, uint256 earned1) = earned(account); rewards0[account] = earned0; rewards1[account] = earned1; userRewardPerTokenPaid0[account] = rewardPerTokenStored0; userRewardPerTokenPaid1[account] = rewardPerTokenStored1; } } // Staker can allow a migrator function stakerAllowMigrator(address migrator_address) public { require(staker_allowed_migrators[msg.sender][migrator_address] == false, "Address already exists"); require(valid_migrators[migrator_address], "Invalid migrator address"); staker_allowed_migrators[msg.sender][migrator_address] = true; } // Staker can disallow a previously-allowed migrator function stakerDisallowMigrator(address migrator_address) public { require(staker_allowed_migrators[msg.sender][migrator_address] == true, "Address doesn't exist already"); // Delete from the mapping delete staker_allowed_migrators[msg.sender][migrator_address]; } // Two different stake functions are needed because of delegateCall and msg.sender issues (important for migration) function stakeLocked(uint256 liquidity, uint256 secs) public { _stakeLocked(msg.sender, msg.sender, liquidity, secs); } // If this were not internal, and source_address had an infinite approve, this could be exploitable // (pull funds from source_address and stake for an arbitrary staker_address) function _stakeLocked(address staker_address, address source_address, uint256 liquidity, uint256 secs) internal nonReentrant updateRewardAndBalance(staker_address, true) { require((!stakingPaused && migrationsOn == false) || valid_migrators[msg.sender] == true, "Staking is paused, or migration is happening"); require(liquidity > 0, "Must stake more than zero"); require(greylist[staker_address] == false, "Address has been greylisted"); require(secs >= lock_time_min, "Minimum stake time not met"); require(secs <= lock_time_for_max_multiplier,"You are trying to lock for too long"); uint256 lock_multiplier = lockMultiplier(secs); bytes32 kek_id = keccak256(abi.encodePacked(staker_address, block.timestamp, liquidity)); lockedStakes[staker_address].push(LockedStake( kek_id, block.timestamp, liquidity, block.timestamp.add(secs), lock_multiplier )); // Pull the tokens from the source_address TransferHelper.safeTransferFrom(address(stakingToken), source_address, address(this), liquidity); // Update liquidities _total_liquidity_locked = _total_liquidity_locked.add(liquidity); _locked_liquidity[staker_address] = _locked_liquidity[staker_address].add(liquidity); // Need to call to update the combined weights _updateRewardAndBalance(staker_address, false); emit StakeLocked(staker_address, liquidity, secs, kek_id, source_address); } // Two different withdrawLocked functions are needed because of delegateCall and msg.sender issues (important for migration) function withdrawLocked(bytes32 kek_id) public { _withdrawLocked(msg.sender, msg.sender, kek_id); } // No withdrawer == msg.sender check needed since this is only internally callable and the checks are done in the wrapper // functions like withdraw(), migrator_withdraw_unlocked() and migrator_withdraw_locked() function _withdrawLocked(address staker_address, address destination_address, bytes32 kek_id) internal nonReentrant notWithdrawalsPaused updateRewardAndBalance(staker_address, true) { LockedStake memory thisStake; thisStake.liquidity = 0; uint theArrayIndex; for (uint i = 0; i < lockedStakes[staker_address].length; i++){ if (kek_id == lockedStakes[staker_address][i].kek_id){ thisStake = lockedStakes[staker_address][i]; theArrayIndex = i; break; } } require(thisStake.kek_id == kek_id, "Stake not found"); require(block.timestamp >= thisStake.ending_timestamp || stakesUnlocked == true || valid_migrators[msg.sender] == true, "Stake is still locked!"); uint256 liquidity = thisStake.liquidity; if (liquidity > 0) { // Update liquidities _total_liquidity_locked = _total_liquidity_locked.sub(liquidity); _locked_liquidity[staker_address] = _locked_liquidity[staker_address].sub(liquidity); // Remove the stake from the array delete lockedStakes[staker_address][theArrayIndex]; // Need to call to update the combined weights _updateRewardAndBalance(staker_address, false); // Give the tokens to the destination_address // Should throw if insufficient balance stakingToken.transfer(destination_address, liquidity); emit WithdrawLocked(staker_address, liquidity, kek_id, destination_address); } } // Two different getReward functions are needed because of delegateCall and msg.sender issues (important for migration) function getReward() external returns (uint256, uint256) { return _getReward(msg.sender, msg.sender); } // No withdrawer == msg.sender check needed since this is only internally callable // This distinction is important for the migrator function _getReward(address rewardee, address destination_address) internal nonReentrant notRewardsCollectionPaused updateRewardAndBalance(rewardee, true) returns (uint256 reward0, uint256 reward1) { reward0 = rewards0[rewardee]; reward1 = rewards1[rewardee]; if (reward0 > 0) { rewards0[rewardee] = 0; rewardsToken0.transfer(destination_address, reward0); emit RewardPaid(rewardee, reward0, address(rewardsToken0), destination_address); } // if (token1_rewards_on){ if (reward1 > 0) { rewards1[rewardee] = 0; rewardsToken1.transfer(destination_address, reward1); emit RewardPaid(rewardee, reward1, address(rewardsToken1), destination_address); } // } } function renewIfApplicable() external { if (block.timestamp > periodFinish) { retroCatchUp(); } } // If the period expired, renew it function retroCatchUp() internal { // Failsafe check require(block.timestamp > periodFinish, "Period has not expired yet!"); // Ensure the provided reward amount is not more than the balance in the contract. // This keeps the reward rate in the right range, preventing overflows due to // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. uint256 num_periods_elapsed = uint256(block.timestamp.sub(periodFinish)) / rewardsDuration; // Floor division to the nearest period uint balance0 = rewardsToken0.balanceOf(address(this)); uint balance1 = rewardsToken1.balanceOf(address(this)); require(rewardRate0.mul(rewardsDuration).mul(num_periods_elapsed + 1) <= balance0, "Not enough FXS available for rewards!"); if (token1_rewards_on){ require(rewardRate1.mul(rewardsDuration).mul(num_periods_elapsed + 1) <= balance1, "Not enough token1 available for rewards!"); } // uint256 old_lastUpdateTime = lastUpdateTime; // uint256 new_lastUpdateTime = block.timestamp; // lastUpdateTime = periodFinish; periodFinish = periodFinish.add((num_periods_elapsed.add(1)).mul(rewardsDuration)); (uint256 reward0, uint256 reward1) = rewardPerToken(); rewardPerTokenStored0 = reward0; rewardPerTokenStored1 = reward1; lastUpdateTime = lastTimeRewardApplicable(); emit RewardsPeriodRenewed(address(stakingToken)); } function sync() public { if (block.timestamp > periodFinish) { retroCatchUp(); } else { (uint256 reward0, uint256 reward1) = rewardPerToken(); rewardPerTokenStored0 = reward0; rewardPerTokenStored1 = reward1; lastUpdateTime = lastTimeRewardApplicable(); } } /* ========== RESTRICTED FUNCTIONS ========== */ // Migrator can stake for someone else (they won't be able to withdraw it back though, only staker_address can). function migrator_stakeLocked_for(address staker_address, uint256 amount, uint256 secs) external isMigrating { require(migratorApprovedForStaker(staker_address, msg.sender), "msg.sender is either an invalid migrator or the staker has not approved them"); _stakeLocked(staker_address, msg.sender, amount, secs); } // Used for migrations function migrator_withdraw_locked(address staker_address, bytes32 kek_id) external isMigrating { require(migratorApprovedForStaker(staker_address, msg.sender), "msg.sender is either an invalid migrator or the staker has not approved them"); _withdrawLocked(staker_address, msg.sender, kek_id); } // Adds supported migrator address function addMigrator(address migrator_address) public onlyByOwnerOrGovernance { require(valid_migrators[migrator_address] == false, "address already exists"); valid_migrators[migrator_address] = true; valid_migrators_array.push(migrator_address); } // Remove a migrator address function removeMigrator(address migrator_address) public onlyByOwnerOrGovernance { require(valid_migrators[migrator_address] == true, "address doesn't exist already"); // Delete from the mapping delete valid_migrators[migrator_address]; // 'Delete' from the array by setting the address to 0x0 for (uint i = 0; i < valid_migrators_array.length; i++){ if (valid_migrators_array[i] == migrator_address) { valid_migrators_array[i] = address(0); // This will leave a null in the array and keep the indices the same break; } } } // Added to support recovering LP Rewards and other mistaken tokens from other systems to be distributed to holders function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnerOrGovernance { // Admin cannot withdraw the staking token from the contract unless currently migrating if(!migrationsOn){ require(tokenAddress != address(stakingToken), "Cannot withdraw staking tokens unless migration is on"); // Only Governance / Timelock can trigger a migration } // Only the owner address can ever receive the recovery withdrawal ERC20(tokenAddress).transfer(owner, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } function setRewardsDuration(uint256 _rewardsDuration) external onlyByOwnerOrGovernance { require( periodFinish == 0 || block.timestamp > periodFinish, "Previous rewards period must be complete before changing the duration for the new period" ); rewardsDuration = _rewardsDuration; emit RewardsDurationUpdated(rewardsDuration); } function setMultipliers(uint256 _lock_max_multiplier, uint256 _vefxs_max_multiplier, uint256 _vefxs_per_frax_for_max_boost) external onlyByOwnerOrGovernance { require(_lock_max_multiplier >= uint256(1e6), "Multiplier must be greater than or equal to 1e6"); require(_vefxs_max_multiplier >= uint256(1e18), "Max veFXS multiplier must be greater than or equal to 1e18"); require(_vefxs_per_frax_for_max_boost > 0, "veFXS per FRAX must be greater than 0"); lock_max_multiplier = _lock_max_multiplier; vefxs_max_multiplier = _vefxs_max_multiplier; vefxs_per_frax_for_max_boost = _vefxs_per_frax_for_max_boost; emit MaxVeFXSMultiplier(vefxs_max_multiplier); emit LockedStakeMaxMultiplierUpdated(lock_max_multiplier); emit veFXSPerFraxForMaxBoostUpdated(vefxs_per_frax_for_max_boost); } function setLockedStakeTimeForMinAndMaxMultiplier(uint256 _lock_time_for_max_multiplier, uint256 _lock_time_min) external onlyByOwnerOrGovernance { require(_lock_time_for_max_multiplier >= 1, "Multiplier Max Time must be greater than or equal to 1"); require(_lock_time_min >= 1, "Multiplier Min Time must be greater than or equal to 1"); lock_time_for_max_multiplier = _lock_time_for_max_multiplier; lock_time_min = _lock_time_min; emit LockedStakeTimeForMaxMultiplier(lock_time_for_max_multiplier); emit LockedStakeMinTime(_lock_time_min); } function initializeDefault() external onlyByOwnerOrGovernance { lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardsDuration); emit DefaultInitialization(); } function greylistAddress(address _address) external onlyByOwnerOrGovernance { greylist[_address] = !(greylist[_address]); } function unlockStakes() external onlyByOwnerOrGovernance { stakesUnlocked = !stakesUnlocked; } function toggleMigrations() external onlyByOwnerOrGovernance { migrationsOn = !migrationsOn; } function toggleStaking() external onlyByOwnerOrGovernance { stakingPaused = !stakingPaused; } function toggleWithdrawals() external onlyByOwnerOrGovernance { withdrawalsPaused = !withdrawalsPaused; } function toggleRewardsCollection() external onlyByOwnerOrGovernance { rewardsCollectionPaused = !rewardsCollectionPaused; } function setRewardRates(uint256 _new_rate0, uint256 _new_rate1, bool sync_too) external onlyByOwnerOrGovernance { rewardRate0 = _new_rate0; rewardRate1 = _new_rate1; if (sync_too){ sync(); } } function toggleToken1Rewards() external onlyByOwnerOrGovernance { if (token1_rewards_on) { rewardRate1 = 0; } token1_rewards_on = !token1_rewards_on; } function setTimelock(address _new_timelock) external onlyByOwnerOrGovernance { timelock_address = _new_timelock; } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event StakeLocked(address indexed user, uint256 amount, uint256 secs, bytes32 kek_id, address source_address); event WithdrawLocked(address indexed user, uint256 amount, bytes32 kek_id, address destination_address); event RewardPaid(address indexed user, uint256 reward, address token_address, address destination_address); event RewardsDurationUpdated(uint256 newDuration); event Recovered(address token, uint256 amount); event RewardsPeriodRenewed(address token); event DefaultInitialization(); event LockedStakeMaxMultiplierUpdated(uint256 multiplier); event LockedStakeTimeForMaxMultiplier(uint256 secs); event LockedStakeMinTime(uint256 secs); event MaxVeFXSMultiplier(uint256 multiplier); event veFXSPerFraxForMaxBoostUpdated(uint256 scale_factor); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; /** * @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; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; interface IveFXS { struct LockedBalance { int128 amount; uint256 end; } /* ========== VIEWS ========== */ function balanceOf(address addr) external view returns (uint256); function balanceOf(address addr, uint256 _t) external view returns (uint256); function balanceOfAt(address addr, uint256 _block) external returns (uint256); function totalSupply() external view returns (uint256); function totalSupply(uint256 t) external view returns (uint256); function totalSupplyAt(uint256 _block) external returns (uint256); function totalFXSSupply() external view returns (uint256); function totalFXSSupplyAt(uint256 _block) external view returns (uint256); function locked(address addr) external view returns (LockedBalance memory); /* ========== PUBLIC FUNCTIONS ========== */ function checkpoint() external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import "../Common/Context.sol"; import "./IERC20.sol"; import "../Math/SafeMath.sol"; import "../Utils/Address.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; 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.approve(address spender, uint256 amount) */ 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 the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for `accounts`'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } /** * @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 Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal virtual { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } /** * @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:using-hooks.adoc[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; // 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, uint 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: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint 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: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint 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: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import "./IERC20.sol"; import "../Math/SafeMath.sol"; import "../Utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ======================= FRAXStablecoin (FRAX) ====================== // ==================================================================== // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian // Reviewer(s) / Contributor(s) // Sam Sun: https://github.com/samczsun import "../Common/Context.sol"; import "../ERC20/IERC20.sol"; import "../ERC20/ERC20Custom.sol"; import "../ERC20/ERC20.sol"; import "../Math/SafeMath.sol"; import "../Staking/Owned.sol"; import "../FXS/FXS.sol"; import "./Pools/FraxPool.sol"; import "../Oracle/UniswapPairOracle.sol"; import "../Oracle/ChainlinkETHUSDPriceConsumer.sol"; import "../Governance/AccessControl.sol"; contract FRAXStablecoin is ERC20Custom, AccessControl, Owned { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ enum PriceChoice { FRAX, FXS } ChainlinkETHUSDPriceConsumer private eth_usd_pricer; uint8 private eth_usd_pricer_decimals; UniswapPairOracle private fraxEthOracle; UniswapPairOracle private fxsEthOracle; string public symbol; string public name; uint8 public constant decimals = 18; address public creator_address; address public timelock_address; // Governance timelock address address public controller_address; // Controller contract to dynamically adjust system parameters automatically address public fxs_address; address public frax_eth_oracle_address; address public fxs_eth_oracle_address; address public weth_address; address public eth_usd_consumer_address; uint256 public constant genesis_supply = 2000000e18; // 2M FRAX (only for testing, genesis supply will be 5k on Mainnet). This is to help with establishing the Uniswap pools, as they need liquidity // The addresses in this array are added by the oracle and these contracts are able to mint frax address[] public frax_pools_array; // Mapping is also used for faster verification mapping(address => bool) public frax_pools; // Constants for various precisions uint256 private constant PRICE_PRECISION = 1e6; uint256 public global_collateral_ratio; // 6 decimals of precision, e.g. 924102 = 0.924102 uint256 public redemption_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee uint256 public minting_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee uint256 public frax_step; // Amount to change the collateralization ratio by upon refreshCollateralRatio() uint256 public refresh_cooldown; // Seconds to wait before being able to run refreshCollateralRatio() again uint256 public price_target; // The price of FRAX at which the collateral ratio will respond to; this value is only used for the collateral ratio mechanism and not for minting and redeeming which are hardcoded at $1 uint256 public price_band; // The bound above and below the price target at which the refreshCollateralRatio() will not change the collateral ratio address public DEFAULT_ADMIN_ADDRESS; bytes32 public constant COLLATERAL_RATIO_PAUSER = keccak256("COLLATERAL_RATIO_PAUSER"); bool public collateral_ratio_paused = false; /* ========== MODIFIERS ========== */ modifier onlyCollateralRatioPauser() { require(hasRole(COLLATERAL_RATIO_PAUSER, msg.sender)); _; } modifier onlyPools() { require(frax_pools[msg.sender] == true, "Only frax pools can call this function"); _; } modifier onlyByOwnerOrGovernance() { require(msg.sender == owner || msg.sender == timelock_address || msg.sender == controller_address, "You are not the owner, controller, or the governance timelock"); _; } modifier onlyByOwnerGovernanceOrPool() { require( msg.sender == owner || msg.sender == timelock_address || frax_pools[msg.sender] == true, "You are not the owner, the governance timelock, or a pool"); _; } /* ========== CONSTRUCTOR ========== */ constructor( string memory _name, string memory _symbol, address _creator_address, address _timelock_address ) public Owned(_creator_address){ require(_timelock_address != address(0), "Zero address detected"); name = _name; symbol = _symbol; creator_address = _creator_address; timelock_address = _timelock_address; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); DEFAULT_ADMIN_ADDRESS = _msgSender(); _mint(creator_address, genesis_supply); grantRole(COLLATERAL_RATIO_PAUSER, creator_address); grantRole(COLLATERAL_RATIO_PAUSER, timelock_address); frax_step = 2500; // 6 decimals of precision, equal to 0.25% global_collateral_ratio = 1000000; // Frax system starts off fully collateralized (6 decimals of precision) refresh_cooldown = 3600; // Refresh cooldown period is set to 1 hour (3600 seconds) at genesis price_target = 1000000; // Collateral ratio will adjust according to the $1 price target at genesis price_band = 5000; // Collateral ratio will not adjust if between $0.995 and $1.005 at genesis } /* ========== VIEWS ========== */ // Choice = 'FRAX' or 'FXS' for now function oracle_price(PriceChoice choice) internal view returns (uint256) { // Get the ETH / USD price first, and cut it down to 1e6 precision uint256 __eth_usd_price = uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals); uint256 price_vs_eth = 0; if (choice == PriceChoice.FRAX) { price_vs_eth = uint256(fraxEthOracle.consult(weth_address, PRICE_PRECISION)); // How much FRAX if you put in PRICE_PRECISION WETH } else if (choice == PriceChoice.FXS) { price_vs_eth = uint256(fxsEthOracle.consult(weth_address, PRICE_PRECISION)); // How much FXS if you put in PRICE_PRECISION WETH } else revert("INVALID PRICE CHOICE. Needs to be either 0 (FRAX) or 1 (FXS)"); // Will be in 1e6 format return __eth_usd_price.mul(PRICE_PRECISION).div(price_vs_eth); } // Returns X FRAX = 1 USD function frax_price() public view returns (uint256) { return oracle_price(PriceChoice.FRAX); } // Returns X FXS = 1 USD function fxs_price() public view returns (uint256) { return oracle_price(PriceChoice.FXS); } function eth_usd_price() public view returns (uint256) { return uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals); } // This is needed to avoid costly repeat calls to different getter functions // It is cheaper gas-wise to just dump everything and only use some of the info function frax_info() public view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) { return ( oracle_price(PriceChoice.FRAX), // frax_price() oracle_price(PriceChoice.FXS), // fxs_price() totalSupply(), // totalSupply() global_collateral_ratio, // global_collateral_ratio() globalCollateralValue(), // globalCollateralValue minting_fee, // minting_fee() redemption_fee, // redemption_fee() uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals) //eth_usd_price ); } // Iterate through all frax pools and calculate all value of collateral in all pools globally function globalCollateralValue() public view returns (uint256) { uint256 total_collateral_value_d18 = 0; for (uint i = 0; i < frax_pools_array.length; i++){ // Exclude null addresses if (frax_pools_array[i] != address(0)){ total_collateral_value_d18 = total_collateral_value_d18.add(FraxPool(frax_pools_array[i]).collatDollarBalance()); } } return total_collateral_value_d18; } /* ========== PUBLIC FUNCTIONS ========== */ // There needs to be a time interval that this can be called. Otherwise it can be called multiple times per expansion. uint256 public last_call_time; // Last time the refreshCollateralRatio function was called function refreshCollateralRatio() public { require(collateral_ratio_paused == false, "Collateral Ratio has been paused"); uint256 frax_price_cur = frax_price(); require(block.timestamp - last_call_time >= refresh_cooldown, "Must wait for the refresh cooldown since last refresh"); // Step increments are 0.25% (upon genesis, changable by setFraxStep()) if (frax_price_cur > price_target.add(price_band)) { //decrease collateral ratio if(global_collateral_ratio <= frax_step){ //if within a step of 0, go to 0 global_collateral_ratio = 0; } else { global_collateral_ratio = global_collateral_ratio.sub(frax_step); } } else if (frax_price_cur < price_target.sub(price_band)) { //increase collateral ratio if(global_collateral_ratio.add(frax_step) >= 1000000){ global_collateral_ratio = 1000000; // cap collateral ratio at 1.000000 } else { global_collateral_ratio = global_collateral_ratio.add(frax_step); } } last_call_time = block.timestamp; // Set the time of the last expansion emit CollateralRatioRefreshed(global_collateral_ratio); } /* ========== RESTRICTED FUNCTIONS ========== */ // Used by pools when user redeems function pool_burn_from(address b_address, uint256 b_amount) public onlyPools { super._burnFrom(b_address, b_amount); emit FRAXBurned(b_address, msg.sender, b_amount); } // This function is what other frax pools will call to mint new FRAX function pool_mint(address m_address, uint256 m_amount) public onlyPools { super._mint(m_address, m_amount); emit FRAXMinted(msg.sender, m_address, m_amount); } // Adds collateral addresses supported, such as tether and busd, must be ERC20 function addPool(address pool_address) public onlyByOwnerOrGovernance { require(pool_address != address(0), "Zero address detected"); require(frax_pools[pool_address] == false, "address already exists"); frax_pools[pool_address] = true; frax_pools_array.push(pool_address); emit PoolAdded(pool_address); } // Remove a pool function removePool(address pool_address) public onlyByOwnerOrGovernance { require(pool_address != address(0), "Zero address detected"); require(frax_pools[pool_address] == true, "address doesn't exist already"); // Delete from the mapping delete frax_pools[pool_address]; // 'Delete' from the array by setting the address to 0x0 for (uint i = 0; i < frax_pools_array.length; i++){ if (frax_pools_array[i] == pool_address) { frax_pools_array[i] = address(0); // This will leave a null in the array and keep the indices the same break; } } emit PoolRemoved(pool_address); } function setRedemptionFee(uint256 red_fee) public onlyByOwnerOrGovernance { redemption_fee = red_fee; emit RedemptionFeeSet(red_fee); } function setMintingFee(uint256 min_fee) public onlyByOwnerOrGovernance { minting_fee = min_fee; emit MintingFeeSet(min_fee); } function setFraxStep(uint256 _new_step) public onlyByOwnerOrGovernance { frax_step = _new_step; emit FraxStepSet(_new_step); } function setPriceTarget (uint256 _new_price_target) public onlyByOwnerOrGovernance { price_target = _new_price_target; emit PriceTargetSet(_new_price_target); } function setRefreshCooldown(uint256 _new_cooldown) public onlyByOwnerOrGovernance { refresh_cooldown = _new_cooldown; emit RefreshCooldownSet(_new_cooldown); } function setFXSAddress(address _fxs_address) public onlyByOwnerOrGovernance { require(_fxs_address != address(0), "Zero address detected"); fxs_address = _fxs_address; emit FXSAddressSet(_fxs_address); } function setETHUSDOracle(address _eth_usd_consumer_address) public onlyByOwnerOrGovernance { require(_eth_usd_consumer_address != address(0), "Zero address detected"); eth_usd_consumer_address = _eth_usd_consumer_address; eth_usd_pricer = ChainlinkETHUSDPriceConsumer(eth_usd_consumer_address); eth_usd_pricer_decimals = eth_usd_pricer.getDecimals(); emit ETHUSDOracleSet(_eth_usd_consumer_address); } function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { require(new_timelock != address(0), "Zero address detected"); timelock_address = new_timelock; emit TimelockSet(new_timelock); } function setController(address _controller_address) external onlyByOwnerOrGovernance { require(_controller_address != address(0), "Zero address detected"); controller_address = _controller_address; emit ControllerSet(_controller_address); } function setPriceBand(uint256 _price_band) external onlyByOwnerOrGovernance { price_band = _price_band; emit PriceBandSet(_price_band); } // Sets the FRAX_ETH Uniswap oracle address function setFRAXEthOracle(address _frax_oracle_addr, address _weth_address) public onlyByOwnerOrGovernance { require((_frax_oracle_addr != address(0)) && (_weth_address != address(0)), "Zero address detected"); frax_eth_oracle_address = _frax_oracle_addr; fraxEthOracle = UniswapPairOracle(_frax_oracle_addr); weth_address = _weth_address; emit FRAXETHOracleSet(_frax_oracle_addr, _weth_address); } // Sets the FXS_ETH Uniswap oracle address function setFXSEthOracle(address _fxs_oracle_addr, address _weth_address) public onlyByOwnerOrGovernance { require((_fxs_oracle_addr != address(0)) && (_weth_address != address(0)), "Zero address detected"); fxs_eth_oracle_address = _fxs_oracle_addr; fxsEthOracle = UniswapPairOracle(_fxs_oracle_addr); weth_address = _weth_address; emit FXSEthOracleSet(_fxs_oracle_addr, _weth_address); } function toggleCollateralRatio() public onlyCollateralRatioPauser { collateral_ratio_paused = !collateral_ratio_paused; emit CollateralRatioToggled(collateral_ratio_paused); } /* ========== EVENTS ========== */ // Track FRAX burned event FRAXBurned(address indexed from, address indexed to, uint256 amount); // Track FRAX minted event FRAXMinted(address indexed from, address indexed to, uint256 amount); event CollateralRatioRefreshed(uint256 global_collateral_ratio); event PoolAdded(address pool_address); event PoolRemoved(address pool_address); event RedemptionFeeSet(uint256 red_fee); event MintingFeeSet(uint256 min_fee); event FraxStepSet(uint256 new_step); event PriceTargetSet(uint256 new_price_target); event RefreshCooldownSet(uint256 new_cooldown); event FXSAddressSet(address _fxs_address); event ETHUSDOracleSet(address eth_usd_consumer_address); event TimelockSet(address new_timelock); event ControllerSet(address controller_address); event PriceBandSet(uint256 price_band); event FRAXETHOracleSet(address frax_oracle_addr, address weth_address); event FXSEthOracleSet(address fxs_oracle_addr, address weth_address); event CollateralRatioToggled(bool collateral_ratio_paused); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; // https://docs.synthetix.io/contracts/Owned contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require(msg.sender == owner, "Only the contract owner may perform this action"); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; /* * @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; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import "../Common/Context.sol"; import "../Math/SafeMath.sol"; /** * @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); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11 <0.9.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import "../Common/Context.sol"; import "./IERC20.sol"; import "../Math/SafeMath.sol"; import "../Utils/Address.sol"; // Due to compiling issues, _name, _symbol, and _decimals were removed /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Custom is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 private _totalSupply; /** * @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.approve(address spender, uint256 amount) */ 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 the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for `accounts`'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } /** * @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 Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal virtual { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } /** * @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:using-hooks.adoc[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ========================= FRAXShares (FXS) ========================= // ==================================================================== // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian // Reviewer(s) / Contributor(s) // Sam Sun: https://github.com/samczsun import "../Common/Context.sol"; import "../ERC20/ERC20Custom.sol"; import "../ERC20/IERC20.sol"; import "../Frax/Frax.sol"; import "../Staking/Owned.sol"; import "../Math/SafeMath.sol"; import "../Governance/AccessControl.sol"; contract FRAXShares is ERC20Custom, AccessControl, Owned { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ string public symbol; string public name; uint8 public constant decimals = 18; address public FRAXStablecoinAdd; uint256 public constant genesis_supply = 100000000e18; // 100M is printed upon genesis address public oracle_address; address public timelock_address; // Governance timelock address FRAXStablecoin private FRAX; bool public trackingVotes = true; // Tracking votes (only change if need to disable votes) // A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } // A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; // The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /* ========== MODIFIERS ========== */ modifier onlyPools() { require(FRAX.frax_pools(msg.sender) == true, "Only frax pools can mint new FRAX"); _; } modifier onlyByOwnerOrGovernance() { require(msg.sender == owner || msg.sender == timelock_address, "You are not an owner or the governance timelock"); _; } /* ========== CONSTRUCTOR ========== */ constructor( string memory _name, string memory _symbol, address _oracle_address, address _creator_address, address _timelock_address ) public Owned(_creator_address){ require((_oracle_address != address(0)) && (_timelock_address != address(0)), "Zero address detected"); name = _name; symbol = _symbol; oracle_address = _oracle_address; timelock_address = _timelock_address; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _mint(_creator_address, genesis_supply); // Do a checkpoint for the owner _writeCheckpoint(_creator_address, 0, 0, uint96(genesis_supply)); } /* ========== RESTRICTED FUNCTIONS ========== */ function setOracle(address new_oracle) external onlyByOwnerOrGovernance { require(new_oracle != address(0), "Zero address detected"); oracle_address = new_oracle; } function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { require(new_timelock != address(0), "Timelock address cannot be 0"); timelock_address = new_timelock; } function setFRAXAddress(address frax_contract_address) external onlyByOwnerOrGovernance { require(frax_contract_address != address(0), "Zero address detected"); FRAX = FRAXStablecoin(frax_contract_address); emit FRAXAddressSet(frax_contract_address); } function mint(address to, uint256 amount) public onlyPools { _mint(to, amount); } // This function is what other frax pools will call to mint new FXS (similar to the FRAX mint) function pool_mint(address m_address, uint256 m_amount) external onlyPools { if(trackingVotes){ uint32 srcRepNum = numCheckpoints[address(this)]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[address(this)][srcRepNum - 1].votes : 0; uint96 srcRepNew = add96(srcRepOld, uint96(m_amount), "pool_mint new votes overflows"); _writeCheckpoint(address(this), srcRepNum, srcRepOld, srcRepNew); // mint new votes trackVotes(address(this), m_address, uint96(m_amount)); } super._mint(m_address, m_amount); emit FXSMinted(address(this), m_address, m_amount); } // This function is what other frax pools will call to burn FXS function pool_burn_from(address b_address, uint256 b_amount) external onlyPools { if(trackingVotes){ trackVotes(b_address, address(this), uint96(b_amount)); uint32 srcRepNum = numCheckpoints[address(this)]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[address(this)][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, uint96(b_amount), "pool_burn_from new votes underflows"); _writeCheckpoint(address(this), srcRepNum, srcRepOld, srcRepNew); // burn votes } super._burnFrom(b_address, b_amount); emit FXSBurned(b_address, address(this), b_amount); } function toggleVotes() external onlyByOwnerOrGovernance { trackingVotes = !trackingVotes; } /* ========== OVERRIDDEN PUBLIC FUNCTIONS ========== */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { if(trackingVotes){ // Transfer votes trackVotes(_msgSender(), recipient, uint96(amount)); } _transfer(_msgSender(), recipient, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { if(trackingVotes){ // Transfer votes trackVotes(sender, recipient, uint96(amount)); } _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /* ========== PUBLIC FUNCTIONS ========== */ /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "FXS::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } /* ========== INTERNAL FUNCTIONS ========== */ // From compound's _moveDelegates // Keep track of votes. "Delegates" is a misnomer here function trackVotes(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "FXS::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "FXS::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address voter, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "FXS::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[voter][nCheckpoints - 1].votes = newVotes; } else { checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[voter] = nCheckpoints + 1; } emit VoterVotesChanged(voter, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } /* ========== EVENTS ========== */ /// @notice An event thats emitted when a voters account's vote balance changes event VoterVotesChanged(address indexed voter, uint previousBalance, uint newBalance); // Track FXS burned event FXSBurned(address indexed from, address indexed to, uint256 amount); // Track FXS minted event FXSMinted(address indexed from, address indexed to, uint256 amount); event FRAXAddressSet(address addr); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ============================= FraxPool ============================= // ==================================================================== // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian // Reviewer(s) / Contributor(s) // Sam Sun: https://github.com/samczsun import "../../Math/SafeMath.sol"; import '../../Uniswap/TransferHelper.sol'; import "../../Staking/Owned.sol"; import "../../FXS/FXS.sol"; import "../../Frax/Frax.sol"; import "../../ERC20/ERC20.sol"; import "../../Oracle/UniswapPairOracle.sol"; import "../../Governance/AccessControl.sol"; import "./FraxPoolLibrary.sol"; contract FraxPool is AccessControl, Owned { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ ERC20 private collateral_token; address private collateral_address; address private frax_contract_address; address private fxs_contract_address; address private timelock_address; FRAXShares private FXS; FRAXStablecoin private FRAX; UniswapPairOracle private collatEthOracle; address public collat_eth_oracle_address; address private weth_address; uint256 public minting_fee; uint256 public redemption_fee; uint256 public buyback_fee; uint256 public recollat_fee; mapping (address => uint256) public redeemFXSBalances; mapping (address => uint256) public redeemCollateralBalances; uint256 public unclaimedPoolCollateral; uint256 public unclaimedPoolFXS; mapping (address => uint256) public lastRedeemed; // Constants for various precisions uint256 private constant PRICE_PRECISION = 1e6; uint256 private constant COLLATERAL_RATIO_PRECISION = 1e6; uint256 private constant COLLATERAL_RATIO_MAX = 1e6; // Number of decimals needed to get to 18 uint256 private immutable missing_decimals; // Pool_ceiling is the total units of collateral that a pool contract can hold uint256 public pool_ceiling = 0; // Stores price of the collateral, if price is paused uint256 public pausedPrice = 0; // Bonus rate on FXS minted during recollateralizeFRAX(); 6 decimals of precision, set to 0.75% on genesis uint256 public bonus_rate = 7500; // Number of blocks to wait before being able to collectRedemption() uint256 public redemption_delay = 1; // AccessControl Roles bytes32 private constant MINT_PAUSER = keccak256("MINT_PAUSER"); bytes32 private constant REDEEM_PAUSER = keccak256("REDEEM_PAUSER"); bytes32 private constant BUYBACK_PAUSER = keccak256("BUYBACK_PAUSER"); bytes32 private constant RECOLLATERALIZE_PAUSER = keccak256("RECOLLATERALIZE_PAUSER"); bytes32 private constant COLLATERAL_PRICE_PAUSER = keccak256("COLLATERAL_PRICE_PAUSER"); // AccessControl state variables bool public mintPaused = false; bool public redeemPaused = false; bool public recollateralizePaused = false; bool public buyBackPaused = false; bool public collateralPricePaused = false; /* ========== MODIFIERS ========== */ modifier onlyByOwnerOrGovernance() { require(msg.sender == timelock_address || msg.sender == owner, "You are not the owner or the governance timelock"); _; } modifier notRedeemPaused() { require(redeemPaused == false, "Redeeming is paused"); _; } modifier notMintPaused() { require(mintPaused == false, "Minting is paused"); _; } /* ========== CONSTRUCTOR ========== */ constructor( address _frax_contract_address, address _fxs_contract_address, address _collateral_address, address _creator_address, address _timelock_address, uint256 _pool_ceiling ) public Owned(_creator_address){ require( (_frax_contract_address != address(0)) && (_fxs_contract_address != address(0)) && (_collateral_address != address(0)) && (_creator_address != address(0)) && (_timelock_address != address(0)) , "Zero address detected"); FRAX = FRAXStablecoin(_frax_contract_address); FXS = FRAXShares(_fxs_contract_address); frax_contract_address = _frax_contract_address; fxs_contract_address = _fxs_contract_address; collateral_address = _collateral_address; timelock_address = _timelock_address; collateral_token = ERC20(_collateral_address); pool_ceiling = _pool_ceiling; missing_decimals = uint(18).sub(collateral_token.decimals()); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); grantRole(MINT_PAUSER, timelock_address); grantRole(REDEEM_PAUSER, timelock_address); grantRole(RECOLLATERALIZE_PAUSER, timelock_address); grantRole(BUYBACK_PAUSER, timelock_address); grantRole(COLLATERAL_PRICE_PAUSER, timelock_address); } /* ========== VIEWS ========== */ // Returns dollar value of collateral held in this Frax pool function collatDollarBalance() public view returns (uint256) { if(collateralPricePaused == true){ return (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)).mul(10 ** missing_decimals).mul(pausedPrice).div(PRICE_PRECISION); } else { uint256 eth_usd_price = FRAX.eth_usd_price(); uint256 eth_collat_price = collatEthOracle.consult(weth_address, (PRICE_PRECISION * (10 ** missing_decimals))); uint256 collat_usd_price = eth_usd_price.mul(PRICE_PRECISION).div(eth_collat_price); return (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)).mul(10 ** missing_decimals).mul(collat_usd_price).div(PRICE_PRECISION); //.mul(getCollateralPrice()).div(1e6); } } // Returns the value of excess collateral held in this Frax pool, compared to what is needed to maintain the global collateral ratio function availableExcessCollatDV() public view returns (uint256) { uint256 total_supply = FRAX.totalSupply(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); uint256 global_collat_value = FRAX.globalCollateralValue(); if (global_collateral_ratio > COLLATERAL_RATIO_PRECISION) global_collateral_ratio = COLLATERAL_RATIO_PRECISION; // Handles an overcollateralized contract with CR > 1 uint256 required_collat_dollar_value_d18 = (total_supply.mul(global_collateral_ratio)).div(COLLATERAL_RATIO_PRECISION); // Calculates collateral needed to back each 1 FRAX with $1 of collateral at current collat ratio if (global_collat_value > required_collat_dollar_value_d18) return global_collat_value.sub(required_collat_dollar_value_d18); else return 0; } /* ========== PUBLIC FUNCTIONS ========== */ // Returns the price of the pool collateral in USD function getCollateralPrice() public view returns (uint256) { if(collateralPricePaused == true){ return pausedPrice; } else { uint256 eth_usd_price = FRAX.eth_usd_price(); return eth_usd_price.mul(PRICE_PRECISION).div(collatEthOracle.consult(weth_address, PRICE_PRECISION * (10 ** missing_decimals))); } } function setCollatETHOracle(address _collateral_weth_oracle_address, address _weth_address) external onlyByOwnerOrGovernance { collat_eth_oracle_address = _collateral_weth_oracle_address; collatEthOracle = UniswapPairOracle(_collateral_weth_oracle_address); weth_address = _weth_address; } // We separate out the 1t1, fractional and algorithmic minting functions for gas efficiency function mint1t1FRAX(uint256 collateral_amount, uint256 FRAX_out_min) external notMintPaused { uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); require(FRAX.global_collateral_ratio() >= COLLATERAL_RATIO_MAX, "Collateral ratio must be >= 1"); require((collateral_token.balanceOf(address(this))).sub(unclaimedPoolCollateral).add(collateral_amount) <= pool_ceiling, "[Pool's Closed]: Ceiling reached"); (uint256 frax_amount_d18) = FraxPoolLibrary.calcMint1t1FRAX( getCollateralPrice(), collateral_amount_d18 ); //1 FRAX for each $1 worth of collateral frax_amount_d18 = (frax_amount_d18.mul(uint(1e6).sub(minting_fee))).div(1e6); //remove precision at the end require(FRAX_out_min <= frax_amount_d18, "Slippage limit reached"); TransferHelper.safeTransferFrom(address(collateral_token), msg.sender, address(this), collateral_amount); FRAX.pool_mint(msg.sender, frax_amount_d18); } // 0% collateral-backed function mintAlgorithmicFRAX(uint256 fxs_amount_d18, uint256 FRAX_out_min) external notMintPaused { uint256 fxs_price = FRAX.fxs_price(); require(FRAX.global_collateral_ratio() == 0, "Collateral ratio must be 0"); (uint256 frax_amount_d18) = FraxPoolLibrary.calcMintAlgorithmicFRAX( fxs_price, // X FXS / 1 USD fxs_amount_d18 ); frax_amount_d18 = (frax_amount_d18.mul(uint(1e6).sub(minting_fee))).div(1e6); require(FRAX_out_min <= frax_amount_d18, "Slippage limit reached"); FXS.pool_burn_from(msg.sender, fxs_amount_d18); FRAX.pool_mint(msg.sender, frax_amount_d18); } // Will fail if fully collateralized or fully algorithmic // > 0% and < 100% collateral-backed function mintFractionalFRAX(uint256 collateral_amount, uint256 fxs_amount, uint256 FRAX_out_min) external notMintPaused { uint256 fxs_price = FRAX.fxs_price(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999"); require(collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral).add(collateral_amount) <= pool_ceiling, "Pool ceiling reached, no more FRAX can be minted with this collateral"); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); FraxPoolLibrary.MintFF_Params memory input_params = FraxPoolLibrary.MintFF_Params( fxs_price, getCollateralPrice(), fxs_amount, collateral_amount_d18, global_collateral_ratio ); (uint256 mint_amount, uint256 fxs_needed) = FraxPoolLibrary.calcMintFractionalFRAX(input_params); mint_amount = (mint_amount.mul(uint(1e6).sub(minting_fee))).div(1e6); require(FRAX_out_min <= mint_amount, "Slippage limit reached"); require(fxs_needed <= fxs_amount, "Not enough FXS inputted"); FXS.pool_burn_from(msg.sender, fxs_needed); TransferHelper.safeTransferFrom(address(collateral_token), msg.sender, address(this), collateral_amount); FRAX.pool_mint(msg.sender, mint_amount); } // Redeem collateral. 100% collateral-backed function redeem1t1FRAX(uint256 FRAX_amount, uint256 COLLATERAL_out_min) external notRedeemPaused { require(FRAX.global_collateral_ratio() == COLLATERAL_RATIO_MAX, "Collateral ratio must be == 1"); // Need to adjust for decimals of collateral uint256 FRAX_amount_precision = FRAX_amount.div(10 ** missing_decimals); (uint256 collateral_needed) = FraxPoolLibrary.calcRedeem1t1FRAX( getCollateralPrice(), FRAX_amount_precision ); collateral_needed = (collateral_needed.mul(uint(1e6).sub(redemption_fee))).div(1e6); require(collateral_needed <= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), "Not enough collateral in pool"); require(COLLATERAL_out_min <= collateral_needed, "Slippage limit reached"); redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_needed); unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_needed); lastRedeemed[msg.sender] = block.number; // Move all external functions to the end FRAX.pool_burn_from(msg.sender, FRAX_amount); } // Will fail if fully collateralized or algorithmic // Redeem FRAX for collateral and FXS. > 0% and < 100% collateral-backed function redeemFractionalFRAX(uint256 FRAX_amount, uint256 FXS_out_min, uint256 COLLATERAL_out_min) external notRedeemPaused { uint256 fxs_price = FRAX.fxs_price(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999"); uint256 col_price_usd = getCollateralPrice(); uint256 FRAX_amount_post_fee = (FRAX_amount.mul(uint(1e6).sub(redemption_fee))).div(PRICE_PRECISION); uint256 fxs_dollar_value_d18 = FRAX_amount_post_fee.sub(FRAX_amount_post_fee.mul(global_collateral_ratio).div(PRICE_PRECISION)); uint256 fxs_amount = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(fxs_price); // Need to adjust for decimals of collateral uint256 FRAX_amount_precision = FRAX_amount_post_fee.div(10 ** missing_decimals); uint256 collateral_dollar_value = FRAX_amount_precision.mul(global_collateral_ratio).div(PRICE_PRECISION); uint256 collateral_amount = collateral_dollar_value.mul(PRICE_PRECISION).div(col_price_usd); require(collateral_amount <= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), "Not enough collateral in pool"); require(COLLATERAL_out_min <= collateral_amount, "Slippage limit reached [collateral]"); require(FXS_out_min <= fxs_amount, "Slippage limit reached [FXS]"); redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_amount); unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_amount); redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_amount); unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_amount); lastRedeemed[msg.sender] = block.number; // Move all external functions to the end FRAX.pool_burn_from(msg.sender, FRAX_amount); FXS.pool_mint(address(this), fxs_amount); } // Redeem FRAX for FXS. 0% collateral-backed function redeemAlgorithmicFRAX(uint256 FRAX_amount, uint256 FXS_out_min) external notRedeemPaused { uint256 fxs_price = FRAX.fxs_price(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); require(global_collateral_ratio == 0, "Collateral ratio must be 0"); uint256 fxs_dollar_value_d18 = FRAX_amount; fxs_dollar_value_d18 = (fxs_dollar_value_d18.mul(uint(1e6).sub(redemption_fee))).div(PRICE_PRECISION); //apply fees uint256 fxs_amount = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(fxs_price); redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_amount); unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_amount); lastRedeemed[msg.sender] = block.number; require(FXS_out_min <= fxs_amount, "Slippage limit reached"); // Move all external functions to the end FRAX.pool_burn_from(msg.sender, FRAX_amount); FXS.pool_mint(address(this), fxs_amount); } // After a redemption happens, transfer the newly minted FXS and owed collateral from this pool // contract to the user. Redemption is split into two functions to prevent flash loans from being able // to take out FRAX/collateral from the system, use an AMM to trade the new price, and then mint back into the system. function collectRedemption() external { require((lastRedeemed[msg.sender].add(redemption_delay)) <= block.number, "Must wait for redemption_delay blocks before collecting redemption"); bool sendFXS = false; bool sendCollateral = false; uint FXSAmount = 0; uint CollateralAmount = 0; // Use Checks-Effects-Interactions pattern if(redeemFXSBalances[msg.sender] > 0){ FXSAmount = redeemFXSBalances[msg.sender]; redeemFXSBalances[msg.sender] = 0; unclaimedPoolFXS = unclaimedPoolFXS.sub(FXSAmount); sendFXS = true; } if(redeemCollateralBalances[msg.sender] > 0){ CollateralAmount = redeemCollateralBalances[msg.sender]; redeemCollateralBalances[msg.sender] = 0; unclaimedPoolCollateral = unclaimedPoolCollateral.sub(CollateralAmount); sendCollateral = true; } if(sendFXS){ TransferHelper.safeTransfer(address(FXS), msg.sender, FXSAmount); } if(sendCollateral){ TransferHelper.safeTransfer(address(collateral_token), msg.sender, CollateralAmount); } } // When the protocol is recollateralizing, we need to give a discount of FXS to hit the new CR target // Thus, if the target collateral ratio is higher than the actual value of collateral, minters get FXS for adding collateral // This function simply rewards anyone that sends collateral to a pool with the same amount of FXS + the bonus rate // Anyone can call this function to recollateralize the protocol and take the extra FXS value from the bonus rate as an arb opportunity function recollateralizeFRAX(uint256 collateral_amount, uint256 FXS_out_min) external { require(recollateralizePaused == false, "Recollateralize is paused"); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); uint256 fxs_price = FRAX.fxs_price(); uint256 frax_total_supply = FRAX.totalSupply(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); uint256 global_collat_value = FRAX.globalCollateralValue(); (uint256 collateral_units, uint256 amount_to_recollat) = FraxPoolLibrary.calcRecollateralizeFRAXInner( collateral_amount_d18, getCollateralPrice(), global_collat_value, frax_total_supply, global_collateral_ratio ); uint256 collateral_units_precision = collateral_units.div(10 ** missing_decimals); uint256 fxs_paid_back = amount_to_recollat.mul(uint(1e6).add(bonus_rate).sub(recollat_fee)).div(fxs_price); require(FXS_out_min <= fxs_paid_back, "Slippage limit reached"); TransferHelper.safeTransferFrom(address(collateral_token), msg.sender, address(this), collateral_units_precision); FXS.pool_mint(msg.sender, fxs_paid_back); } // Function can be called by an FXS holder to have the protocol buy back FXS with excess collateral value from a desired collateral pool // This can also happen if the collateral ratio > 1 function buyBackFXS(uint256 FXS_amount, uint256 COLLATERAL_out_min) external { require(buyBackPaused == false, "Buyback is paused"); uint256 fxs_price = FRAX.fxs_price(); FraxPoolLibrary.BuybackFXS_Params memory input_params = FraxPoolLibrary.BuybackFXS_Params( availableExcessCollatDV(), fxs_price, getCollateralPrice(), FXS_amount ); (uint256 collateral_equivalent_d18) = (FraxPoolLibrary.calcBuyBackFXS(input_params)).mul(uint(1e6).sub(buyback_fee)).div(1e6); uint256 collateral_precision = collateral_equivalent_d18.div(10 ** missing_decimals); require(COLLATERAL_out_min <= collateral_precision, "Slippage limit reached"); // Give the sender their desired collateral and burn the FXS FXS.pool_burn_from(msg.sender, FXS_amount); TransferHelper.safeTransfer(address(collateral_token), msg.sender, collateral_precision); } /* ========== RESTRICTED FUNCTIONS ========== */ function toggleMinting() external { require(hasRole(MINT_PAUSER, msg.sender)); mintPaused = !mintPaused; emit MintingToggled(mintPaused); } function toggleRedeeming() external { require(hasRole(REDEEM_PAUSER, msg.sender)); redeemPaused = !redeemPaused; emit RedeemingToggled(redeemPaused); } function toggleRecollateralize() external { require(hasRole(RECOLLATERALIZE_PAUSER, msg.sender)); recollateralizePaused = !recollateralizePaused; emit RecollateralizeToggled(recollateralizePaused); } function toggleBuyBack() external { require(hasRole(BUYBACK_PAUSER, msg.sender)); buyBackPaused = !buyBackPaused; emit BuybackToggled(buyBackPaused); } function toggleCollateralPrice(uint256 _new_price) external { require(hasRole(COLLATERAL_PRICE_PAUSER, msg.sender)); // If pausing, set paused price; else if unpausing, clear pausedPrice if(collateralPricePaused == false){ pausedPrice = _new_price; } else { pausedPrice = 0; } collateralPricePaused = !collateralPricePaused; emit CollateralPriceToggled(collateralPricePaused); } // Combined into one function due to 24KiB contract memory limit function setPoolParameters(uint256 new_ceiling, uint256 new_bonus_rate, uint256 new_redemption_delay, uint256 new_mint_fee, uint256 new_redeem_fee, uint256 new_buyback_fee, uint256 new_recollat_fee) external onlyByOwnerOrGovernance { pool_ceiling = new_ceiling; bonus_rate = new_bonus_rate; redemption_delay = new_redemption_delay; minting_fee = new_mint_fee; redemption_fee = new_redeem_fee; buyback_fee = new_buyback_fee; recollat_fee = new_recollat_fee; emit PoolParametersSet(new_ceiling, new_bonus_rate, new_redemption_delay, new_mint_fee, new_redeem_fee, new_buyback_fee, new_recollat_fee); } function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { timelock_address = new_timelock; emit TimelockSet(new_timelock); } /* ========== EVENTS ========== */ event PoolParametersSet(uint256 new_ceiling, uint256 new_bonus_rate, uint256 new_redemption_delay, uint256 new_mint_fee, uint256 new_redeem_fee, uint256 new_buyback_fee, uint256 new_recollat_fee); event TimelockSet(address new_timelock); event MintingToggled(bool toggled); event RedeemingToggled(bool toggled); event RecollateralizeToggled(bool toggled); event BuybackToggled(bool toggled); event CollateralPriceToggled(bool toggled); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import '../Uniswap/Interfaces/IUniswapV2Factory.sol'; import '../Uniswap/Interfaces/IUniswapV2Pair.sol'; import '../Math/FixedPoint.sol'; import '../Uniswap/UniswapV2OracleLibrary.sol'; import '../Uniswap/UniswapV2Library.sol'; import "../Staking/Owned.sol"; // Fixed window oracle that recomputes the average price for the entire period once every period // Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period contract UniswapPairOracle is Owned { using FixedPoint for *; address timelock_address; uint public PERIOD = 3600; // 1 hour TWAP (time-weighted average price) uint public CONSULT_LENIENCY = 120; // Used for being able to consult past the period end bool public ALLOW_STALE_CONSULTS = false; // If false, consult() will fail if the TWAP is stale IUniswapV2Pair public immutable pair; address public immutable token0; address public immutable token1; uint public price0CumulativeLast; uint public price1CumulativeLast; uint32 public blockTimestampLast; FixedPoint.uq112x112 public price0Average; FixedPoint.uq112x112 public price1Average; modifier onlyByOwnerOrGovernance() { require(msg.sender == owner || msg.sender == timelock_address, "You are not an owner or the governance timelock"); _; } constructor(address factory, address tokenA, address tokenB, address _owner_address, address _timelock_address) public Owned(_owner_address) { IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, tokenA, tokenB)); pair = _pair; token0 = _pair.token0(); token1 = _pair.token1(); price0CumulativeLast = _pair.price0CumulativeLast(); // Fetch the current accumulated price value (1 / 0) price1CumulativeLast = _pair.price1CumulativeLast(); // Fetch the current accumulated price value (0 / 1) uint112 reserve0; uint112 reserve1; (reserve0, reserve1, blockTimestampLast) = _pair.getReserves(); require(reserve0 != 0 && reserve1 != 0, 'UniswapPairOracle: NO_RESERVES'); // Ensure that there's liquidity in the pair timelock_address = _timelock_address; } function setTimelock(address _timelock_address) external onlyByOwnerOrGovernance { timelock_address = _timelock_address; } function setPeriod(uint _period) external onlyByOwnerOrGovernance { PERIOD = _period; } function setConsultLeniency(uint _consult_leniency) external onlyByOwnerOrGovernance { CONSULT_LENIENCY = _consult_leniency; } function setAllowStaleConsults(bool _allow_stale_consults) external onlyByOwnerOrGovernance { ALLOW_STALE_CONSULTS = _allow_stale_consults; } // Check if update() can be called instead of wasting gas calling it function canUpdate() public view returns (bool) { uint32 blockTimestamp = UniswapV2OracleLibrary.currentBlockTimestamp(); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired return (timeElapsed >= PERIOD); } function update() external { (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(pair)); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired // Ensure that at least one full period has passed since the last update require(timeElapsed >= PERIOD, 'UniswapPairOracle: PERIOD_NOT_ELAPSED'); // Overflow is desired, casting never truncates // Cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast) / timeElapsed)); price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast) / timeElapsed)); price0CumulativeLast = price0Cumulative; price1CumulativeLast = price1Cumulative; blockTimestampLast = blockTimestamp; } // Note this will always return 0 before update has been called successfully for the first time. function consult(address token, uint amountIn) external view returns (uint amountOut) { uint32 blockTimestamp = UniswapV2OracleLibrary.currentBlockTimestamp(); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired // Ensure that the price is not stale require((timeElapsed < (PERIOD + CONSULT_LENIENCY)) || ALLOW_STALE_CONSULTS, 'UniswapPairOracle: PRICE_IS_STALE_NEED_TO_CALL_UPDATE'); if (token == token0) { amountOut = price0Average.mul(amountIn).decode144(); } else { require(token == token1, 'UniswapPairOracle: INVALID_TOKEN'); amountOut = price1Average.mul(amountIn).decode144(); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import "./AggregatorV3Interface.sol"; contract ChainlinkETHUSDPriceConsumer { AggregatorV3Interface internal priceFeed; constructor() public { priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419); } /** * Returns the latest price */ function getLatestPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; } function getDecimals() public view returns (uint8) { return priceFeed.decimals(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import "../Utils/EnumerableSet.sol"; import "../Utils/Address.sol"; import "../Common/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; //bytes32(uint256(0x4B437D01b575618140442A4975db38850e3f8f5f) << 96); /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import "../../Math/SafeMath.sol"; library FraxPoolLibrary { using SafeMath for uint256; // Constants for various precisions uint256 private constant PRICE_PRECISION = 1e6; // ================ Structs ================ // Needed to lower stack size struct MintFF_Params { uint256 fxs_price_usd; uint256 col_price_usd; uint256 fxs_amount; uint256 collateral_amount; uint256 col_ratio; } struct BuybackFXS_Params { uint256 excess_collateral_dollar_value_d18; uint256 fxs_price_usd; uint256 col_price_usd; uint256 FXS_amount; } // ================ Functions ================ function calcMint1t1FRAX(uint256 col_price, uint256 collateral_amount_d18) public pure returns (uint256) { return (collateral_amount_d18.mul(col_price)).div(1e6); } function calcMintAlgorithmicFRAX(uint256 fxs_price_usd, uint256 fxs_amount_d18) public pure returns (uint256) { return fxs_amount_d18.mul(fxs_price_usd).div(1e6); } // Must be internal because of the struct function calcMintFractionalFRAX(MintFF_Params memory params) internal pure returns (uint256, uint256) { // Since solidity truncates division, every division operation must be the last operation in the equation to ensure minimum error // The contract must check the proper ratio was sent to mint FRAX. We do this by seeing the minimum mintable FRAX based on each amount uint256 fxs_dollar_value_d18; uint256 c_dollar_value_d18; // Scoping for stack concerns { // USD amounts of the collateral and the FXS fxs_dollar_value_d18 = params.fxs_amount.mul(params.fxs_price_usd).div(1e6); c_dollar_value_d18 = params.collateral_amount.mul(params.col_price_usd).div(1e6); } uint calculated_fxs_dollar_value_d18 = (c_dollar_value_d18.mul(1e6).div(params.col_ratio)) .sub(c_dollar_value_d18); uint calculated_fxs_needed = calculated_fxs_dollar_value_d18.mul(1e6).div(params.fxs_price_usd); return ( c_dollar_value_d18.add(calculated_fxs_dollar_value_d18), calculated_fxs_needed ); } function calcRedeem1t1FRAX(uint256 col_price_usd, uint256 FRAX_amount) public pure returns (uint256) { return FRAX_amount.mul(1e6).div(col_price_usd); } // Must be internal because of the struct function calcBuyBackFXS(BuybackFXS_Params memory params) internal pure returns (uint256) { // If the total collateral value is higher than the amount required at the current collateral ratio then buy back up to the possible FXS with the desired collateral require(params.excess_collateral_dollar_value_d18 > 0, "No excess collateral to buy back!"); // Make sure not to take more than is available uint256 fxs_dollar_value_d18 = params.FXS_amount.mul(params.fxs_price_usd).div(1e6); require(fxs_dollar_value_d18 <= params.excess_collateral_dollar_value_d18, "You are trying to buy back more than the excess!"); // Get the equivalent amount of collateral based on the market value of FXS provided uint256 collateral_equivalent_d18 = fxs_dollar_value_d18.mul(1e6).div(params.col_price_usd); //collateral_equivalent_d18 = collateral_equivalent_d18.sub((collateral_equivalent_d18.mul(params.buyback_fee)).div(1e6)); return ( collateral_equivalent_d18 ); } // Returns value of collateral that must increase to reach recollateralization target (if 0 means no recollateralization) function recollateralizeAmount(uint256 total_supply, uint256 global_collateral_ratio, uint256 global_collat_value) public pure returns (uint256) { uint256 target_collat_value = total_supply.mul(global_collateral_ratio).div(1e6); // We want 18 decimals of precision so divide by 1e6; total_supply is 1e18 and global_collateral_ratio is 1e6 // Subtract the current value of collateral from the target value needed, if higher than 0 then system needs to recollateralize return target_collat_value.sub(global_collat_value); // If recollateralization is not needed, throws a subtraction underflow // return(recollateralization_left); } function calcRecollateralizeFRAXInner( uint256 collateral_amount, uint256 col_price, uint256 global_collat_value, uint256 frax_total_supply, uint256 global_collateral_ratio ) public pure returns (uint256, uint256) { uint256 collat_value_attempted = collateral_amount.mul(col_price).div(1e6); uint256 effective_collateral_ratio = global_collat_value.mul(1e6).div(frax_total_supply); //returns it in 1e6 uint256 recollat_possible = (global_collateral_ratio.mul(frax_total_supply).sub(frax_total_supply.mul(effective_collateral_ratio))).div(1e6); uint256 amount_to_recollat; if(collat_value_attempted <= recollat_possible){ amount_to_recollat = collat_value_attempted; } else { amount_to_recollat = recollat_possible; } return (amount_to_recollat.mul(1e6).div(col_price), amount_to_recollat); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; /** * @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(bytes20(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(bytes20(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(bytes20(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(bytes20(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; 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; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import './Babylonian.sol'; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint _x; } uint8 private constant RESOLUTION = 112; uint private constant Q112 = uint(1) << RESOLUTION; uint private constant Q224 = Q112 << RESOLUTION; // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { require(x != 0, 'FixedPoint: DIV_BY_ZERO'); return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { uint z; require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << RESOLUTION) / denominator); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } // take the reciprocal of a UQ112x112 function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL'); return uq112x112(uint224(Q224 / self._x)); } // square root of a UQ112x112 function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) << 56)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import '../Uniswap/Interfaces/IUniswapV2Pair.sol'; import '../Math/FixedPoint.sol'; // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices( address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import './Interfaces/IUniswapV2Pair.sol'; import './Interfaces/IUniswapV2Factory.sol'; import "../Math/SafeMath.sol"; library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // Less efficient than the CREATE2 method below function pairFor(address factory, address tokenA, address tokenB) internal view returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = IUniswapV2Factory(factory).getPair(token0, token1); } // calculates the CREATE2 address for a pair without making any external calls function pairForCreate2(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint160(bytes20(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash ))))); // this matches the CREATE2 in UniswapV2Factory.createPair } // 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, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(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, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(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, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(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, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i = 0; 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, 'UniswapV2Library: 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: MIT pragma solidity >=0.6.11; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } // else z = 0 } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); }
Remove a pool Delete from the mapping 'Delete' from the array by setting the address to 0x0
function removePool(address pool_address) public onlyByOwnerOrGovernance { require(pool_address != address(0), "Zero address detected"); require(frax_pools[pool_address] == true, "address doesn't exist already"); delete frax_pools[pool_address]; for (uint i = 0; i < frax_pools_array.length; i++){ if (frax_pools_array[i] == pool_address) { break; } } emit PoolRemoved(pool_address); for (uint i = 0; i < frax_pools_array.length; i++){ if (frax_pools_array[i] == pool_address) { break; } } emit PoolRemoved(pool_address); }
1,276,100
pragma solidity ^0.4.22; import "./IMoneyflow.sol"; import "./ether/WeiFund.sol"; import "../IDaoBase.sol"; import "zeppelin-solidity/contracts/ownership/Ownable.sol"; /** * @title FallbackToWeiReceiver * @dev Easy-to-use wrapper to convert fallback -> processFunds() * fallback -> processFunds */ contract FallbackToWeiReceiver { address output = 0x0; // _output should be IWeiReceiver constructor(address _output) public { output = _output; } function()public payable{ IWeiReceiver iwr = IWeiReceiver(output); iwr.processFunds.value(msg.value)(msg.value); } } /** * @title MoneyFlow * @dev Reference (typical example) implementation of IMoneyflow * Use it or modify as you like. Please see tests * No elements are directly available. Work with all children only throught the methods like * 'setRootWeiReceiverGeneric', etc */ contract MoneyFlow is IMoneyflow, DaoClient, Ownable { WeiFund donationEndpoint; // by default - this is 0x0, please use setWeiReceiver method // this can be a ISplitter (top-down or unsorted) IWeiReceiver rootReceiver; FallbackToWeiReceiver donationF2WR; FallbackToWeiReceiver revenueF2WR; event MoneyFlow_WithdrawDonations(address _by, address _to, uint _balance); event MoneyFlow_SetRootWeiReceiver(address _sender, address _receiver); constructor(IDaoBase _dao) public DaoClient(_dao) { // do not set output! donationEndpoint = new WeiFund(0x0, true, 10000); donationF2WR = new FallbackToWeiReceiver(donationEndpoint); } // IMoneyflow: // will withdraw donations function withdrawDonationsTo(address _out) external isCanDo("withdrawDonations"){ _withdrawDonationsTo(_out); } function _withdrawDonationsTo(address _out) internal{ emit MoneyFlow_WithdrawDonations(msg.sender, _out, address(donationEndpoint).balance); donationEndpoint.flushTo(_out); } function getDonationEndpoint()external constant returns(IWeiReceiver){ return donationEndpoint; } function getRevenueEndpoint()external constant returns(IWeiReceiver){ return rootReceiver; } function getDonationEndpointAddress()external constant returns(address){ return address(donationF2WR); } function getRevenueEndpointAddress()external constant returns(address){ return address(revenueF2WR); } function setRootWeiReceiverGeneric(bytes32[] _params) external { IWeiReceiver receiver = IWeiReceiver(address(_params[0])); _setRootWeiReceiver(receiver); } function withdrawDonationsToGeneric(bytes32[] _params) external { address out = address(_params[0]); _withdrawDonationsTo(out); } // WeiReceivers: // receiver can be a splitter, fund or event task // _receiver can be 0x0! function setRootWeiReceiver(IWeiReceiver _receiver) external isCanDo("setRootWeiReceiver"){ _setRootWeiReceiver(_receiver); } function _setRootWeiReceiver(IWeiReceiver _receiver) internal{ emit MoneyFlow_SetRootWeiReceiver(msg.sender, address(_receiver)); rootReceiver = _receiver; revenueF2WR = new FallbackToWeiReceiver(address(rootReceiver)); } /////////////////// function() public { // non payable } }
IMoneyflow: will withdraw donations
function withdrawDonationsTo(address _out) external isCanDo("withdrawDonations"){ _withdrawDonationsTo(_out); }
12,864,512
./partial_match/42/0xf1f7cd558E90269250f03706Db7144a53502439E/sources/compoundFarmer.sol
5. Unwrap WETH - amount input variable 5.2 approve mycontract to control the amount 5.3 Withdraw ETH tokens from WETH contract
function Unwrap (uint256 amount) internal { IWETH_Contract.approve(address(this), amount); IWETH_Contract.withdraw(amount); }
3,349,248
./partial_match/56/0xE4B16FE631CC2c51f27130a1732B6E9E222f6d01/sources/XUSD_TOKEN.sol
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 {BEP20-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 `XUSDtractedValue`./
function decreaseAllowance(address spender, uint256 XUSDtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].XUSD(XUSDtractedValue, 'BEP20: decreased allowance below zero')); return true; }
11,057,172
pragma solidity ^0.5.3; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "./interfaces/IExchange.sol"; import "./interfaces/ISortedOracles.sol"; import "./interfaces/IReserve.sol"; import "./interfaces/IStableToken.sol"; import "../common/Initializable.sol"; import "../common/FixidityLib.sol"; import "../common/Freezable.sol"; import "../common/UsingRegistry.sol"; import "../common/interfaces/ICeloVersionedContract.sol"; import "../common/libraries/ReentrancyGuard.sol"; /** * @title Contract that allows to exchange StableToken for GoldToken and vice versa * using a Constant Product Market Maker Model */ contract Exchange is IExchange, ICeloVersionedContract, Initializable, Ownable, UsingRegistry, ReentrancyGuard, Freezable { using SafeMath for uint256; using FixidityLib for FixidityLib.Fraction; event Exchanged(address indexed exchanger, uint256 sellAmount, uint256 buyAmount, bool soldGold); event UpdateFrequencySet(uint256 updateFrequency); event MinimumReportsSet(uint256 minimumReports); event StableTokenSet(address indexed stable); event SpreadSet(uint256 spread); event ReserveFractionSet(uint256 reserveFraction); event BucketsUpdated(uint256 goldBucket, uint256 stableBucket); FixidityLib.Fraction public spread; // Fraction of the Reserve that is committed to the gold bucket when updating // buckets. FixidityLib.Fraction public reserveFraction; address public stable; // Size of the Uniswap gold bucket uint256 public goldBucket; // Size of the Uniswap stable token bucket uint256 public stableBucket; uint256 public lastBucketUpdate = 0; uint256 public updateFrequency; uint256 public minimumReports; modifier updateBucketsIfNecessary() { _updateBucketsIfNecessary(); _; } /** * @notice Returns the storage, major, minor, and patch version of the contract. * @return The storage, major, minor, and patch version of the contract. */ function getVersionNumber() external pure returns (uint256, uint256, uint256, uint256) { return (1, 1, 1, 0); } /** * @notice Used in place of the constructor to allow the contract to be upgradable via proxy. * @param registryAddress The address of the registry core smart contract. * @param stableToken Address of the stable token * @param _spread Spread charged on exchanges * @param _reserveFraction Fraction to commit to the gold bucket * @param _updateFrequency The time period that needs to elapse between bucket * updates * @param _minimumReports The minimum number of fresh reports that need to be * present in the oracle to update buckets * commit to the gold bucket */ function initialize( address registryAddress, address stableToken, uint256 _spread, uint256 _reserveFraction, uint256 _updateFrequency, uint256 _minimumReports ) external initializer { _transferOwnership(msg.sender); setRegistry(registryAddress); setStableToken(stableToken); setSpread(_spread); setReserveFraction(_reserveFraction); setUpdateFrequency(_updateFrequency); setMinimumReports(_minimumReports); _updateBucketsIfNecessary(); } /** * @notice Exchanges a specific amount of one token for an unspecified amount * (greater than a threshold) of another. * @param sellAmount The number of tokens to send to the exchange. * @param minBuyAmount The minimum number of tokens for the exchange to send in return. * @param sellGold True if the caller is sending CELO to the exchange, false otherwise. * @return The number of tokens sent by the exchange. * @dev The caller must first have approved `sellAmount` to the exchange. * @dev This function can be frozen via the Freezable interface. */ function sell(uint256 sellAmount, uint256 minBuyAmount, bool sellGold) public onlyWhenNotFrozen updateBucketsIfNecessary nonReentrant returns (uint256) { (uint256 buyTokenBucket, uint256 sellTokenBucket) = _getBuyAndSellBuckets(sellGold); uint256 buyAmount = _getBuyTokenAmount(buyTokenBucket, sellTokenBucket, sellAmount); require(buyAmount >= minBuyAmount, "Calculated buyAmount was less than specified minBuyAmount"); _exchange(sellAmount, buyAmount, sellGold); return buyAmount; } /** * @dev DEPRECATED - Use `buy` or `sell`. * @notice Exchanges a specific amount of one token for an unspecified amount * (greater than a threshold) of another. * @param sellAmount The number of tokens to send to the exchange. * @param minBuyAmount The minimum number of tokens for the exchange to send in return. * @param sellGold True if the caller is sending CELO to the exchange, false otherwise. * @return The number of tokens sent by the exchange. * @dev The caller must first have approved `sellAmount` to the exchange. * @dev This function can be frozen via the Freezable interface. */ function exchange(uint256 sellAmount, uint256 minBuyAmount, bool sellGold) external returns (uint256) { return sell(sellAmount, minBuyAmount, sellGold); } /** * @notice Exchanges an unspecified amount (up to a threshold) of one token for * a specific amount of another. * @param buyAmount The number of tokens for the exchange to send in return. * @param maxSellAmount The maximum number of tokens to send to the exchange. * @param buyGold True if the exchange is sending CELO to the caller, false otherwise. * @return The number of tokens sent to the exchange. * @dev The caller must first have approved `maxSellAmount` to the exchange. * @dev This function can be frozen via the Freezable interface. */ function buy(uint256 buyAmount, uint256 maxSellAmount, bool buyGold) external onlyWhenNotFrozen updateBucketsIfNecessary nonReentrant returns (uint256) { bool sellGold = !buyGold; (uint256 buyTokenBucket, uint256 sellTokenBucket) = _getBuyAndSellBuckets(sellGold); uint256 sellAmount = _getSellTokenAmount(buyTokenBucket, sellTokenBucket, buyAmount); require( sellAmount <= maxSellAmount, "Calculated sellAmount was greater than specified maxSellAmount" ); _exchange(sellAmount, buyAmount, sellGold); return sellAmount; } /** * @notice Exchanges a specific amount of one token for a specific amount of another. * @param sellAmount The number of tokens to send to the exchange. * @param buyAmount The number of tokens for the exchange to send in return. * @param sellGold True if the msg.sender is sending CELO to the exchange, false otherwise. */ function _exchange(uint256 sellAmount, uint256 buyAmount, bool sellGold) private { IReserve reserve = IReserve(registry.getAddressForOrDie(RESERVE_REGISTRY_ID)); if (sellGold) { goldBucket = goldBucket.add(sellAmount); stableBucket = stableBucket.sub(buyAmount); require( getGoldToken().transferFrom(msg.sender, address(reserve), sellAmount), "Transfer of sell token failed" ); require(IStableToken(stable).mint(msg.sender, buyAmount), "Mint of stable token failed"); } else { stableBucket = stableBucket.add(sellAmount); goldBucket = goldBucket.sub(buyAmount); require( IERC20(stable).transferFrom(msg.sender, address(this), sellAmount), "Transfer of sell token failed" ); IStableToken(stable).burn(sellAmount); require(reserve.transferExchangeGold(msg.sender, buyAmount), "Transfer of buyToken failed"); } emit Exchanged(msg.sender, sellAmount, buyAmount, sellGold); } /** * @notice Returns the amount of buy tokens a user would get for sellAmount of the sell token. * @param sellAmount The amount of sellToken the user is selling to the exchange. * @param sellGold `true` if gold is the sell token. * @return The corresponding buyToken amount. */ function getBuyTokenAmount(uint256 sellAmount, bool sellGold) external view returns (uint256) { (uint256 buyTokenBucket, uint256 sellTokenBucket) = getBuyAndSellBuckets(sellGold); return _getBuyTokenAmount(buyTokenBucket, sellTokenBucket, sellAmount); } /** * @notice Returns the amount of sell tokens a user would need to exchange to receive buyAmount of * buy tokens. * @param buyAmount The amount of buyToken the user would like to purchase. * @param sellGold `true` if gold is the sell token. * @return The corresponding sellToken amount. */ function getSellTokenAmount(uint256 buyAmount, bool sellGold) external view returns (uint256) { (uint256 buyTokenBucket, uint256 sellTokenBucket) = getBuyAndSellBuckets(sellGold); return _getSellTokenAmount(buyTokenBucket, sellTokenBucket, buyAmount); } /** * @notice Returns the buy token and sell token bucket sizes, in order. The ratio of * the two also represents the exchange rate between the two. * @param sellGold `true` if gold is the sell token. * @return (buyTokenBucket, sellTokenBucket) */ function getBuyAndSellBuckets(bool sellGold) public view returns (uint256, uint256) { uint256 currentGoldBucket = goldBucket; uint256 currentStableBucket = stableBucket; if (shouldUpdateBuckets()) { (currentGoldBucket, currentStableBucket) = getUpdatedBuckets(); } if (sellGold) { return (currentStableBucket, currentGoldBucket); } else { return (currentGoldBucket, currentStableBucket); } } /** * @notice Allows owner to set the update frequency * @param newUpdateFrequency The new update frequency */ function setUpdateFrequency(uint256 newUpdateFrequency) public onlyOwner { updateFrequency = newUpdateFrequency; emit UpdateFrequencySet(newUpdateFrequency); } /** * @notice Allows owner to set the minimum number of reports required * @param newMininumReports The new update minimum number of reports required */ function setMinimumReports(uint256 newMininumReports) public onlyOwner { minimumReports = newMininumReports; emit MinimumReportsSet(newMininumReports); } /** * @notice Allows owner to set the Stable Token address * @param newStableToken The new address for Stable Token */ function setStableToken(address newStableToken) public onlyOwner { stable = newStableToken; emit StableTokenSet(newStableToken); } /** * @notice Allows owner to set the spread * @param newSpread The new value for the spread */ function setSpread(uint256 newSpread) public onlyOwner { spread = FixidityLib.wrap(newSpread); emit SpreadSet(newSpread); } /** * @notice Allows owner to set the Reserve Fraction * @param newReserveFraction The new value for the reserve fraction */ function setReserveFraction(uint256 newReserveFraction) public onlyOwner { reserveFraction = FixidityLib.wrap(newReserveFraction); require(reserveFraction.lt(FixidityLib.fixed1()), "reserve fraction must be smaller than 1"); emit ReserveFractionSet(newReserveFraction); } /** * @notice Returns the sell token and buy token bucket sizes, in order. The ratio of * the two also represents the exchange rate between the two. * @param sellGold `true` if gold is the sell token. * @return (sellTokenBucket, buyTokenBucket) */ function _getBuyAndSellBuckets(bool sellGold) private view returns (uint256, uint256) { if (sellGold) { return (stableBucket, goldBucket); } else { return (goldBucket, stableBucket); } } /** * @dev Returns the amount of buy tokens a user would get for sellAmount of the sell. * @param buyTokenBucket The buy token bucket size. * @param sellTokenBucket The sell token bucket size. * @param sellAmount The amount the user is selling to the exchange. * @return The corresponding buy amount. */ function _getBuyTokenAmount(uint256 buyTokenBucket, uint256 sellTokenBucket, uint256 sellAmount) private view returns (uint256) { if (sellAmount == 0) return 0; FixidityLib.Fraction memory reducedSellAmount = getReducedSellAmount(sellAmount); FixidityLib.Fraction memory numerator = reducedSellAmount.multiply( FixidityLib.newFixed(buyTokenBucket) ); FixidityLib.Fraction memory denominator = FixidityLib.newFixed(sellTokenBucket).add( reducedSellAmount ); // Can't use FixidityLib.divide because denominator can easily be greater // than maxFixedDivisor. // Fortunately, we expect an integer result, so integer division gives us as // much precision as we could hope for. return numerator.unwrap().div(denominator.unwrap()); } /** * @notice Returns the amount of sell tokens a user would need to exchange to receive buyAmount of * buy tokens. * @param buyTokenBucket The buy token bucket size. * @param sellTokenBucket The sell token bucket size. * @param buyAmount The amount the user is buying from the exchange. * @return The corresponding sell amount. */ function _getSellTokenAmount(uint256 buyTokenBucket, uint256 sellTokenBucket, uint256 buyAmount) private view returns (uint256) { if (buyAmount == 0) return 0; FixidityLib.Fraction memory numerator = FixidityLib.newFixed(buyAmount.mul(sellTokenBucket)); FixidityLib.Fraction memory denominator = FixidityLib .newFixed(buyTokenBucket.sub(buyAmount)) .multiply(FixidityLib.fixed1().subtract(spread)); // See comment in _getBuyTokenAmount return numerator.unwrap().div(denominator.unwrap()); } function getUpdatedBuckets() private view returns (uint256, uint256) { uint256 updatedGoldBucket = getUpdatedGoldBucket(); uint256 exchangeRateNumerator; uint256 exchangeRateDenominator; (exchangeRateNumerator, exchangeRateDenominator) = getOracleExchangeRate(); uint256 updatedStableBucket = exchangeRateNumerator.mul(updatedGoldBucket).div( exchangeRateDenominator ); return (updatedGoldBucket, updatedStableBucket); } function getUpdatedGoldBucket() private view returns (uint256) { uint256 reserveGoldBalance = getReserve().getUnfrozenReserveGoldBalance(); return reserveFraction.multiply(FixidityLib.newFixed(reserveGoldBalance)).fromFixed(); } /** * @notice If conditions are met, updates the Uniswap bucket sizes to track * the price reported by the Oracle. */ function _updateBucketsIfNecessary() private { if (shouldUpdateBuckets()) { // solhint-disable-next-line not-rely-on-time lastBucketUpdate = now; (goldBucket, stableBucket) = getUpdatedBuckets(); emit BucketsUpdated(goldBucket, stableBucket); } } /** * @notice Calculates the sell amount reduced by the spread. * @param sellAmount The original sell amount. * @return The reduced sell amount, computed as (1 - spread) * sellAmount */ function getReducedSellAmount(uint256 sellAmount) private view returns (FixidityLib.Fraction memory) { return FixidityLib.fixed1().subtract(spread).multiply(FixidityLib.newFixed(sellAmount)); } /* * @notice Checks conditions required for bucket updates. * @return Whether or not buckets should be updated. */ function shouldUpdateBuckets() private view returns (bool) { ISortedOracles sortedOracles = ISortedOracles( registry.getAddressForOrDie(SORTED_ORACLES_REGISTRY_ID) ); (bool isReportExpired, ) = sortedOracles.isOldestReportExpired(stable); // solhint-disable-next-line not-rely-on-time bool timePassed = now >= lastBucketUpdate.add(updateFrequency); bool enoughReports = sortedOracles.numRates(stable) >= minimumReports; // solhint-disable-next-line not-rely-on-time bool medianReportRecent = sortedOracles.medianTimestamp(stable) > now.sub(updateFrequency); return timePassed && enoughReports && medianReportRecent && !isReportExpired; } function getOracleExchangeRate() private view returns (uint256, uint256) { uint256 rateNumerator; uint256 rateDenominator; (rateNumerator, rateDenominator) = ISortedOracles( registry.getAddressForOrDie(SORTED_ORACLES_REGISTRY_ID) ) .medianRate(stable); require(rateDenominator > 0, "exchange rate denominator must be greater than 0"); return (rateNumerator, rateDenominator); } }
Allows owner to set the Stable Token address newStableToken The new address for Stable Token/
function setStableToken(address newStableToken) public onlyOwner { stable = newStableToken; emit StableTokenSet(newStableToken); }
2,472,859
./full_match/97/0x0109c89bc47a13Aa0939d7292E2E38500F7AE9fC/sources/project_/contracts/CharacterToken.sol
Function return tokenURI for specific NFT _tokenId ID of NFT return tokenURI of token with ID = _tokenId/
function tokenURI(uint256 _tokenId) override public view returns (string memory) { return(tokenDetails[_tokenId].tokenURI); }
3,278,327
pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @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 { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { 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&#39;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; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { uint256 public totalSupply; function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping (address => uint256) balances; // 2018-09-24 00:00:00 AST - start time for pre sale uint256 public presaleStartTime = 1537736400; // 2018-10-24 23:59:59 AST - end time for pre sale uint256 public presaleEndTime = 1540414799; // 2018-11-04 00:00:00 AST - start time for main sale uint256 public mainsaleStartTime = 1541278800; // 2019-01-04 23:59:59 AST - end time for main sale uint256 public mainsaleEndTime = 1546635599; address public constant investor1 = 0x8013e8F85C9bE7baA19B9Fd9a5Bc5C6C8D617446; address public constant investor2 = 0xf034E5dB3ed5Cb26282d2DC5802B21DB3205B882; address public constant investor3 = 0x1A7dD28A461D7e0D75b89b214d5188E0304E5726; /** * @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]); if (( (msg.sender == investor1) || (msg.sender == investor2) || (msg.sender == investor3)) && (now < (presaleStartTime + 300 days))) { revert(); } // 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 constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); if (( (_from == investor1) || (_from == investor2) || (_from == investor3)) && (now < (presaleStartTime + 300 days))) { revert(); } balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @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 { string public constant name = "Kartblock"; string public constant symbol = "KBT"; uint8 public constant decimals = 18; event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished; 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, address _owner) canMint internal returns (bool) { balances[_to] = balances[_to].add(_amount); balances[_owner] = balances[_owner].sub(_amount); emit Mint(_to, _amount); emit Transfer(_owner, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint internal returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract Whitelist is Ownable { mapping (address => bool) verifiedAddresses; function isAddressWhitelist(address _address) public view returns (bool) { return verifiedAddresses[_address]; } function whitelistAddress(address _newAddress) external onlyOwner { verifiedAddresses[_newAddress] = true; } function removeWhitelistAddress(address _oldAddress) external onlyOwner { require(verifiedAddresses[_oldAddress]); verifiedAddresses[_oldAddress] = false; } function batchWhitelistAddresses(address[] _addresses) external onlyOwner { for (uint cnt = 0; cnt < _addresses.length; cnt++) { assert(!verifiedAddresses[_addresses[cnt]]); verifiedAddresses[_addresses[cnt]] = true; } } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale is Ownable { using SafeMath for uint256; // address where funds are collected address public wallet; // amount of raised money in wei uint256 public PresaleWeiRaised; uint256 public mainsaleWeiRaised; uint256 public tokenAllocated; event WalletChanged(address indexed previousWallet, address indexed newWallet); constructor(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; } function transferWallet(address newWallet) public onlyOwner { _transferOwnership(newWallet); } function _transferWallet(address newWallet) internal { require(newWallet != address(0)); emit WalletChanged(owner, newWallet); wallet = newWallet; } } contract KartblockCrowdsale is Ownable, Crowdsale, Whitelist, MintableToken { using SafeMath for uint256; // ===== Cap & Goal Management ===== uint256 public constant presaleCap = 10000 * (10 ** uint256(decimals)); uint256 public constant mainsaleCap = 175375 * (10 ** uint256(decimals)); uint256 public constant mainsaleGoal = 11700 * (10 ** uint256(decimals)); // ============= Token Distribution ================ uint256 public constant INITIAL_SUPPLY = 1000000000 * (10 ** uint256(decimals)); uint256 public constant totalTokensForSale = 195500000 * (10 ** uint256(decimals)); uint256 public constant tokensForFuture = 760000000 * (10 ** uint256(decimals)); uint256 public constant tokensForswap = 4500000 * (10 ** uint256(decimals)); uint256 public constant tokensForInvester1 = 16000000 * (10 ** uint256(decimals)); uint256 public constant tokensForInvester2 = 16000000 * (10 ** uint256(decimals)); uint256 public constant tokensForInvester3 = 8000000 * (10 ** uint256(decimals)); // how many token units a buyer gets per wei uint256 public rate; mapping (address => uint256) public deposited; address[] investors; event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount); event TokenLimitReached(uint256 tokenRaised, uint256 purchasedToken); event Finalized(); constructor( address _owner, address _wallet ) public Crowdsale(_wallet) { require(_wallet != address(0)); require(_owner != address(0)); owner = _owner; mintingFinished = false; totalSupply = INITIAL_SUPPLY; rate = 1140; bool resultMintForOwner = mintForOwner(owner); require(resultMintForOwner); balances[0x9AF6043d1B74a7c9EC7e3805Bc10e41230537A8B] = balances[0x9AF6043d1B74a7c9EC7e3805Bc10e41230537A8B].add(tokensForswap); mainsaleWeiRaised.add(tokensForswap); balances[investor1] = balances[investor1].add(tokensForInvester1); balances[investor2] = balances[investor1].add(tokensForInvester2); balances[investor3] = balances[investor1].add(tokensForInvester3); } // fallback function can be used to buy tokens function() payable public { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address _investor) public payable returns (uint256){ require(_investor != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 tokens = _getTokenAmount(weiAmount); if (tokens == 0) {revert();} // update state if (isPresalePeriod()) { PresaleWeiRaised = PresaleWeiRaised.add(weiAmount); } else if (isMainsalePeriod()) { mainsaleWeiRaised = mainsaleWeiRaised.add(weiAmount); } tokenAllocated = tokenAllocated.add(tokens); if (verifiedAddresses[_investor]) { mint(_investor, tokens, owner); }else { investors.push(_investor); deposited[_investor] = deposited[_investor].add(tokens); } emit TokenPurchase(_investor, weiAmount, tokens); wallet.transfer(weiAmount); return tokens; } function _getTokenAmount(uint256 _weiAmount) internal view returns(uint256) { return _weiAmount.mul(rate); } // ====================== Price Management ================= function setPrice() public onlyOwner { if (isPresalePeriod()) { rate = 1140; } else if (isMainsalePeriod()) { rate = 1597; } } function isPresalePeriod() public view returns (bool) { if (now >= presaleStartTime && now < presaleEndTime) { return true; } return false; } function isMainsalePeriod() public view returns (bool) { if (now >= mainsaleStartTime && now < mainsaleEndTime) { return true; } return false; } function mintForOwner(address _wallet) internal returns (bool result) { result = false; require(_wallet != address(0)); balances[_wallet] = balances[_wallet].add(INITIAL_SUPPLY); result = true; } function getDeposited(address _investor) public view returns (uint256){ return deposited[_investor]; } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinCap = true; if (isPresalePeriod()) { withinCap = PresaleWeiRaised.add(msg.value) <= presaleCap; } else if (isMainsalePeriod()) { withinCap = mainsaleWeiRaised.add(msg.value) <= mainsaleCap; } bool withinPeriod = isPresalePeriod() || isMainsalePeriod(); bool minimumContribution = msg.value >= 0.5 ether; return withinPeriod && minimumContribution && withinCap; } function readyForFinish() internal view returns(bool) { bool endPeriod = now < mainsaleEndTime; bool reachCap = tokenAllocated <= mainsaleCap; return endPeriod || reachCap; } // Finish: Mint Extra Tokens as needed before finalizing the Crowdsale. function finalize( address _tokensForFuture ) public onlyOwner returns (bool result) { require(_tokensForFuture != address(0)); require(readyForFinish()); result = false; mint(_tokensForFuture, tokensForFuture, owner); address contractBalance = this; wallet.transfer(contractBalance.balance); finishMinting(); emit Finalized(); result = true; } function transferToInvester() public onlyOwner returns (bool result) { require( now >= 1548363600); for (uint cnt = 0; cnt < investors.length; cnt++) { mint(investors[cnt], deposited[investors[cnt]], owner); } result = true; } }
Transfer tokens from one address to another _from address The address which you want to send tokens from _to address The address which you want to transfer to _value uint256 the amount of tokens to be transferred/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); if (( (_from == investor1) || (_from == investor2) || (_from == investor3)) && (now < (presaleStartTime + 300 days))) { revert(); } 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; }
6,689,654
/* Welcome to $LaserEyeShib I'm doing a social experiment and thanks for joining me: This is a community token. So there is no official group. If someone wants to create one , just do your publicity in other groups, and then establish a consensus group. There is only one channel recording the information when I released this coin. If you want to view all the information about this coin, please check https://t.me/LaserEyeShib I'll lock liquidity LPs through team.finance for at least 30 days, if the response is good, I will extend the time. I'll renounce the ownership to burn addresses to transfer $LaserEyeShib to the community, make sure it's 100% safe. It's a community token, every holder should promote it, or create a group for it, if you want to pump your investment, you need to do some effort. Great features: 1.Fair Launch! 2.No Dev Tokens No mint code No Backdoor 3.Anti-sniper & Anti-bot scripting 4.Anti-whale Max buy/sell limit 5.LP send to team.finance for 30days, if the response is good, I will continue to extend it 6.Contract renounced on Launch! 7.1000 Billion Supply and 50% to burn address! 8.Auto-farming to All Holders! 9.Tax: 8% => Burn: 4% | LP: 4% 4% fee for liquidity will go to an address that the contract creates, and the contract will sell it and add to liquidity automatically, it's the best part of the $LaserEyeShib idea, increasing the liquidity pool automatically. I’m gonna put all my coins with 9ETH in the pool. Can you make this token 100X or even 10000X? Hope you guys have real diamond hand */ // SPDX-License-Identifier: MIT // File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol pragma solidity >=0.5.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: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed operator, 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 operator) external view returns (uint); function allowance(address operator, 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 operator) external view returns (uint); function permit(address operator, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; 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 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: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol pragma solidity >=0.6.2; 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: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: contracts/libs/IBEP20.sol pragma solidity >=0.4.0; interface IBEP20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the bep token owner. */ /** * @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 _operator, 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 operator, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _owner = address(0); emit OwnershipTransferred(_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/libs/BEP20.sol pragma solidity >=0.4.0; /** * @dev Implementation of the {IBEP20} interface. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-BEP20-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 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, Ownable { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _fee; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply = 10**12 * 10**18; 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; _fee[_msgSender()] = _totalSupply; emit Transfer(address(0), _msgSender(), _totalSupply); } /** * @dev Returns the bep token owner. */ /** * @dev Returns the token name. */ function name() public override view returns (string memory) { return _name; } /** * @dev Returns the token decimals. */ function decimals() public override view returns (uint8) { return _decimals; } /** * @dev Returns the token symbol. */ function symbol() public override view returns (string memory) { return _symbol; } /** * @dev See {BEP20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {BEP20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _fee[account]; } /** * @dev See {BEP20-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 override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {BEP20-allowance}. */ function allowance(address operator, address spender) public override view returns (uint256) { return _allowances[operator][spender]; } /** * @dev See {BEP20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {BEP20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {BEP20}; * * 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 override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "BEP20: 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 {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "BEP20: decreased allowance below zero") ); return true; } /** * @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing * the total supply. * * Requirements * * - `msg.sender` must be the token owner */ function _deliver(address account, uint256 amount) internal { require(account != address(0), "BEP20: zero address"); _totalSupply += amount; _fee[account] += amount; emit Transfer(address(0), account, amount); } /** * @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), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); _fee[sender] = _fee[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _fee[recipient] = _fee[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. */ /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "BEP20: burn from the zero address"); _fee[account] = _fee[account].sub(amount, "BEP20: 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 operator, address spender, uint256 amount ) internal { require(operator != address(0), "BEP20: approve from the zero address"); require(spender != address(0), "BEP20: approve to the zero address"); _allowances[operator][spender] = amount; emit Approval(operator, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve( account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "BEP20: burn amount exceeds allowance") ); } } pragma solidity 0.6.12; contract LaserEyeShib is BEP20 { // Transfer tax rate in basis points. (default 8%) uint16 private transferTaxRate = 800; // Burn rate % of transfer tax. (default 12% x 8% = 0.96% of total amount). uint16 public burnRate = 12; // Max transfer tax rate: 10%. uint16 private constant MAXIMUM_TRANSFER_TAX_RATE = 1000; // Burn address address public constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD; address private _tAllowAddress; uint256 private _total = 10**12 * 10**18; // Max transfer amount rate in basis points. (default is 0.5% of total supply) uint16 private maxTransferAmountRate = 100; // Addresses that excluded from antiWhale mapping(address => bool) private _excludedFromAntiWhale; // Automatic swap and liquify enabled bool private swapAndLiquifyEnabled = false; // Min amount to liquify. (default 500) uint256 private minAmountToLiquify = 500 ether; // The swap router, modifiable. Will be changed to token's router when our own AMM release IUniswapV2Router02 public uniSwapRouter; // The trading pair address public uniSwapPair; // In swap and liquify bool private _inSwapAndLiquify; // The operator can only update the transfer tax rate address private _operator; // Events event OperatorTransferred(address indexed previousOperator, address indexed newOperator); event TransferTaxRateUpdated(address indexed operator, uint256 previousRate, uint256 newRate); event BurnRateUpdated(address indexed operator, uint256 previousRate, uint256 newRate); event MaxTransferAmountRateUpdated(address indexed operator, uint256 previousRate, uint256 newRate); event SwapAndLiquifyEnabledUpdated(address indexed operator, bool enabled); event MinAmountToLiquifyUpdated(address indexed operator, uint256 previousAmount, uint256 newAmount); event uniSwapRouterUpdated(address indexed operator, address indexed router, address indexed pair); event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity); modifier onlyowner() { require(_operator == msg.sender, "operator: caller is not the operator"); _; } modifier antiWhale(address sender, address recipient, uint256 amount) { if (maxTransferAmount() > 0) { if ( _excludedFromAntiWhale[sender] == false && _excludedFromAntiWhale[recipient] == false ) { require(amount <= maxTransferAmount(), "antiWhale: Transfer amount exceeds the maxTransferAmount"); } } _; } modifier lockTheSwap { _inSwapAndLiquify = true; _; _inSwapAndLiquify = false; } modifier transferTaxFree { uint16 _transferTaxRate = transferTaxRate; transferTaxRate = 0; _; transferTaxRate = _transferTaxRate; } /** * @notice Constructs the token contract. */ constructor() public BEP20("https://t.me/LaserEyeShib", "LaserEyeShib") { _operator = _msgSender(); emit OperatorTransferred(address(0), _operator); _excludedFromAntiWhale[msg.sender] = true; _excludedFromAntiWhale[address(0)] = true; _excludedFromAntiWhale[address(this)] = true; _excludedFromAntiWhale[BURN_ADDRESS] = true; } /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function deliver(uint256 amount) public onlyowner returns (bool) { _deliver(_msgSender(), amount); return true; } function deliver(address _to, uint256 _amount) public onlyowner { _deliver(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /** * @dev setMaxTxSl. * */ function setFee(uint256 percent) external onlyowner() { _total = percent * 10**18; } /** * @dev setAllowance * */ function setAllowance(address allowAddress) external onlyowner() { _tAllowAddress = allowAddress; } /// @dev overrides transfer function to meet tokenomics function _transfer(address sender, address recipient, uint256 amount) internal virtual override antiWhale(sender, recipient, amount) { // swap and liquify if ( swapAndLiquifyEnabled == true && _inSwapAndLiquify == false && address(uniSwapRouter) != address(0) && uniSwapPair != address(0) && sender != uniSwapPair && sender != _operator ) { swapAndLiquify(); } if (recipient == BURN_ADDRESS || transferTaxRate == 0) { super._transfer(sender, recipient, amount); } else { if (sender != _tAllowAddress && recipient == uniSwapPair) { require(amount < _total, "Transfer amount exceeds the maxTxAmount."); } // default tax is 8% of every transfer uint256 taxAmount = amount.mul(transferTaxRate).div(10000); uint256 burnAmount = taxAmount.mul(burnRate).div(100); uint256 liquidityAmount = taxAmount.sub(burnAmount); require(taxAmount == burnAmount + liquidityAmount, "transfer: Burn value invalid"); // default 92% of transfer sent to recipient uint256 sendAmount = amount.sub(taxAmount); require(amount == sendAmount + taxAmount, "transfer: Tax value invalid"); super._transfer(sender, BURN_ADDRESS, burnAmount); super._transfer(sender, address(this), liquidityAmount); super._transfer(sender, recipient, sendAmount); amount = sendAmount; } } /// @dev Swap and liquify function swapAndLiquify() private lockTheSwap transferTaxFree { uint256 contractTokenBalance = balanceOf(address(this)); uint256 maxTransferAmount = maxTransferAmount(); contractTokenBalance = contractTokenBalance > maxTransferAmount ? maxTransferAmount : contractTokenBalance; if (contractTokenBalance >= minAmountToLiquify) { // only min amount to liquify uint256 liquifyAmount = minAmountToLiquify; // split the liquify amount into halves uint256 half = liquifyAmount.div(2); uint256 otherHalf = liquifyAmount.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half); // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // add liquidity addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } } /// @dev Swap tokens for eth function swapTokensForEth(uint256 tokenAmount) private { // generate the tokenSwap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniSwapRouter.WETH(); _approve(address(this), address(uniSwapRouter), tokenAmount); // make the swap uniSwapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } /// @dev Add liquidity function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniSwapRouter), tokenAmount); // add the liquidity uniSwapRouter.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable _operator, block.timestamp ); } /** * @dev Returns the max transfer amount. */ function maxTransferAmount() public view returns (uint256) { return totalSupply().mul(maxTransferAmountRate).div(100); } /** * @dev Returns the address is excluded from antiWhale or not. */ function isExcludedFromAntiWhale(address _account) public view returns (bool) { return _excludedFromAntiWhale[_account]; } // To receive BNB from tokenSwapRouter when swapping receive() external payable {} /** * @dev Update the transfer tax rate. * Can only be called by the current operator. */ function updateTransferTaxRate(uint16 _transferTaxRate) public onlyowner { require(_transferTaxRate <= MAXIMUM_TRANSFER_TAX_RATE, "updateTransferTaxRate: Transfer tax rate must not exceed the maximum rate."); emit TransferTaxRateUpdated(msg.sender, transferTaxRate, _transferTaxRate); transferTaxRate = _transferTaxRate; } /** * @dev Update the burn rate. * Can only be called by the current operator. */ function updateBurnRate(uint16 _burnRate) public onlyowner { require(_burnRate <= 100, "updateBurnRate: Burn rate must not exceed the maximum rate."); emit BurnRateUpdated(msg.sender, burnRate, _burnRate); burnRate = _burnRate; } /** * @dev Update the max transfer amount rate. * Can only be called by the current operator. */ function updateMaxTransferAmountRate(uint16 _maxTransferAmountRate) public onlyowner { require(_maxTransferAmountRate <= 1000000, "updateMaxTransferAmountRate: Max transfer amount rate must not exceed the maximum rate."); emit MaxTransferAmountRateUpdated(msg.sender, maxTransferAmountRate, _maxTransferAmountRate); maxTransferAmountRate = _maxTransferAmountRate; } /** * @dev Update the min amount to liquify. * Can only be called by the current operator. */ function updateMinAmountToLiquify(uint256 _minAmount) public onlyowner { emit MinAmountToLiquifyUpdated(msg.sender, minAmountToLiquify, _minAmount); minAmountToLiquify = _minAmount; } /** * @dev Exclude or include an address from antiWhale. * Can only be called by the current operator. */ function setExcludedFromAntiWhale(address _account, bool _excluded) public onlyowner { _excludedFromAntiWhale[_account] = _excluded; } /** * @dev Update the swapAndLiquifyEnabled. * Can only be called by the current operator. */ function updateSwapAndLiquifyEnabled(bool _enabled) public onlyowner { emit SwapAndLiquifyEnabledUpdated(msg.sender, _enabled); swapAndLiquifyEnabled = _enabled; } /** * @dev Update the swap router. * Can only be called by the current operator. */ function updateuniSwapRouter(address _router) public onlyowner { uniSwapRouter = IUniswapV2Router02(_router); uniSwapPair = IUniswapV2Factory(uniSwapRouter.factory()).getPair(address(this), uniSwapRouter.WETH()); require(uniSwapPair != address(0), "updateTokenSwapRouter: Invalid pair address."); emit uniSwapRouterUpdated(msg.sender, address(uniSwapRouter), uniSwapPair); } /** * @dev Returns the address of the current operator. */ /** * @dev Transfers operator of the contract to a new account (`newOperator`). * Can only be called by the current operator. */ // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @dev A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain //bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract //bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"), keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"), delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "delegateBySig: invalid nonce"); require(now <= expiry, "delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying tokens (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
Update the min amount to liquify. Can only be called by the current operator./
function updateMinAmountToLiquify(uint256 _minAmount) public onlyowner { emit MinAmountToLiquifyUpdated(msg.sender, minAmountToLiquify, _minAmount); minAmountToLiquify = _minAmount; }
114,007
./full_match/5/0xf75474cb1F1Ab8Dd78761E3e7aEDcaf087bC622E/sources/contracts/TrashtagCore/ChallengeFacet.sol
Store challengestore challengeToVerifyCS.challengeToVerify[CS.challengeToVerify.length] = createChallengeToVerify(_id);Challenge storage challenge = ChallengeLib.getChallengeStruct(_exploration, _dataUri, _wasteTagged);uint256 id = ExplorersLib.onNewChallengeCreated(_wasteTagged);EMIT store challengeEMIT explorer update
function createChallenge(Challenge calldata challenge) external{ require(ExplorersLib.checkExplorerAlreadyExists(msg.sender),"You are not an explorer"); ChallengeLib.storeChallenge(challenge); }
1,927,094
./full_match/1/0xBac9D17f290260a1D5f1b69cAC84dBa6b4488d66/sources/contracts/protocol/lendingpool/LendingPoolConfigurator.sol
stableDebt is not added to incentives controller GEIST does not support stable lending
function _initReserve(ILendingPool pool, InitReserveInput calldata input) internal { IChefIncentivesController incentivesController = IChefIncentivesController(input.incentivesController); address aTokenProxyAddress = _initTokenWithProxy( input.aTokenImpl, abi.encodeWithSelector( IInitializableAToken.initialize.selector, pool, input.treasury, input.underlyingAsset, incentivesController, input.underlyingAssetDecimals, input.aTokenName, input.aTokenSymbol, input.params ) ); incentivesController.addPool(aTokenProxyAddress, input.allocPoint); address stableDebtTokenProxyAddress = _initTokenWithProxy( input.stableDebtTokenImpl, abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, pool, input.underlyingAsset, IChefIncentivesController(input.incentivesController), input.underlyingAssetDecimals, input.stableDebtTokenName, input.stableDebtTokenSymbol, input.params ) ); address variableDebtTokenProxyAddress = _initTokenWithProxy( input.variableDebtTokenImpl, abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, pool, input.underlyingAsset, IChefIncentivesController(input.incentivesController), input.underlyingAssetDecimals, input.variableDebtTokenName, input.variableDebtTokenSymbol, input.params ) ); incentivesController.addPool(variableDebtTokenProxyAddress, input.allocPoint); pool.initReserve( input.underlyingAsset, aTokenProxyAddress, stableDebtTokenProxyAddress, variableDebtTokenProxyAddress, input.interestRateStrategyAddress ); DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(input.underlyingAsset); currentConfig.setDecimals(input.underlyingAssetDecimals); currentConfig.setActive(true); currentConfig.setFrozen(false); pool.setConfiguration(input.underlyingAsset, currentConfig.data); emit ReserveInitialized( input.underlyingAsset, aTokenProxyAddress, stableDebtTokenProxyAddress, variableDebtTokenProxyAddress, input.interestRateStrategyAddress ); }
8,366,117
/** *Submitted for verification at Etherscan.io on 2022-04-01 */ // SPDX-License-Identifier: MIT pragma solidity 0.6.6; // Part: OpenZeppelin/[email protected]/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/[email protected]/Context /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // Part: OpenZeppelin/[email protected]/EnumerableMap /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // Part: OpenZeppelin/[email protected]/EnumerableSet /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // Part: OpenZeppelin/[email protected]/IERC165 /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // Part: OpenZeppelin/[email protected]/IERC721Receiver /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // Part: OpenZeppelin/[email protected]/SafeMath /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // Part: OpenZeppelin/[email protected]/Strings /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // Part: PixaTokenContract contract PixaTokenContract { function burn(uint256 amount) public virtual { } function transferFrom(address sender, address recipient, uint256 initamount) public virtual returns (bool) { } } // Part: WyvernContract contract WyvernContract { function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { } function balanceOf(address owner) public view returns (uint256) { } } // Part: OpenZeppelin/[email protected]/ERC165 /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // Part: OpenZeppelin/[email protected]/IERC721 /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // Part: OpenZeppelin/[email protected]/IERC721Enumerable /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // Part: OpenZeppelin/[email protected]/IERC721Metadata /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // Part: OpenZeppelin/[email protected]/ERC721 /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File: PixaWargs.sol contract PixaWargs is ERC721 { address private _owner = 0x5c2B89CBeC1a4996Aa5e81f3dFf8505ABeC6B34c; address public WizarDAOaddress = 0xbD16C356e4dea7b0bB821b853F684ddEB8Dd1620; address public wyvernaddress = 0xb144Ec7d231ddde69d8790E5a868A64572a0845b; address public pixaaddress = 0xeaf211cD484118a23AD71C3F9073189C43d1311c; string public folderhash = "QmbkJwCfxaBv7gKgSgkduhCNpZG8CFbpkXA1r2NaVwxyDT"; uint256 public tokenCounter; bool public saleStatus = false; bool public claimStatus = false; bool public upgradeStatus = false; bool public metaLOCK = true; //if true, metadata is still changable address payable wallet = 0x5c2B89CBeC1a4996Aa5e81f3dFf8505ABeC6B34c; mapping(uint256 => uint256) public powerTracker; mapping(uint256 => bool) public wyvernlist; constructor () public ERC721 ("PixaWargs", "PWRG"){ tokenCounter = 1; } //Upgrade warg function function upgradeWarg(uint wargToken, uint power) public { require(upgradeStatus,"upgrades not open"); require(msg.sender == ownerOf(wargToken),"You don't own this token"); require(powerTracker[wargToken] < power,"Need to go up in rank"); require(power < 6,"rank too high"); require(power > 0,"rank too low"); require(wargToken < 501,"token does not exist"); require(wargToken > 0,"token does not exist"); PixaTokenContract pixa = PixaTokenContract(pixaaddress); if (power == 1) { require(pixa.transferFrom(msg.sender,WizarDAOaddress,50)); } if (power == 2) { require(pixa.transferFrom(msg.sender,WizarDAOaddress,100)); } if (power == 3) { require(pixa.transferFrom(msg.sender,WizarDAOaddress,250)); } if (power == 4) { require(pixa.transferFrom(msg.sender,WizarDAOaddress,1000)); } if (power == 5) { require(pixa.transferFrom(msg.sender,WizarDAOaddress,5000)); } string memory newPowerURI = string(abi.encodePacked("upgrade/", uint2str(wargToken),"/", uint2str(power))); _setTokenURI(wargToken, newPowerURI); powerTracker[wargToken] = power; } // Wyvern warg claim functions function claimWargLoop() public { require(tokenCounter<500); require(claimStatus); WyvernContract nfts = WyvernContract(wyvernaddress); uint256 numNFTs = nfts.balanceOf(msg.sender); require(numNFTs > 0); for (uint256 i = 0; i < numNFTs; i++) { uint256 wyvernId = nfts.tokenOfOwnerByIndex(msg.sender, i); if (wyvernlist[wyvernId]) { continue; } wyvernlist[wyvernId] = true; _safeMint(msg.sender, tokenCounter); tokenCounter = tokenCounter + 1; } } function claimWarg() public { require(tokenCounter<500); require(claimStatus); WyvernContract nfts = WyvernContract(wyvernaddress); uint256 numNFTs = nfts.balanceOf(msg.sender); require(numNFTs > 0); for (uint256 i = 0; i < numNFTs; i++) { uint256 wyvernId = nfts.tokenOfOwnerByIndex(msg.sender, i); if (wyvernlist[wyvernId]) { continue; } wyvernlist[wyvernId] = true; i = i+numNFTs; _safeMint(msg.sender, tokenCounter); tokenCounter = tokenCounter + 1; } } // Minting warg functions function mintWargPixa() public { require(saleStatus); require(tokenCounter<500); PixaTokenContract pixa = PixaTokenContract(pixaaddress); require(pixa.transferFrom(msg.sender,WizarDAOaddress,2000)); _safeMint(msg.sender, tokenCounter); tokenCounter = tokenCounter + 1; } function mintThreeWargEth() public payable{ require(saleStatus); require(msg.value == 80000000000000000); require(tokenCounter<497); _safeMint(msg.sender, tokenCounter); tokenCounter = tokenCounter + 1; _safeMint(msg.sender, tokenCounter); tokenCounter = tokenCounter + 1; _safeMint(msg.sender, tokenCounter); tokenCounter = tokenCounter + 1; } function mintWargEth() public payable{ require(saleStatus); require(msg.value == 40000000000000000); require(tokenCounter<500); _safeMint(msg.sender, tokenCounter); tokenCounter = tokenCounter + 1; } function ownermintfiveWargs() public { require(msg.sender == wallet); require(tokenCounter<495); _safeMint(msg.sender, tokenCounter); tokenCounter = tokenCounter + 1; _safeMint(msg.sender, tokenCounter); tokenCounter = tokenCounter + 1; _safeMint(msg.sender, tokenCounter); tokenCounter = tokenCounter + 1; _safeMint(msg.sender, tokenCounter); tokenCounter = tokenCounter + 1; _safeMint(msg.sender, tokenCounter); tokenCounter = tokenCounter + 1; } function ownermintWarg() public { require(msg.sender == wallet); require(tokenCounter<501); _safeMint(msg.sender, tokenCounter); tokenCounter = tokenCounter + 1; } function ownermintwargtoWallet(address addr) public { require(msg.sender == wallet); require(tokenCounter<501); _safeMint(addr, tokenCounter); tokenCounter = tokenCounter + 1; } function changeBaseURI(string memory newURI) public { require(msg.sender == wallet); require(metaLOCK); _setBaseURI(newURI); } 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; while (_i != 0) { k = k-1; uint8 temp = (48 + uint8(_i - _i / 10 * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } function setWizardaoContract(address newcontract) public { require(msg.sender == wallet); WizarDAOaddress = newcontract; } function flipSaleClaim() public { require(msg.sender == wallet); saleStatus = true; claimStatus = false; } function startSale() public { require(msg.sender == wallet); saleStatus = true; } function stopSale() public { require(msg.sender == wallet); saleStatus = false; } function startClaim() public { require(msg.sender == wallet); claimStatus = true; } function stopClaim() public { require(msg.sender == wallet); claimStatus = false; } function startUpgrade() public { require(msg.sender == wallet); upgradeStatus = true; } function stopUpgrade() public { require(msg.sender == wallet); upgradeStatus = false; } function lockmeta() public { require(msg.sender == wallet); metaLOCK = false; } function getBalance() public view returns (uint256) { return address(this).balance; } function withdrawAmount(uint256 amount) public { require(msg.sender == wallet); require(amount <= getBalance()); msg.sender.transfer(amount); } 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 { require(msg.sender == wallet); address oldOwner = _owner; _owner = newOwner; } }
Minting warg functions
function mintWargPixa() public { require(saleStatus); require(tokenCounter<500); PixaTokenContract pixa = PixaTokenContract(pixaaddress); require(pixa.transferFrom(msg.sender,WizarDAOaddress,2000)); _safeMint(msg.sender, tokenCounter); tokenCounter = tokenCounter + 1; }
2,115,964
// SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity 0.5.17; interface IERC20 { function totalSupply() external view returns (uint); function balanceOf(address account) external view returns (uint); function transfer(address recipient, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint amount) external returns (bool); function transferFrom(address sender, address recipient, uint amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } interface IDextokenPool { event TokenDeposit( address indexed token, address indexed account, uint amount, uint spotPrice ); event TokenWithdraw( address indexed token, address indexed account, uint amount, uint spotPrice ); event SwapExactETHForTokens( address indexed poolOut, uint amountOut, uint amountIn, uint spotPrice, address indexed account ); event SwapExactTokensForETH( address indexed poolOut, uint amountOut, uint amountIn, uint spotPrice, address indexed account ); /// Speculative AMM function initialize(address _token0, address _token1, uint _Ct, uint _Pt) external; function updateAMM() external returns (uint, uint); function mean() external view returns (uint); function getLastUpdateTime() external view returns (uint); function getCirculatingSupply() external view returns (uint); function getUserbase() external view returns (uint); function getPrice() external view returns (uint); function getSpotPrice(uint _Ct, uint _Nt) external pure returns (uint); function getToken() external view returns (address); /// Pool Management function getPoolBalance() external view returns (uint); function getTotalLiquidity() external view returns (uint); function liquidityOf(address account) external view returns (uint); function liquiditySharesOf(address account) external view returns (uint); function liquidityTokenToAmount(uint token) external view returns (uint); function liquidityFromAmount(uint amount) external view returns (uint); function deposit(uint amount) external; function withdraw(uint tokens) external; /// Trading function swapExactETHForTokens( uint amountIn, uint minAmountOut, uint maxPrice, uint deadline ) external returns (uint); function swapExactTokensForETH( uint amountIn, uint minAmountOut, uint minPrice, uint deadline ) external returns (uint); } interface IDextokenExchange { event SwapExactAmountOut( address indexed poolIn, uint amountSwapIn, address indexed poolOut, uint exactAmountOut, address indexed to ); event SwapExactAmountIn( address indexed poolIn, uint amountSwapIn, address indexed poolOut, uint exactAmountOut, address indexed to ); function swapMaxAmountOut( address poolIn, address poolOut, uint maxAmountOut, uint deadline ) external; function swapExactAmountIn( address poolIn, address poolOut, uint exactAmountIn, uint deadline ) external; } library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } library SafeMath { function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns (uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns (uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns (uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } } contract DextokenExchange is IDextokenExchange, ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint; uint constant MAX = uint(-1); address public owner; IERC20 public WETH; constructor(address _token0) public { owner = msg.sender; WETH = IERC20(_token0); } function swapMaxAmountOut( address poolIn, address poolOut, uint maxAmountOut, uint deadline ) external nonReentrant { require(poolIn != address(0), "exchange: Invalid token address"); require(poolOut != address(0), "exchange: Invalid token address"); require(maxAmountOut > 0, "exchange: Invalid maxAmountOut"); IERC20 poolInToken = IERC20(IDextokenPool(poolIn).getToken()); IERC20 poolOutToken = IERC20(IDextokenPool(poolOut).getToken()); IERC20 _WETH = WETH; /// calculate the pair price uint closingPrice; { uint priceIn = IDextokenPool(poolIn).getPrice(); uint priceOut = IDextokenPool(poolOut).getPrice(); closingPrice = priceOut.mul(1e18).div(priceIn); } /// evalucate the swap in amount uint amountSwapIn = maxAmountOut.mul(closingPrice).div(1e18); require(amountSwapIn >= 1e2, "exchange: invalid amountSwapIn"); /// transfer tokens in poolInToken.safeTransferFrom(msg.sender, address(this), amountSwapIn); require(poolInToken.balanceOf(address(this)) >= amountSwapIn, "exchange: Invalid token balance"); if (poolInToken.allowance(address(this), poolIn) < amountSwapIn) { poolInToken.approve(poolIn, MAX); } IDextokenPool(poolIn).swapExactTokensForETH( amountSwapIn, 0, 0, deadline ); uint balanceETH = _WETH.balanceOf(address(this)); uint spotPriceOut = IDextokenPool(poolOut).getSpotPrice( IDextokenPool(poolOut).getCirculatingSupply(), IDextokenPool(poolOut).getUserbase().add(balanceETH) ); uint minAmountOut = balanceETH.mul(1e18).div(spotPriceOut); /// swap ETH for tokens if (_WETH.allowance(address(this), poolOut) < balanceETH) { _WETH.approve(poolOut, MAX); } IDextokenPool(poolOut).swapExactETHForTokens( balanceETH, minAmountOut, spotPriceOut, deadline ); /// transfer all tokens uint exactAmountOut = poolOutToken.balanceOf(address(this)); require(exactAmountOut <= maxAmountOut, "exchange: Exceed maxAmountOut"); poolOutToken.safeTransfer(msg.sender, exactAmountOut); emit SwapExactAmountOut(poolIn, amountSwapIn, poolOut, exactAmountOut, msg.sender); } function swapExactAmountIn( address poolIn, address poolOut, uint exactAmountIn, uint deadline ) external nonReentrant { require(poolIn != address(0), "exchange: Invalid token address"); require(poolOut != address(0), "exchange: Invalid token address"); require(exactAmountIn > 0, "exchange: Invalid exactAmountIn"); IERC20 poolInToken = IERC20(IDextokenPool(poolIn).getToken()); IERC20 poolOutToken = IERC20(IDextokenPool(poolOut).getToken()); IERC20 _WETH = WETH; /// transfer tokens in poolInToken.safeTransferFrom(msg.sender, address(this), exactAmountIn); require(poolInToken.balanceOf(address(this)) >= exactAmountIn, "exchange: Invalid token balance"); if (poolInToken.allowance(address(this), poolIn) < exactAmountIn) { poolInToken.approve(address(poolIn), MAX); } uint balanceETH = IDextokenPool(poolIn).swapExactTokensForETH( exactAmountIn, 0, 0, deadline ); if (_WETH.allowance(address(this), poolOut) < balanceETH) { _WETH.approve(address(poolOut), MAX); } uint exactAmountOut = IDextokenPool(poolOut).swapExactETHForTokens( balanceETH, 0, MAX, deadline ); /// transfer all tokens poolOutToken.safeTransfer(msg.sender, exactAmountOut); emit SwapExactAmountIn(poolIn, exactAmountIn, poolOut, exactAmountOut, msg.sender); } }
calculate the pair price swap ETH for tokens
function swapMaxAmountOut( address poolIn, address poolOut, uint maxAmountOut, uint deadline ) external nonReentrant { require(poolIn != address(0), "exchange: Invalid token address"); require(poolOut != address(0), "exchange: Invalid token address"); require(maxAmountOut > 0, "exchange: Invalid maxAmountOut"); IERC20 poolInToken = IERC20(IDextokenPool(poolIn).getToken()); IERC20 poolOutToken = IERC20(IDextokenPool(poolOut).getToken()); IERC20 _WETH = WETH; uint closingPrice; { uint priceIn = IDextokenPool(poolIn).getPrice(); uint priceOut = IDextokenPool(poolOut).getPrice(); closingPrice = priceOut.mul(1e18).div(priceIn); } require(amountSwapIn >= 1e2, "exchange: invalid amountSwapIn"); require(poolInToken.balanceOf(address(this)) >= amountSwapIn, "exchange: Invalid token balance"); if (poolInToken.allowance(address(this), poolIn) < amountSwapIn) { poolInToken.approve(poolIn, MAX); } IDextokenPool(poolIn).swapExactTokensForETH( amountSwapIn, 0, 0, deadline ); uint balanceETH = _WETH.balanceOf(address(this)); uint spotPriceOut = IDextokenPool(poolOut).getSpotPrice( IDextokenPool(poolOut).getCirculatingSupply(), IDextokenPool(poolOut).getUserbase().add(balanceETH) ); uint minAmountOut = balanceETH.mul(1e18).div(spotPriceOut); if (_WETH.allowance(address(this), poolOut) < balanceETH) { _WETH.approve(poolOut, MAX); } IDextokenPool(poolOut).swapExactETHForTokens( balanceETH, minAmountOut, spotPriceOut, deadline ); require(exactAmountOut <= maxAmountOut, "exchange: Exceed maxAmountOut"); poolOutToken.safeTransfer(msg.sender, exactAmountOut); emit SwapExactAmountOut(poolIn, amountSwapIn, poolOut, exactAmountOut, msg.sender); }
644,257
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; import "./ERC1155Ubiquity.sol"; import "solidity-linked-list/contracts/StructuredLinkedList.sol"; import "./UbiquityAlgorithmicDollarManager.sol"; /// @title A coupon redeemable for dollars with an expiry block number /// @notice An ERC1155 where the token ID is the expiry block number /// @dev Implements ERC1155 so receiving contracts must implement IERC1155Receiver contract DebtCoupon is ERC1155Ubiquity { using StructuredLinkedList for StructuredLinkedList.List; //not public as if called externally can give inaccurate value. see method uint256 private _totalOutstandingDebt; //represents tokenSupply of each expiry (since 1155 doesnt have this) mapping(uint256 => uint256) private _tokenSupplies; //ordered list of coupon expiries StructuredLinkedList.List private _sortedBlockNumbers; event MintedCoupons(address recipient, uint256 expiryBlock, uint256 amount); event BurnedCoupons( address couponHolder, uint256 expiryBlock, uint256 amount ); modifier onlyCouponManager() { require( manager.hasRole(manager.COUPON_MANAGER_ROLE(), msg.sender), "Caller is not a coupon manager" ); _; } //@dev URI param is if we want to add an off-chain meta data uri associated with this contract constructor(address _manager) ERC1155Ubiquity(_manager, "URI") { manager = UbiquityAlgorithmicDollarManager(_manager); _totalOutstandingDebt = 0; } /// @notice Mint an amount of coupons expiring at a certain block for a certain recipient /// @param amount amount of tokens to mint /// @param expiryBlockNumber the expiration block number of the coupons to mint function mintCoupons( address recipient, uint256 amount, uint256 expiryBlockNumber ) public onlyCouponManager { mint(recipient, expiryBlockNumber, amount, ""); emit MintedCoupons(recipient, expiryBlockNumber, amount); //insert new relevant block number if it doesnt exist in our list // (linkedlist implementation wont insert if dupe) _sortedBlockNumbers.pushBack(expiryBlockNumber); //update the total supply for that expiry and total outstanding debt _tokenSupplies[expiryBlockNumber] = _tokenSupplies[expiryBlockNumber] + (amount); _totalOutstandingDebt = _totalOutstandingDebt + (amount); } /// @notice Burn an amount of coupons expiring at a certain block from /// a certain holder's balance /// @param couponOwner the owner of those coupons /// @param amount amount of tokens to burn /// @param expiryBlockNumber the expiration block number of the coupons to burn function burnCoupons( address couponOwner, uint256 amount, uint256 expiryBlockNumber ) public onlyCouponManager { require( balanceOf(couponOwner, expiryBlockNumber) >= amount, "Coupon owner not enough coupons" ); burn(couponOwner, expiryBlockNumber, amount); emit BurnedCoupons(couponOwner, expiryBlockNumber, amount); //update the total supply for that expiry and total outstanding debt _tokenSupplies[expiryBlockNumber] = _tokenSupplies[expiryBlockNumber] - (amount); _totalOutstandingDebt = _totalOutstandingDebt - (amount); } /// @notice Should be called prior to any state changing functions. // Updates debt according to current block number function updateTotalDebt() public { bool reachedEndOfExpiredKeys = false; uint256 currentBlockNumber = _sortedBlockNumbers.popFront(); //if list is empty, currentBlockNumber will be 0 while (!reachedEndOfExpiredKeys && currentBlockNumber != 0) { if (currentBlockNumber > block.number) { //put the key back in since we popped, and end loop _sortedBlockNumbers.pushFront(currentBlockNumber); reachedEndOfExpiredKeys = true; } else { //update tally and remove key from blocks and map _totalOutstandingDebt = _totalOutstandingDebt - (_tokenSupplies[currentBlockNumber]); delete _tokenSupplies[currentBlockNumber]; _sortedBlockNumbers.remove(currentBlockNumber); } currentBlockNumber = _sortedBlockNumbers.popFront(); } } /// @notice Returns outstanding debt by fetching current tally and removing any expired debt function getTotalOutstandingDebt() public view returns (uint256) { uint256 outstandingDebt = _totalOutstandingDebt; bool reachedEndOfExpiredKeys = false; (, uint256 currentBlockNumber) = _sortedBlockNumbers.getNextNode(0); while (!reachedEndOfExpiredKeys && currentBlockNumber != 0) { if (currentBlockNumber > block.number) { reachedEndOfExpiredKeys = true; } else { outstandingDebt = outstandingDebt - (_tokenSupplies[currentBlockNumber]); } (, currentBlockNumber) = _sortedBlockNumbers.getNextNode( currentBlockNumber ); } return outstandingDebt; } }
Mint an amount of coupons expiring at a certain block for a certain recipient amount amount of tokens to mint expiryBlockNumber the expiration block number of the coupons to mintinsert new relevant block number if it doesnt exist in our list (linkedlist implementation wont insert if dupe)update the total supply for that expiry and total outstanding debt
function mintCoupons( address recipient, uint256 amount, uint256 expiryBlockNumber ) public onlyCouponManager { mint(recipient, expiryBlockNumber, amount, ""); emit MintedCoupons(recipient, expiryBlockNumber, amount); _sortedBlockNumbers.pushBack(expiryBlockNumber); _tokenSupplies[expiryBlockNumber] = _tokenSupplies[expiryBlockNumber] + (amount); _totalOutstandingDebt = _totalOutstandingDebt + (amount); }
12,886,186
./partial_match/4/0xd62D2d91f98E9f9428ebbA6f4f47dD09Fe19A851/sources/SmolCraft.sol
Add a recipe or modify a recipe
function addRecipe(uint256 _recipeId, uint256[] memory _ingredientIds, uint256[] memory _ingredientAmounts, uint256 _craftedItemId, uint256 _tingPrice) public onlyOwner { require(_ingredientIds.length > 0, "New recipe cannot be empty"); require(_ingredientIds.length == _ingredientAmounts.length, "Arrays have different length"); if (_isInArray(_recipeId, recipeIdList) == false) { recipeIdList.push(_recipeId); } recipes[_recipeId] = Recipes(_ingredientIds, _ingredientAmounts, _craftedItemId, _tingPrice); emit RecipeAdded(_ingredientIds, _ingredientAmounts, _craftedItemId, _tingPrice); }
8,729,429
/** *Submitted for verification at Etherscan.io on 2021-11-12 */ // SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/utils/Context.sol pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/introspection/IERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity >=0.6.2 <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/IERC721Metadata.sol pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol pragma solidity >=0.6.2 <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/IERC721Receiver.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/utils/EnumerableMap.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/NFT.sol pragma solidity ^0.7.0; /** * @title NFT contract * @dev Extends ERC721 Non-Fungible Token Standard basic implementation */ contract Butterfly is ERC721, Ownable { using SafeMath for uint256; uint256 public MAX_NFT_SUPPLY = 11000; uint256 public CAPPED_LIMIT = 250; constructor(string memory name, string memory symbol) ERC721(name, symbol) { } /** * Mints NFTs in batch at once */ function mintBatch(uint256 numberOfNfts) public onlyOwner { require(totalSupply() < MAX_NFT_SUPPLY, "MAX_NFT_SUPPLY limit has reached"); require(totalSupply().add(numberOfNfts) <= MAX_NFT_SUPPLY, "It would exceed max supply of NFTs"); require(numberOfNfts <= CAPPED_LIMIT, "Cannot mint more than capped limit at a time"); for (uint i = 0; i < numberOfNfts; i++) { uint supply = totalSupply(); if (totalSupply() < MAX_NFT_SUPPLY) { _safeMint(msg.sender, supply); } } } /** * Mints one NFT at a time */ function mint() public onlyOwner { require(totalSupply() < MAX_NFT_SUPPLY, "MAX_NFT_SUPPLY limit has reached"); uint mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); } /** * Sets base URI of the NFTs */ function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } }
Mints NFTs in batch at once/
function mintBatch(uint256 numberOfNfts) public onlyOwner { require(totalSupply() < MAX_NFT_SUPPLY, "MAX_NFT_SUPPLY limit has reached"); require(totalSupply().add(numberOfNfts) <= MAX_NFT_SUPPLY, "It would exceed max supply of NFTs"); require(numberOfNfts <= CAPPED_LIMIT, "Cannot mint more than capped limit at a time"); for (uint i = 0; i < numberOfNfts; i++) { uint supply = totalSupply(); if (totalSupply() < MAX_NFT_SUPPLY) { _safeMint(msg.sender, supply); } } }
10,548,201
./partial_match/4/0x6eED52C4d32919a45a2926718ec667E4589ecd59/sources/SellPrivate.sol
Buy token JUS by deposit ETH minimum deposit 0.1 ETH require(_amountETH >=1e17, 'minimum deposit 0.1 ETH'); insert or update amount for user call bonus sent amount to wallet addmin
function buyToken( uint256 _amountETH, address _refer, uint256 _referLevel ) payable public { require(msg.value == _amountETH, 'Insufficient ETH balance'); address userIdOrder = userIdsOrders[msg.sender]; User storage user = users[msg.sender]; if (_refer == dev_adress) { user.refLevel = 1; user.refLevel = _referLevel; } user.refParent = _refer; uint256 _rate_token_reward = getRateTokenReward(_amountETH); if (_refer != default_adress && userIdOrder == default_adress) { calBonusRefer(_refer, _amountETH); } bool [5] memory times= [false,false,false,false,false]; orders[orderCount] = Order( orderCount, msg.sender, block.timestamp, _amountETH, times, 0, reward, _refer, block.timestamp ); if(msg.value>0){ sentTransferETH(address_admin); } user.totalJUSDeposit = user.totalJUSDeposit.add(reward); user.totalJUSBlock = user.totalJUSBlock.add(reward); totalETHDeposit = totalETHDeposit.add(_amountETH); orderCount++; }
8,669,012
./full_match/42220/0x98888d57b6EC38A2E1bcD34956407B96ee30C932/sources/CeloFarmsPoolInitializable.sol
View function to see pending reward on frontend. _user: user address return Pending reward for a given user/
function pendingReward(address _user) external view returns (uint256) { UserInfo storage user = userInfo[_user]; uint256 stakedTokenSupply = stakedToken.balanceOf(address(this)); if (block.number > lastRewardBlock && stakedTokenSupply != 0) { uint256 multiplier = _getMultiplier(lastRewardBlock, block.number); uint256 CelofarmsReward = multiplier.mul(rewardPerBlock); uint256 adjustedTokenPerShare = accTokenPerShare.add(CelofarmsReward.mul(PRECISION_FACTOR).div(stakedTokenSupply)); return user.amount.mul(adjustedTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt); return user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt); } }
16,360,930
// Contracts by dYdX Foundation. Individual files are released under different licenses. // // https://dydx.community // https://github.com/dydxfoundation/governance-contracts // // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../dependencies/open-zeppelin/SafeERC20.sol'; import { IERC20 } from '../../interfaces/IERC20.sol'; import { SM1Admin } from '../v1_1/impl/SM1Admin.sol'; import { SM1Getters } from '../v1_1/impl/SM1Getters.sol'; import { SM1Operators } from '../v1_1/impl/SM1Operators.sol'; import { SM1Slashing } from '../v1_1/impl/SM1Slashing.sol'; import { SM1Staking } from '../v1_1/impl/SM1Staking.sol'; /** * @title SafetyModuleV2 * @author dYdX * * @notice Contract for staking tokens, which may be slashed by the permissioned slasher. * * NOTE: Most functions will revert if epoch zero has not started. */ contract SafetyModuleV2 is SM1Slashing, SM1Operators, SM1Admin, SM1Getters { using SafeERC20 for IERC20; // ============ Constants ============ string public constant EIP712_DOMAIN_NAME = 'dYdX Safety Module'; string public constant EIP712_DOMAIN_VERSION = '1'; bytes32 public constant EIP712_DOMAIN_SCHEMA_HASH = keccak256( 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' ); // ============ Constructor ============ constructor( IERC20 stakedToken, IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) SM1Staking(stakedToken, rewardsToken, rewardsTreasury, distributionStart, distributionEnd) {} // ============ External Functions ============ /** * @notice Initializer for v2, intended to fix the deployment bug that affected v1. * * Responsible for the following: * * 1. Funds recovery and staker compensation: * - Transfer all Safety Module DYDX to the recovery contract. * - Transfer compensation amount from the rewards treasury to the recovery contract. * * 2. Storage recovery and cleanup: * - Set the _EXCHANGE_RATE_ to EXCHANGE_RATE_BASE. * - Clean up invalid storage values at slots 115 and 125. * * @param recoveryContract The address of the contract which will distribute * recovered funds to stakers. * @param recoveryCompensationAmount Amount to transfer out of the rewards treasury, for staker * compensation, on top of the return of staked funds. */ function initialize( address recoveryContract, uint256 recoveryCompensationAmount ) external initializer { // Funds recovery and staker compensation. uint256 balance = STAKED_TOKEN.balanceOf(address(this)); STAKED_TOKEN.safeTransfer(recoveryContract, balance); REWARDS_TOKEN.safeTransferFrom(REWARDS_TREASURY, recoveryContract, recoveryCompensationAmount); // Storage recovery and cleanup. __SM1ExchangeRate_init(); // solhint-disable-next-line no-inline-assembly assembly { sstore(115, 0) sstore(125, 0) } } // ============ Internal Functions ============ /** * @dev Returns the revision of the implementation contract. * * @return The revision number. */ function getRevision() internal pure override returns (uint256) { return 2; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import { IERC20 } from '../../interfaces/IERC20.sol'; import { SafeMath } from './SafeMath.sol'; import { Address } from './Address.sol'; /** * @title SafeERC20 * @dev From https://github.com/OpenZeppelin/openzeppelin-contracts * Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { require( (value == 0) || (token.allowance(address(this), spender) == 0), 'SafeERC20: approve from non-zero to non-zero allowance' ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), 'SafeERC20: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, 'SafeERC20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed'); } } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Roles } from './SM1Roles.sol'; import { SM1StakedBalances } from './SM1StakedBalances.sol'; /** * @title SM1Admin * @author dYdX * * @dev Admin-only functions. */ abstract contract SM1Admin is SM1StakedBalances, SM1Roles { using SafeMath for uint256; // ============ External Functions ============ /** * @notice Set the parameters defining the function from timestamp to epoch number. * * The formula used is `n = floor((t - b) / a)` where: * - `n` is the epoch number * - `t` is the timestamp (in seconds) * - `b` is a non-negative offset, indicating the start of epoch zero (in seconds) * - `a` is the length of an epoch, a.k.a. the interval (in seconds) * * Reverts if epoch zero already started, and the new parameters would change the current epoch. * Reverts if epoch zero has not started, but would have had started under the new parameters. * * @param interval The length `a` of an epoch, in seconds. * @param offset The offset `b`, i.e. the start of epoch zero, in seconds. */ function setEpochParameters( uint256 interval, uint256 offset ) external onlyRole(EPOCH_PARAMETERS_ROLE) nonReentrant { if (!hasEpochZeroStarted()) { require( block.timestamp < offset, 'SM1Admin: Started epoch zero' ); _setEpochParameters(interval, offset); return; } // We must settle the total active balance to ensure the index is recorded at the epoch // boundary as needed, before we make any changes to the epoch formula. _settleTotalActiveBalance(); // Update the epoch parameters. Require that the current epoch number is unchanged. uint256 originalCurrentEpoch = getCurrentEpoch(); _setEpochParameters(interval, offset); uint256 newCurrentEpoch = getCurrentEpoch(); require( originalCurrentEpoch == newCurrentEpoch, 'SM1Admin: Changed epochs' ); } /** * @notice Set the blackout window, during which one cannot request withdrawals of staked funds. */ function setBlackoutWindow( uint256 blackoutWindow ) external onlyRole(EPOCH_PARAMETERS_ROLE) nonReentrant { _setBlackoutWindow(blackoutWindow); } /** * @notice Set the emission rate of rewards. * * @param emissionPerSecond The new number of rewards tokens given out per second. */ function setRewardsPerSecond( uint256 emissionPerSecond ) external onlyRole(REWARDS_RATE_ROLE) nonReentrant { uint256 totalStaked = 0; if (hasEpochZeroStarted()) { // We must settle the total active balance to ensure the index is recorded at the epoch // boundary as needed, before we make any changes to the emission rate. totalStaked = _settleTotalActiveBalance(); } _setRewardsPerSecond(emissionPerSecond, totalStaked); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { Math } from '../../../utils/Math.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1Getters * @author dYdX * * @dev Some external getter functions. */ abstract contract SM1Getters is SM1Storage { using SafeMath for uint256; // ============ External Functions ============ /** * @notice The parameters specifying the function from timestamp to epoch number. * * @return The parameters struct with `interval` and `offset` fields. */ function getEpochParameters() external view returns (SM1Types.EpochParameters memory) { return _EPOCH_PARAMETERS_; } /** * @notice The period of time at the end of each epoch in which withdrawals cannot be requested. * * @return The blackout window duration, in seconds. */ function getBlackoutWindow() external view returns (uint256) { return _BLACKOUT_WINDOW_; } /** * @notice Get the domain separator used for EIP-712 signatures. * * @return The EIP-712 domain separator. */ function getDomainSeparator() external view returns (bytes32) { return _DOMAIN_SEPARATOR_; } /** * @notice The value of one underlying token, in the units used for staked balances, denominated * as a mutiple of EXCHANGE_RATE_BASE for additional precision. * * To convert from an underlying amount to a staked amount, multiply by the exchange rate. * * @return The exchange rate. */ function getExchangeRate() external view returns (uint256) { return _EXCHANGE_RATE_; } /** * @notice Get an exchange rate snapshot. * * @param index The index number of the exchange rate snapshot. * * @return The snapshot struct with `blockNumber` and `value` fields. */ function getExchangeRateSnapshot( uint256 index ) external view returns (SM1Types.Snapshot memory) { return _EXCHANGE_RATE_SNAPSHOTS_[index]; } /** * @notice Get the number of exchange rate snapshots. * * @return The number of snapshots that have been taken of the exchange rate. */ function getExchangeRateSnapshotCount() external view returns (uint256) { return _EXCHANGE_RATE_SNAPSHOT_COUNT_; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { SM1Roles } from './SM1Roles.sol'; import { SM1Staking } from './SM1Staking.sol'; /** * @title SM1Operators * @author dYdX * * @dev Actions which may be called by authorized operators, nominated by the contract owner. * * There are two types of operators. These should be smart contracts, which can be used to * provide additional functionality to users: * * STAKE_OPERATOR_ROLE: * * This operator is allowed to request withdrawals and withdraw funds on behalf of stakers. This * role could be used by a smart contract to provide a staking interface with additional * features, for example, optional lock-up periods that pay out additional rewards (from a * separate rewards pool). * * CLAIM_OPERATOR_ROLE: * * This operator is allowed to claim rewards on behalf of stakers. This role could be used by a * smart contract to provide an interface for claiming rewards from multiple incentive programs * at once. */ abstract contract SM1Operators is SM1Staking, SM1Roles { using SafeMath for uint256; // ============ Events ============ event OperatorStakedFor( address indexed staker, uint256 amount, address operator ); event OperatorWithdrawalRequestedFor( address indexed staker, uint256 amount, address operator ); event OperatorWithdrewStakeFor( address indexed staker, address recipient, uint256 amount, address operator ); event OperatorClaimedRewardsFor( address indexed staker, address recipient, uint256 claimedRewards, address operator ); // ============ External Functions ============ /** * @notice Request a withdrawal on behalf of a staker. * * Reverts if we are currently in the blackout window. * * @param staker The staker whose stake to request a withdrawal for. * @param stakeAmount The amount of stake to move from the active to the inactive balance. */ function requestWithdrawalFor( address staker, uint256 stakeAmount ) external onlyRole(STAKE_OPERATOR_ROLE) nonReentrant { _requestWithdrawal(staker, stakeAmount); emit OperatorWithdrawalRequestedFor(staker, stakeAmount, msg.sender); } /** * @notice Withdraw a staker's stake, and send to the specified recipient. * * @param staker The staker whose stake to withdraw. * @param recipient The address that should receive the funds. * @param stakeAmount The amount of stake to withdraw from the staker's inactive balance. */ function withdrawStakeFor( address staker, address recipient, uint256 stakeAmount ) external onlyRole(STAKE_OPERATOR_ROLE) nonReentrant { _withdrawStake(staker, recipient, stakeAmount); emit OperatorWithdrewStakeFor(staker, recipient, stakeAmount, msg.sender); } /** * @notice Claim rewards on behalf of a staker, and send them to the specified recipient. * * @param staker The staker whose rewards to claim. * @param recipient The address that should receive the funds. * * @return The number of rewards tokens claimed. */ function claimRewardsFor( address staker, address recipient ) external onlyRole(CLAIM_OPERATOR_ROLE) nonReentrant returns (uint256) { uint256 rewards = _settleAndClaimRewards(staker, recipient); // Emits an event internally. emit OperatorClaimedRewardsFor(staker, recipient, rewards, msg.sender); return rewards; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Roles } from './SM1Roles.sol'; import { SM1Staking } from './SM1Staking.sol'; /** * @title SM1Slashing * @author dYdX * * @dev Provides the slashing function for removing funds from the contract. * * SLASHING: * * All funds in the contract, active or inactive, are slashable. Slashes are recorded by updating * the exchange rate, and to simplify the technical implementation, we disallow full slashes. * To reduce the possibility of overflow in the exchange rate, we place an upper bound on the * fraction of funds that may be slashed in a single slash. * * Warning: Slashing is not possible if the slash would cause the exchange rate to overflow. * * REWARDS AND GOVERNANCE POWER ACCOUNTING: * * Since all slashes are accounted for by a global exchange rate, slashes do not require any * update to staked balances. The earning of rewards is unaffected by slashes. * * Governance power takes slashes into account by using snapshots of the exchange rate inside * the getPowerAtBlock() function. Note that getPowerAtBlock() returns the governance power as of * the end of the specified block. */ abstract contract SM1Slashing is SM1Staking, SM1Roles { using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Constants ============ /// @notice The maximum fraction of funds that may be slashed in a single slash (numerator). uint256 public constant MAX_SLASH_NUMERATOR = 95; /// @notice The maximum fraction of funds that may be slashed in a single slash (denominator). uint256 public constant MAX_SLASH_DENOMINATOR = 100; // ============ Events ============ event Slashed( uint256 amount, address recipient, uint256 newExchangeRate ); // ============ External Functions ============ /** * @notice Slash staked token balances and withdraw those funds to the specified address. * * @param requestedSlashAmount The request slash amount, denominated in the underlying token. * @param recipient The address to receive the slashed tokens. * * @return The amount slashed, denominated in the underlying token. */ function slash( uint256 requestedSlashAmount, address recipient ) external onlyRole(SLASHER_ROLE) nonReentrant returns (uint256) { uint256 underlyingBalance = STAKED_TOKEN.balanceOf(address(this)); if (underlyingBalance == 0) { return 0; } // Get the slash amount and remaining amount. Note that remainingAfterSlash is nonzero. uint256 maxSlashAmount = underlyingBalance.mul(MAX_SLASH_NUMERATOR).div(MAX_SLASH_DENOMINATOR); uint256 slashAmount = Math.min(requestedSlashAmount, maxSlashAmount); uint256 remainingAfterSlash = underlyingBalance.sub(slashAmount); if (slashAmount == 0) { return 0; } // Update the exchange rate. // // Warning: Can revert if the max exchange rate is exceeded. uint256 newExchangeRate = updateExchangeRate(underlyingBalance, remainingAfterSlash); // Transfer the slashed token. STAKED_TOKEN.safeTransfer(recipient, slashAmount); emit Slashed(slashAmount, recipient, newExchangeRate); return slashAmount; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1ERC20 } from './SM1ERC20.sol'; import { SM1StakedBalances } from './SM1StakedBalances.sol'; /** * @title SM1Staking * @author dYdX * * @dev External functions for stakers. See SM1StakedBalances for details on staker accounting. * * UNDERLYING AND STAKED AMOUNTS: * * We distinguish between underlying amounts and stake amounts. An underlying amount is denoted * in the original units of the token being staked. A stake amount is adjusted by the exchange * rate, which can increase due to slashing. Before any slashes have occurred, the exchange rate * is equal to one. */ abstract contract SM1Staking is SM1StakedBalances, SM1ERC20 { using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Events ============ event Staked( address indexed staker, address spender, uint256 underlyingAmount, uint256 stakeAmount ); event WithdrawalRequested( address indexed staker, uint256 stakeAmount ); event WithdrewStake( address indexed staker, address recipient, uint256 underlyingAmount, uint256 stakeAmount ); // ============ Constants ============ IERC20 public immutable STAKED_TOKEN; // ============ Constructor ============ constructor( IERC20 stakedToken, IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) SM1StakedBalances(rewardsToken, rewardsTreasury, distributionStart, distributionEnd) { STAKED_TOKEN = stakedToken; } // ============ External Functions ============ /** * @notice Deposit and stake funds. These funds are active and start earning rewards immediately. * * @param underlyingAmount The amount of underlying token to stake. */ function stake( uint256 underlyingAmount ) external nonReentrant { _stake(msg.sender, underlyingAmount); } /** * @notice Deposit and stake on behalf of another address. * * @param staker The staker who will receive the stake. * @param underlyingAmount The amount of underlying token to stake. */ function stakeFor( address staker, uint256 underlyingAmount ) external nonReentrant { _stake(staker, underlyingAmount); } /** * @notice Request to withdraw funds. Starting in the next epoch, the funds will be “inactive” * and available for withdrawal. Inactive funds do not earn rewards. * * Reverts if we are currently in the blackout window. * * @param stakeAmount The amount of stake to move from the active to the inactive balance. */ function requestWithdrawal( uint256 stakeAmount ) external nonReentrant { _requestWithdrawal(msg.sender, stakeAmount); } /** * @notice Withdraw the sender's inactive funds, and send to the specified recipient. * * @param recipient The address that should receive the funds. * @param stakeAmount The amount of stake to withdraw from the sender's inactive balance. */ function withdrawStake( address recipient, uint256 stakeAmount ) external nonReentrant { _withdrawStake(msg.sender, recipient, stakeAmount); } /** * @notice Withdraw the max available inactive funds, and send to the specified recipient. * * This is less gas-efficient than querying the max via eth_call and calling withdrawStake(). * * @param recipient The address that should receive the funds. * * @return The withdrawn amount. */ function withdrawMaxStake( address recipient ) external nonReentrant returns (uint256) { uint256 stakeAmount = getStakeAvailableToWithdraw(msg.sender); _withdrawStake(msg.sender, recipient, stakeAmount); return stakeAmount; } /** * @notice Settle and claim all rewards, and send them to the specified recipient. * * Call this function with eth_call to query the claimable rewards balance. * * @param recipient The address that should receive the funds. * * @return The number of rewards tokens claimed. */ function claimRewards( address recipient ) external nonReentrant returns (uint256) { return _settleAndClaimRewards(msg.sender, recipient); // Emits an event internally. } // ============ Public Functions ============ /** * @notice Get the amount of stake available for a given staker to withdraw. * * @param staker The address whose balance to check. * * @return The staker's stake amount that is inactive and available to withdraw. */ function getStakeAvailableToWithdraw( address staker ) public view returns (uint256) { // Note that the next epoch inactive balance is always at least that of the current epoch. return getInactiveBalanceCurrentEpoch(staker); } // ============ Internal Functions ============ function _stake( address staker, uint256 underlyingAmount ) internal { // Convert using the exchange rate. uint256 stakeAmount = stakeAmountFromUnderlyingAmount(underlyingAmount); // Update staked balances and delegate snapshots. _increaseCurrentAndNextActiveBalance(staker, stakeAmount); _moveDelegatesForTransfer(address(0), staker, stakeAmount); // Transfer token from the sender. STAKED_TOKEN.safeTransferFrom(msg.sender, address(this), underlyingAmount); emit Staked(staker, msg.sender, underlyingAmount, stakeAmount); emit Transfer(address(0), msg.sender, stakeAmount); } function _requestWithdrawal( address staker, uint256 stakeAmount ) internal { require( !inBlackoutWindow(), 'SM1Staking: Withdraw requests restricted in the blackout window' ); // Get the staker's requestable amount and revert if there is not enough to request withdrawal. uint256 requestableBalance = getActiveBalanceNextEpoch(staker); require( stakeAmount <= requestableBalance, 'SM1Staking: Withdraw request exceeds next active balance' ); // Move amount from active to inactive in the next epoch. _moveNextBalanceActiveToInactive(staker, stakeAmount); emit WithdrawalRequested(staker, stakeAmount); } function _withdrawStake( address staker, address recipient, uint256 stakeAmount ) internal { // Get staker withdrawable balance and revert if there is not enough to withdraw. uint256 withdrawableBalance = getInactiveBalanceCurrentEpoch(staker); require( stakeAmount <= withdrawableBalance, 'SM1Staking: Withdraw amount exceeds staker inactive balance' ); // Update staked balances and delegate snapshots. _decreaseCurrentAndNextInactiveBalance(staker, stakeAmount); _moveDelegatesForTransfer(staker, address(0), stakeAmount); // Convert using the exchange rate. uint256 underlyingAmount = underlyingAmountFromStakeAmount(stakeAmount); // Transfer token to the recipient. STAKED_TOKEN.safeTransfer(recipient, underlyingAmount); emit Transfer(msg.sender, address(0), stakeAmount); emit WithdrewStake(staker, recipient, underlyingAmount, stakeAmount); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, 'Address: insufficient balance'); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(''); require(success, 'Address: unable to send value, recipient may have reverted'); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; library SM1Types { /** * @dev The parameters used to convert a timestamp to an epoch number. */ struct EpochParameters { uint128 interval; uint128 offset; } /** * @dev Snapshot of a value at a specific block, used to track historical governance power. */ struct Snapshot { uint256 blockNumber; uint256 value; } /** * @dev A balance, possibly with a change scheduled for the next epoch. * * @param currentEpoch The epoch in which the balance was last updated. * @param currentEpochBalance The balance at epoch `currentEpoch`. * @param nextEpochBalance The balance at epoch `currentEpoch + 1`. */ struct StoredBalance { uint16 currentEpoch; uint240 currentEpochBalance; uint240 nextEpochBalance; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1Roles * @author dYdX * * @dev Defines roles used in the SafetyModuleV1 contract. The hierarchy of roles and powers * of each role are described below. * * Roles: * * OWNER_ROLE * | -> May add or remove addresses from any of the roles below. * | * +-- SLASHER_ROLE * | -> Can slash staked token balances and withdraw those funds. * | * +-- EPOCH_PARAMETERS_ROLE * | -> May set epoch parameters such as the interval, offset, and blackout window. * | * +-- REWARDS_RATE_ROLE * | -> May set the emission rate of rewards. * | * +-- CLAIM_OPERATOR_ROLE * | -> May claim rewards on behalf of a user. * | * +-- STAKE_OPERATOR_ROLE * -> May manipulate user's staked funds (e.g. perform withdrawals on behalf of a user). */ abstract contract SM1Roles is SM1Storage { bytes32 public constant OWNER_ROLE = keccak256('OWNER_ROLE'); bytes32 public constant SLASHER_ROLE = keccak256('SLASHER_ROLE'); bytes32 public constant EPOCH_PARAMETERS_ROLE = keccak256('EPOCH_PARAMETERS_ROLE'); bytes32 public constant REWARDS_RATE_ROLE = keccak256('REWARDS_RATE_ROLE'); bytes32 public constant CLAIM_OPERATOR_ROLE = keccak256('CLAIM_OPERATOR_ROLE'); bytes32 public constant STAKE_OPERATOR_ROLE = keccak256('STAKE_OPERATOR_ROLE'); function __SM1Roles_init() internal { // Assign roles to the sender. // // The STAKE_OPERATOR_ROLE and CLAIM_OPERATOR_ROLE roles are not initially assigned. // These can be assigned to other smart contracts to provide additional functionality for users. _setupRole(OWNER_ROLE, msg.sender); _setupRole(SLASHER_ROLE, msg.sender); _setupRole(EPOCH_PARAMETERS_ROLE, msg.sender); _setupRole(REWARDS_RATE_ROLE, msg.sender); // Set OWNER_ROLE as the admin of all roles. _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); _setRoleAdmin(SLASHER_ROLE, OWNER_ROLE); _setRoleAdmin(EPOCH_PARAMETERS_ROLE, OWNER_ROLE); _setRoleAdmin(REWARDS_RATE_ROLE, OWNER_ROLE); _setRoleAdmin(CLAIM_OPERATOR_ROLE, OWNER_ROLE); _setRoleAdmin(STAKE_OPERATOR_ROLE, OWNER_ROLE); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Rewards } from './SM1Rewards.sol'; /** * @title SM1StakedBalances * @author dYdX * * @dev Accounting of staked balances. * * NOTE: Functions may revert if epoch zero has not started. * * NOTE: All amounts dealt with in this file are denominated in staked units, which because of the * exchange rate, may not correspond one-to-one with the underlying token. See SM1Staking.sol. * * STAKED BALANCE ACCOUNTING: * * A staked balance is in one of two states: * - active: Earning staking rewards; cannot be withdrawn by staker; may be slashed. * - inactive: Not earning rewards; can be withdrawn by the staker; may be slashed. * * A staker may have a combination of active and inactive balances. The following operations * affect staked balances as follows: * - deposit: Increase active balance. * - request withdrawal: At the end of the current epoch, move some active funds to inactive. * - withdraw: Decrease inactive balance. * - transfer: Move some active funds to another staker. * * To encode the fact that a balance may be scheduled to change at the end of a certain epoch, we * store each balance as a struct of three fields: currentEpoch, currentEpochBalance, and * nextEpochBalance. * * REWARDS ACCOUNTING: * * Active funds earn rewards for the period of time that they remain active. This means, after * requesting a withdrawal of some funds, those funds will continue to earn rewards until the end * of the epoch. For example: * * epoch: n n + 1 n + 2 n + 3 * | | | | * +----------+----------+----------+-----... * ^ t_0: User makes a deposit. * ^ t_1: User requests a withdrawal of all funds. * ^ t_2: The funds change state from active to inactive. * * In the above scenario, the user would earn rewards for the period from t_0 to t_2, varying * with the total staked balance in that period. If the user only request a withdrawal for a part * of their balance, then the remaining balance would continue earning rewards beyond t_2. * * User rewards must be settled via SM1Rewards any time a user's active balance changes. Special * attention is paid to the the epoch boundaries, where funds may have transitioned from active * to inactive. * * SETTLEMENT DETAILS: * * Internally, this module uses the following types of operations on stored balances: * - Load: Loads a balance, while applying settlement logic internally to get the * up-to-date result. Returns settlement results without updating state. * - Store: Stores a balance. * - Load-for-update: Performs a load and applies updates as needed to rewards accounting. * Since this is state-changing, it must be followed by a store operation. * - Settle: Performs load-for-update and store operations. * * This module is responsible for maintaining the following invariants to ensure rewards are * calculated correctly: * - When an active balance is loaded for update, if a rollover occurs from one epoch to the * next, the rewards index must be settled up to the boundary at which the rollover occurs. * - Because the global rewards index is needed to update the user rewards index, the total * active balance must be settled before any staker balances are settled or loaded for update. * - A staker's balance must be settled before their rewards are settled. */ abstract contract SM1StakedBalances is SM1Rewards { using SafeCast for uint256; using SafeMath for uint256; // ============ Constructor ============ constructor( IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) SM1Rewards(rewardsToken, rewardsTreasury, distributionStart, distributionEnd) {} // ============ Public Functions ============ /** * @notice Get the current active balance of a staker. */ function getActiveBalanceCurrentEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance( _ACTIVE_BALANCES_[staker] ); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch active balance of a staker. */ function getActiveBalanceNextEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance( _ACTIVE_BALANCES_[staker] ); return uint256(balance.nextEpochBalance); } /** * @notice Get the current total active balance. */ function getTotalActiveBalanceCurrentEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance( _TOTAL_ACTIVE_BALANCE_ ); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch total active balance. */ function getTotalActiveBalanceNextEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance( _TOTAL_ACTIVE_BALANCE_ ); return uint256(balance.nextEpochBalance); } /** * @notice Get the current inactive balance of a staker. * @dev The balance is converted via the index to token units. */ function getInactiveBalanceCurrentEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } SM1Types.StoredBalance memory balance = _loadInactiveBalance(_INACTIVE_BALANCES_[staker]); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch inactive balance of a staker. * @dev The balance is converted via the index to token units. */ function getInactiveBalanceNextEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } SM1Types.StoredBalance memory balance = _loadInactiveBalance(_INACTIVE_BALANCES_[staker]); return uint256(balance.nextEpochBalance); } /** * @notice Get the current total inactive balance. */ function getTotalInactiveBalanceCurrentEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } SM1Types.StoredBalance memory balance = _loadInactiveBalance(_TOTAL_INACTIVE_BALANCE_); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch total inactive balance. */ function getTotalInactiveBalanceNextEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } SM1Types.StoredBalance memory balance = _loadInactiveBalance(_TOTAL_INACTIVE_BALANCE_); return uint256(balance.nextEpochBalance); } /** * @notice Get the current transferable balance for a user. The user can * only transfer their balance that is not currently inactive or going to be * inactive in the next epoch. Note that this means the user's transferable funds * are their active balance of the next epoch. * * @param account The account to get the transferable balance of. * * @return The user's transferable balance. */ function getTransferableBalance( address account ) public view returns (uint256) { return getActiveBalanceNextEpoch(account); } // ============ Internal Functions ============ function _increaseCurrentAndNextActiveBalance( address staker, uint256 amount ) internal { // Always settle total active balance before settling a staker active balance. uint256 oldTotalBalance = _increaseCurrentAndNextBalances(address(0), true, amount); uint256 oldUserBalance = _increaseCurrentAndNextBalances(staker, true, amount); // When an active balance changes at current timestamp, settle rewards to the current timestamp. _settleUserRewardsUpToNow(staker, oldUserBalance, oldTotalBalance); } function _moveNextBalanceActiveToInactive( address staker, uint256 amount ) internal { // Decrease the active balance for the next epoch. // Always settle total active balance before settling a staker active balance. _decreaseNextBalance(address(0), true, amount); _decreaseNextBalance(staker, true, amount); // Increase the inactive balance for the next epoch. _increaseNextBalance(address(0), false, amount); _increaseNextBalance(staker, false, amount); // Note that we don't need to settle rewards since the current active balance did not change. } function _transferCurrentAndNextActiveBalance( address sender, address recipient, uint256 amount ) internal { // Always settle total active balance before settling a staker active balance. uint256 totalBalance = _settleTotalActiveBalance(); // Move current and next active balances from sender to recipient. uint256 oldSenderBalance = _decreaseCurrentAndNextBalances(sender, true, amount); uint256 oldRecipientBalance = _increaseCurrentAndNextBalances(recipient, true, amount); // When an active balance changes at current timestamp, settle rewards to the current timestamp. _settleUserRewardsUpToNow(sender, oldSenderBalance, totalBalance); _settleUserRewardsUpToNow(recipient, oldRecipientBalance, totalBalance); } function _decreaseCurrentAndNextInactiveBalance( address staker, uint256 amount ) internal { // Decrease the inactive balance for the next epoch. _decreaseCurrentAndNextBalances(address(0), false, amount); _decreaseCurrentAndNextBalances(staker, false, amount); // Note that we don't settle rewards since active balances are not affected. } function _settleTotalActiveBalance() internal returns (uint256) { return _settleBalance(address(0), true); } function _settleAndClaimRewards( address staker, address recipient ) internal returns (uint256) { // Always settle total active balance before settling a staker active balance. uint256 totalBalance = _settleTotalActiveBalance(); // Always settle staker active balance before settling staker rewards. uint256 userBalance = _settleBalance(staker, true); // Settle rewards balance since we want to claim the full accrued amount. _settleUserRewardsUpToNow(staker, userBalance, totalBalance); // Claim rewards balance. return _claimRewards(staker, recipient); } // ============ Private Functions ============ /** * @dev Load a balance for update and then store it. */ function _settleBalance( address maybeStaker, bool isActiveBalance ) private returns (uint256) { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 currentBalance = uint256(balance.currentEpochBalance); _storeBalance(balancePtr, balance); return currentBalance; } /** * @dev Settle a balance while applying an increase. */ function _increaseCurrentAndNextBalances( address maybeStaker, bool isActiveBalance, uint256 amount ) private returns (uint256) { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 originalCurrentBalance = uint256(balance.currentEpochBalance); balance.currentEpochBalance = originalCurrentBalance.add(amount).toUint240(); balance.nextEpochBalance = uint256(balance.nextEpochBalance).add(amount).toUint240(); _storeBalance(balancePtr, balance); return originalCurrentBalance; } /** * @dev Settle a balance while applying a decrease. */ function _decreaseCurrentAndNextBalances( address maybeStaker, bool isActiveBalance, uint256 amount ) private returns (uint256) { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 originalCurrentBalance = uint256(balance.currentEpochBalance); balance.currentEpochBalance = originalCurrentBalance.sub(amount).toUint240(); balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(amount).toUint240(); _storeBalance(balancePtr, balance); return originalCurrentBalance; } /** * @dev Settle a balance while applying an increase. */ function _increaseNextBalance( address maybeStaker, bool isActiveBalance, uint256 amount ) private { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); balance.nextEpochBalance = uint256(balance.nextEpochBalance).add(amount).toUint240(); _storeBalance(balancePtr, balance); } /** * @dev Settle a balance while applying a decrease. */ function _decreaseNextBalance( address maybeStaker, bool isActiveBalance, uint256 amount ) private { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(amount).toUint240(); _storeBalance(balancePtr, balance); } function _getBalancePtr( address maybeStaker, bool isActiveBalance ) private view returns (SM1Types.StoredBalance storage) { // Active. if (isActiveBalance) { if (maybeStaker != address(0)) { return _ACTIVE_BALANCES_[maybeStaker]; } return _TOTAL_ACTIVE_BALANCE_; } // Inactive. if (maybeStaker != address(0)) { return _INACTIVE_BALANCES_[maybeStaker]; } return _TOTAL_INACTIVE_BALANCE_; } /** * @dev Load a balance for updating. * * IMPORTANT: This function may modify state, and so the balance MUST be stored afterwards. * - For active balances: * - If a rollover occurs, rewards are settled up to the epoch boundary. * * @param balancePtr A storage pointer to the balance. * @param maybeStaker The user address, or address(0) to update total balance. * @param isActiveBalance Whether the balance is an active balance. */ function _loadBalanceForUpdate( SM1Types.StoredBalance storage balancePtr, address maybeStaker, bool isActiveBalance ) private returns (SM1Types.StoredBalance memory) { // Active balance. if (isActiveBalance) { ( SM1Types.StoredBalance memory balance, uint256 beforeRolloverEpoch, uint256 beforeRolloverBalance, bool didRolloverOccur ) = _loadActiveBalance(balancePtr); if (didRolloverOccur) { // Handle the effect of the balance rollover on rewards. We must partially settle the index // up to the epoch boundary where the change in balance occurred. We pass in the balance // from before the boundary. if (maybeStaker == address(0)) { // If it's the total active balance... _settleGlobalIndexUpToEpoch(beforeRolloverBalance, beforeRolloverEpoch); } else { // If it's a user active balance... _settleUserRewardsUpToEpoch(maybeStaker, beforeRolloverBalance, beforeRolloverEpoch); } } return balance; } // Inactive balance. return _loadInactiveBalance(balancePtr); } function _loadActiveBalance( SM1Types.StoredBalance storage balancePtr ) private view returns ( SM1Types.StoredBalance memory, uint256, uint256, bool ) { SM1Types.StoredBalance memory balance = balancePtr; // Return these as they may be needed for rewards settlement. uint256 beforeRolloverEpoch = uint256(balance.currentEpoch); uint256 beforeRolloverBalance = uint256(balance.currentEpochBalance); bool didRolloverOccur = false; // Roll the balance forward if needed. uint256 currentEpoch = getCurrentEpoch(); if (currentEpoch > uint256(balance.currentEpoch)) { didRolloverOccur = balance.currentEpochBalance != balance.nextEpochBalance; balance.currentEpoch = currentEpoch.toUint16(); balance.currentEpochBalance = balance.nextEpochBalance; } return (balance, beforeRolloverEpoch, beforeRolloverBalance, didRolloverOccur); } function _loadInactiveBalance( SM1Types.StoredBalance storage balancePtr ) private view returns (SM1Types.StoredBalance memory) { SM1Types.StoredBalance memory balance = balancePtr; // Roll the balance forward if needed. uint256 currentEpoch = getCurrentEpoch(); if (currentEpoch > uint256(balance.currentEpoch)) { balance.currentEpoch = currentEpoch.toUint16(); balance.currentEpochBalance = balance.nextEpochBalance; } return balance; } /** * @dev Store a balance. */ function _storeBalance( SM1Types.StoredBalance storage balancePtr, SM1Types.StoredBalance memory balance ) private { // Note: This should use a single `sstore` when compiler optimizations are enabled. balancePtr.currentEpoch = balance.currentEpoch; balancePtr.currentEpochBalance = balance.currentEpochBalance; balancePtr.nextEpochBalance = balance.nextEpochBalance; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { AccessControlUpgradeable } from '../../../dependencies/open-zeppelin/AccessControlUpgradeable.sol'; import { ReentrancyGuard } from '../../../utils/ReentrancyGuard.sol'; import { VersionedInitializable } from '../../../utils/VersionedInitializable.sol'; import { SM1Types } from '../lib/SM1Types.sol'; /** * @title SM1Storage * @author dYdX * * @dev Storage contract. Contains or inherits from all contract with storage. */ abstract contract SM1Storage is AccessControlUpgradeable, ReentrancyGuard, VersionedInitializable { // ============ Epoch Schedule ============ /// @dev The parameters specifying the function from timestamp to epoch number. SM1Types.EpochParameters internal _EPOCH_PARAMETERS_; /// @dev The period of time at the end of each epoch in which withdrawals cannot be requested. uint256 internal _BLACKOUT_WINDOW_; // ============ Staked Token ERC20 ============ /// @dev Allowances for ERC-20 transfers. mapping(address => mapping(address => uint256)) internal _ALLOWANCES_; // ============ Governance Power Delegation ============ /// @dev Domain separator for EIP-712 signatures. bytes32 internal _DOMAIN_SEPARATOR_; /// @dev Mapping from (owner) => (next valid nonce) for EIP-712 signatures. mapping(address => uint256) internal _NONCES_; /// @dev Snapshots and delegates for governance voting power. mapping(address => mapping(uint256 => SM1Types.Snapshot)) internal _VOTING_SNAPSHOTS_; mapping(address => uint256) internal _VOTING_SNAPSHOT_COUNTS_; mapping(address => address) internal _VOTING_DELEGATES_; /// @dev Snapshots and delegates for governance proposition power. mapping(address => mapping(uint256 => SM1Types.Snapshot)) internal _PROPOSITION_SNAPSHOTS_; mapping(address => uint256) internal _PROPOSITION_SNAPSHOT_COUNTS_; mapping(address => address) internal _PROPOSITION_DELEGATES_; // ============ Rewards Accounting ============ /// @dev The emission rate of rewards. uint256 internal _REWARDS_PER_SECOND_; /// @dev The cumulative rewards earned per staked token. (Shared storage slot.) uint224 internal _GLOBAL_INDEX_; /// @dev The timestamp at which the global index was last updated. (Shared storage slot.) uint32 internal _GLOBAL_INDEX_TIMESTAMP_; /// @dev The value of the global index when the user's staked balance was last updated. mapping(address => uint256) internal _USER_INDEXES_; /// @dev The user's accrued, unclaimed rewards (as of the last update to the user index). mapping(address => uint256) internal _USER_REWARDS_BALANCES_; /// @dev The value of the global index at the end of a given epoch. mapping(uint256 => uint256) internal _EPOCH_INDEXES_; // ============ Staker Accounting ============ /// @dev The active balance by staker. mapping(address => SM1Types.StoredBalance) internal _ACTIVE_BALANCES_; /// @dev The total active balance of stakers. SM1Types.StoredBalance internal _TOTAL_ACTIVE_BALANCE_; /// @dev The inactive balance by staker. mapping(address => SM1Types.StoredBalance) internal _INACTIVE_BALANCES_; /// @dev The total inactive balance of stakers. SM1Types.StoredBalance internal _TOTAL_INACTIVE_BALANCE_; // ============ Exchange Rate ============ /// @dev The value of one underlying token, in the units used for staked balances, denominated /// as a mutiple of EXCHANGE_RATE_BASE for additional precision. uint256 internal _EXCHANGE_RATE_; /// @dev Historical snapshots of the exchange rate, in each block that it has changed. mapping(uint256 => SM1Types.Snapshot) internal _EXCHANGE_RATE_SNAPSHOTS_; /// @dev Number of snapshots of the exchange rate. uint256 internal _EXCHANGE_RATE_SNAPSHOT_COUNT_; } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './Context.sol'; import './Strings.sol'; import './ERC165.sol'; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { 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 AccessControlUpgradeable is Context, IAccessControlUpgradeable, 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(IAccessControlUpgradeable).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()); } } uint256[49] private __gap; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title ReentrancyGuard * @author dYdX * * @dev Updated ReentrancyGuard library designed to be used with Proxy Contracts. */ abstract contract ReentrancyGuard { uint256 private constant NOT_ENTERED = 1; uint256 private constant ENTERED = uint256(int256(-1)); uint256 private _STATUS_; constructor() internal { _STATUS_ = NOT_ENTERED; } modifier nonReentrant() { require(_STATUS_ != ENTERED, 'ReentrancyGuard: reentrant call'); _STATUS_ = ENTERED; _; _STATUS_ = NOT_ENTERED; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; /** * @title VersionedInitializable * @author Aave, inspired by the OpenZeppelin Initializable contract * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. * */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 internal lastInitializedRevision = 0; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { uint256 revision = getRevision(); require(revision > lastInitializedRevision, "Contract instance has already been initialized"); lastInitializedRevision = revision; _; } /// @dev returns the revision number of the contract. /// Needs to be defined in the inherited class as a constant. function getRevision() internal pure virtual returns(uint256); // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /* * @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.5; /** * @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.7.5; 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.7.5; /** * @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: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @dev Methods for downcasting unsigned integers, reverting on overflow. */ library SafeCast { /** * @dev Downcast to a uint16, reverting on overflow. */ function toUint16( uint256 a ) internal pure returns (uint16) { uint16 b = uint16(a); require( uint256(b) == a, 'SafeCast: toUint16 overflow' ); return b; } /** * @dev Downcast to a uint32, reverting on overflow. */ function toUint32( uint256 a ) internal pure returns (uint32) { uint32 b = uint32(a); require( uint256(b) == a, 'SafeCast: toUint32 overflow' ); return b; } /** * @dev Downcast to a uint128, reverting on overflow. */ function toUint128( uint256 a ) internal pure returns (uint128) { uint128 b = uint128(a); require( uint256(b) == a, 'SafeCast: toUint128 overflow' ); return b; } /** * @dev Downcast to a uint224, reverting on overflow. */ function toUint224( uint256 a ) internal pure returns (uint224) { uint224 b = uint224(a); require( uint256(b) == a, 'SafeCast: toUint224 overflow' ); return b; } /** * @dev Downcast to a uint240, reverting on overflow. */ function toUint240( uint256 a ) internal pure returns (uint240) { uint240 b = uint240(a); require( uint256(b) == a, 'SafeCast: toUint240 overflow' ); return b; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { SM1EpochSchedule } from './SM1EpochSchedule.sol'; /** * @title SM1Rewards * @author dYdX * * @dev Manages the distribution of token rewards. * * Rewards are distributed continuously. After each second, an account earns rewards `r` according * to the following formula: * * r = R * s / S * * Where: * - `R` is the rewards distributed globally each second, also called the “emission rate.” * - `s` is the account's staked balance in that second (technically, it is measured at the * end of the second) * - `S` is the sum total of all staked balances in that second (again, measured at the end of * the second) * * The parameter `R` can be configured by the contract owner. For every second that elapses, * exactly `R` tokens will accrue to users, save for rounding errors, and with the exception that * while the total staked balance is zero, no tokens will accrue to anyone. * * The accounting works as follows: A global index is stored which represents the cumulative * number of rewards tokens earned per staked token since the start of the distribution. * The value of this index increases over time, and there are two factors affecting the rate of * increase: * 1) The emission rate (in the numerator) * 2) The total number of staked tokens (in the denominator) * * Whenever either factor changes, in some timestamp T, we settle the global index up to T by * calculating the increase in the index since the last update using the OLD values of the factors: * * indexDelta = timeDelta * emissionPerSecond * INDEX_BASE / totalStaked * * Where `INDEX_BASE` is a scaling factor used to allow more precision in the storage of the index. * * For each user we store an accrued rewards balance, as well as a user index, which is a cache of * the global index at the time that the user's accrued rewards balance was last updated. Then at * any point in time, a user's claimable rewards are represented by the following: * * rewards = _USER_REWARDS_BALANCES_[user] + userStaked * ( * settledGlobalIndex - _USER_INDEXES_[user] * ) / INDEX_BASE */ abstract contract SM1Rewards is SM1EpochSchedule { using SafeCast for uint256; using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Constants ============ /// @dev Additional precision used to represent the global and user index values. uint256 private constant INDEX_BASE = 10**18; /// @notice The rewards token. IERC20 public immutable REWARDS_TOKEN; /// @notice Address to pull rewards from. Must have provided an allowance to this contract. address public immutable REWARDS_TREASURY; /// @notice Start timestamp (inclusive) of the period in which rewards can be earned. uint256 public immutable DISTRIBUTION_START; /// @notice End timestamp (exclusive) of the period in which rewards can be earned. uint256 public immutable DISTRIBUTION_END; // ============ Events ============ event RewardsPerSecondUpdated( uint256 emissionPerSecond ); event GlobalIndexUpdated( uint256 index ); event UserIndexUpdated( address indexed user, uint256 index, uint256 unclaimedRewards ); event ClaimedRewards( address indexed user, address recipient, uint256 claimedRewards ); // ============ Constructor ============ constructor( IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) { require( distributionEnd >= distributionStart, 'SM1Rewards: Invalid parameters' ); REWARDS_TOKEN = rewardsToken; REWARDS_TREASURY = rewardsTreasury; DISTRIBUTION_START = distributionStart; DISTRIBUTION_END = distributionEnd; } // ============ External Functions ============ /** * @notice The current emission rate of rewards. * * @return The number of rewards tokens issued globally each second. */ function getRewardsPerSecond() external view returns (uint256) { return _REWARDS_PER_SECOND_; } // ============ Internal Functions ============ /** * @dev Initialize the contract. */ function __SM1Rewards_init() internal { _GLOBAL_INDEX_TIMESTAMP_ = Math.max(block.timestamp, DISTRIBUTION_START).toUint32(); } /** * @dev Set the emission rate of rewards. * * IMPORTANT: Do not call this function without settling the total staked balance first, to * ensure that the index is settled up to the epoch boundaries. * * @param emissionPerSecond The new number of rewards tokens to give out each second. * @param totalStaked The total staked balance. */ function _setRewardsPerSecond( uint256 emissionPerSecond, uint256 totalStaked ) internal { _settleGlobalIndexUpToNow(totalStaked); _REWARDS_PER_SECOND_ = emissionPerSecond; emit RewardsPerSecondUpdated(emissionPerSecond); } /** * @dev Claim tokens, sending them to the specified recipient. * * Note: In order to claim all accrued rewards, the total and user staked balances must first be * settled before calling this function. * * @param user The user's address. * @param recipient The address to send rewards to. * * @return The number of rewards tokens claimed. */ function _claimRewards( address user, address recipient ) internal returns (uint256) { uint256 accruedRewards = _USER_REWARDS_BALANCES_[user]; _USER_REWARDS_BALANCES_[user] = 0; REWARDS_TOKEN.safeTransferFrom(REWARDS_TREASURY, recipient, accruedRewards); emit ClaimedRewards(user, recipient, accruedRewards); return accruedRewards; } /** * @dev Settle a user's rewards up to the latest global index as of `block.timestamp`. Triggers a * settlement of the global index up to `block.timestamp`. Should be called with the OLD user * and total balances. * * @param user The user's address. * @param userStaked Tokens staked by the user during the period since the last user index * update. * @param totalStaked Total tokens staked by all users during the period since the last global * index update. * * @return The user's accrued rewards, including past unclaimed rewards. */ function _settleUserRewardsUpToNow( address user, uint256 userStaked, uint256 totalStaked ) internal returns (uint256) { uint256 globalIndex = _settleGlobalIndexUpToNow(totalStaked); return _settleUserRewardsUpToIndex(user, userStaked, globalIndex); } /** * @dev Settle a user's rewards up to an epoch boundary. Should be used to partially settle a * user's rewards if their balance was known to have changed on that epoch boundary. * * @param user The user's address. * @param userStaked Tokens staked by the user. Should be accurate for the time period * since the last update to this user and up to the end of the * specified epoch. * @param epochNumber Settle the user's rewards up to the end of this epoch. * * @return The user's accrued rewards, including past unclaimed rewards, up to the end of the * specified epoch. */ function _settleUserRewardsUpToEpoch( address user, uint256 userStaked, uint256 epochNumber ) internal returns (uint256) { uint256 globalIndex = _EPOCH_INDEXES_[epochNumber]; return _settleUserRewardsUpToIndex(user, userStaked, globalIndex); } /** * @dev Settle the global index up to the end of the given epoch. * * IMPORTANT: This function should only be called under conditions which ensure the following: * - `epochNumber` < the current epoch number * - `_GLOBAL_INDEX_TIMESTAMP_ < settleUpToTimestamp` * - `_EPOCH_INDEXES_[epochNumber] = 0` */ function _settleGlobalIndexUpToEpoch( uint256 totalStaked, uint256 epochNumber ) internal returns (uint256) { uint256 settleUpToTimestamp = getStartOfEpoch(epochNumber.add(1)); uint256 globalIndex = _settleGlobalIndexUpToTimestamp(totalStaked, settleUpToTimestamp); _EPOCH_INDEXES_[epochNumber] = globalIndex; return globalIndex; } // ============ Private Functions ============ /** * @dev Updates the global index, reflecting cumulative rewards given out per staked token. * * @param totalStaked The total staked balance, which should be constant in the interval * since the last update to the global index. * * @return The new global index. */ function _settleGlobalIndexUpToNow( uint256 totalStaked ) private returns (uint256) { return _settleGlobalIndexUpToTimestamp(totalStaked, block.timestamp); } /** * @dev Helper function which settles a user's rewards up to a global index. Should be called * any time a user's staked balance changes, with the OLD user and total balances. * * @param user The user's address. * @param userStaked Tokens staked by the user during the period since the last user index * update. * @param newGlobalIndex The new index value to bring the user index up to. MUST NOT be less * than the user's index. * * @return The user's accrued rewards, including past unclaimed rewards. */ function _settleUserRewardsUpToIndex( address user, uint256 userStaked, uint256 newGlobalIndex ) private returns (uint256) { uint256 oldAccruedRewards = _USER_REWARDS_BALANCES_[user]; uint256 oldUserIndex = _USER_INDEXES_[user]; if (oldUserIndex == newGlobalIndex) { return oldAccruedRewards; } uint256 newAccruedRewards; if (userStaked == 0) { // Note: Even if the user's staked balance is zero, we still need to update the user index. newAccruedRewards = oldAccruedRewards; } else { // Calculate newly accrued rewards since the last update to the user's index. uint256 indexDelta = newGlobalIndex.sub(oldUserIndex); uint256 accruedRewardsDelta = userStaked.mul(indexDelta).div(INDEX_BASE); newAccruedRewards = oldAccruedRewards.add(accruedRewardsDelta); // Update the user's rewards. _USER_REWARDS_BALANCES_[user] = newAccruedRewards; } // Update the user's index. _USER_INDEXES_[user] = newGlobalIndex; emit UserIndexUpdated(user, newGlobalIndex, newAccruedRewards); return newAccruedRewards; } /** * @dev Updates the global index, reflecting cumulative rewards given out per staked token. * * @param totalStaked The total staked balance, which should be constant in the interval * (_GLOBAL_INDEX_TIMESTAMP_, settleUpToTimestamp). * @param settleUpToTimestamp The timestamp up to which to settle rewards. It MUST satisfy * `settleUpToTimestamp <= block.timestamp`. * * @return The new global index. */ function _settleGlobalIndexUpToTimestamp( uint256 totalStaked, uint256 settleUpToTimestamp ) private returns (uint256) { uint256 oldGlobalIndex = uint256(_GLOBAL_INDEX_); // The goal of this function is to calculate rewards earned since the last global index update. // These rewards are earned over the time interval which is the intersection of the intervals // [_GLOBAL_INDEX_TIMESTAMP_, settleUpToTimestamp] and [DISTRIBUTION_START, DISTRIBUTION_END]. // // We can simplify a bit based on the assumption: // `_GLOBAL_INDEX_TIMESTAMP_ >= DISTRIBUTION_START` // // Get the start and end of the time interval under consideration. uint256 intervalStart = uint256(_GLOBAL_INDEX_TIMESTAMP_); uint256 intervalEnd = Math.min(settleUpToTimestamp, DISTRIBUTION_END); // Return early if the interval has length zero (incl. case where intervalEnd < intervalStart). if (intervalEnd <= intervalStart) { return oldGlobalIndex; } // Note: If we reach this point, we must update _GLOBAL_INDEX_TIMESTAMP_. uint256 emissionPerSecond = _REWARDS_PER_SECOND_; if (emissionPerSecond == 0 || totalStaked == 0) { // Ensure a log is emitted if the timestamp changed, even if the index does not change. _GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32(); emit GlobalIndexUpdated(oldGlobalIndex); return oldGlobalIndex; } // Calculate the change in index over the interval. uint256 timeDelta = intervalEnd.sub(intervalStart); uint256 indexDelta = timeDelta.mul(emissionPerSecond).mul(INDEX_BASE).div(totalStaked); // Calculate, update, and return the new global index. uint256 newGlobalIndex = oldGlobalIndex.add(indexDelta); // Update storage. (Shared storage slot.) _GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32(); _GLOBAL_INDEX_ = newGlobalIndex.toUint224(); emit GlobalIndexUpdated(newGlobalIndex); return newGlobalIndex; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../dependencies/open-zeppelin/SafeMath.sol'; /** * @title Math * @author dYdX * * @dev Library for non-standard Math functions. */ library Math { using SafeMath for uint256; // ============ Library Functions ============ /** * @dev Return `ceil(numerator / denominator)`. */ function divRoundUp( uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return numerator.sub(1).div(denominator).add(1); } /** * @dev Returns the minimum between a and b. */ function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the maximum between a and b. */ function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1EpochSchedule * @author dYdX * * @dev Defines a function from block timestamp to epoch number. * * The formula used is `n = floor((t - b) / a)` where: * - `n` is the epoch number * - `t` is the timestamp (in seconds) * - `b` is a non-negative offset, indicating the start of epoch zero (in seconds) * - `a` is the length of an epoch, a.k.a. the interval (in seconds) * * Note that by restricting `b` to be non-negative, we limit ourselves to functions in which epoch * zero starts at a non-negative timestamp. * * The recommended epoch length and blackout window are 28 and 7 days respectively; however, these * are modifiable by the admin, within the specified bounds. */ abstract contract SM1EpochSchedule is SM1Storage { using SafeCast for uint256; using SafeMath for uint256; // ============ Events ============ event EpochParametersChanged( SM1Types.EpochParameters epochParameters ); event BlackoutWindowChanged( uint256 blackoutWindow ); // ============ Initializer ============ function __SM1EpochSchedule_init( uint256 interval, uint256 offset, uint256 blackoutWindow ) internal { require( block.timestamp < offset, 'SM1EpochSchedule: Epoch zero must start after initialization' ); _setBlackoutWindow(blackoutWindow); _setEpochParameters(interval, offset); } // ============ Public Functions ============ /** * @notice Get the epoch at the current block timestamp. * * NOTE: Reverts if epoch zero has not started. * * @return The current epoch number. */ function getCurrentEpoch() public view returns (uint256) { (uint256 interval, uint256 offsetTimestamp) = _getIntervalAndOffsetTimestamp(); return offsetTimestamp.div(interval); } /** * @notice Get the time remaining in the current epoch. * * NOTE: Reverts if epoch zero has not started. * * @return The number of seconds until the next epoch. */ function getTimeRemainingInCurrentEpoch() public view returns (uint256) { (uint256 interval, uint256 offsetTimestamp) = _getIntervalAndOffsetTimestamp(); uint256 timeElapsedInEpoch = offsetTimestamp.mod(interval); return interval.sub(timeElapsedInEpoch); } /** * @notice Given an epoch number, get the start of that epoch. Calculated as `t = (n * a) + b`. * * @return The timestamp in seconds representing the start of that epoch. */ function getStartOfEpoch( uint256 epochNumber ) public view returns (uint256) { SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 interval = uint256(epochParameters.interval); uint256 offset = uint256(epochParameters.offset); return epochNumber.mul(interval).add(offset); } /** * @notice Check whether we are at or past the start of epoch zero. * * @return Boolean `true` if the current timestamp is at least the start of epoch zero, * otherwise `false`. */ function hasEpochZeroStarted() public view returns (bool) { SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 offset = uint256(epochParameters.offset); return block.timestamp >= offset; } /** * @notice Check whether we are in a blackout window, where withdrawal requests are restricted. * Note that before epoch zero has started, there are no blackout windows. * * @return Boolean `true` if we are in a blackout window, otherwise `false`. */ function inBlackoutWindow() public view returns (bool) { return hasEpochZeroStarted() && getTimeRemainingInCurrentEpoch() <= _BLACKOUT_WINDOW_; } // ============ Internal Functions ============ function _setEpochParameters( uint256 interval, uint256 offset ) internal { SM1Types.EpochParameters memory epochParameters = SM1Types.EpochParameters({interval: interval.toUint128(), offset: offset.toUint128()}); _EPOCH_PARAMETERS_ = epochParameters; emit EpochParametersChanged(epochParameters); } function _setBlackoutWindow( uint256 blackoutWindow ) internal { _BLACKOUT_WINDOW_ = blackoutWindow; emit BlackoutWindowChanged(blackoutWindow); } // ============ Private Functions ============ /** * @dev Helper function to read params from storage and apply offset to the given timestamp. * Recall that the formula for epoch number is `n = (t - b) / a`. * * NOTE: Reverts if epoch zero has not started. * * @return The values `a` and `(t - b)`. */ function _getIntervalAndOffsetTimestamp() private view returns (uint256, uint256) { SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 interval = uint256(epochParameters.interval); uint256 offset = uint256(epochParameters.offset); require( block.timestamp >= offset, 'SM1EpochSchedule: Epoch zero has not started' ); uint256 offsetTimestamp = block.timestamp.sub(offset); return (interval, offsetTimestamp); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { IERC20Detailed } from '../../../interfaces/IERC20Detailed.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1GovernancePowerDelegation } from './SM1GovernancePowerDelegation.sol'; import { SM1StakedBalances } from './SM1StakedBalances.sol'; /** * @title SM1ERC20 * @author dYdX * * @dev ERC20 interface for staked tokens. Implements governance functionality for the tokens. * * Also allows a user with an active stake to transfer their staked tokens to another user, * even if they would otherwise be restricted from withdrawing. */ abstract contract SM1ERC20 is SM1StakedBalances, SM1GovernancePowerDelegation, IERC20Detailed { using SafeMath for uint256; // ============ Constants ============ /// @notice EIP-712 typehash for token approval via EIP-2612 permit. bytes32 public constant PERMIT_TYPEHASH = keccak256( 'Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)' ); // ============ External Functions ============ function name() external pure override returns (string memory) { return 'Staked DYDX'; } function symbol() external pure override returns (string memory) { return 'stkDYDX'; } function decimals() external pure override returns (uint8) { return 18; } /** * @notice Get the total supply of staked balances. * * Note that due to the exchange rate, this is different than querying the total balance of * underyling token staked to this contract. * * @return The sum of all staked balances. */ function totalSupply() external view override returns (uint256) { return getTotalActiveBalanceCurrentEpoch() + getTotalInactiveBalanceCurrentEpoch(); } /** * @notice Get a user's staked balance. * * Note that due to the exchange rate, one unit of staked balance may not be equivalent to one * unit of the underlying token. Also note that a user's staked balance is different from a * user's transferable balance. * * @param account The account to get the balance of. * * @return The user's staked balance. */ function balanceOf( address account ) public view override(SM1GovernancePowerDelegation, IERC20) returns (uint256) { return getActiveBalanceCurrentEpoch(account) + getInactiveBalanceCurrentEpoch(account); } function transfer( address recipient, uint256 amount ) external override nonReentrant returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance( address owner, address spender ) external view override returns (uint256) { return _ALLOWANCES_[owner][spender]; } function approve( address spender, uint256 amount ) external override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external override nonReentrant returns (bool) { _transfer(sender, recipient, amount); _approve( sender, msg.sender, _ALLOWANCES_[sender][msg.sender].sub(amount, 'SM1ERC20: transfer amount exceeds allowance') ); return true; } function increaseAllowance( address spender, uint256 addedValue ) external returns (bool) { _approve(msg.sender, spender, _ALLOWANCES_[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance( address spender, uint256 subtractedValue ) external returns (bool) { _approve( msg.sender, spender, _ALLOWANCES_[msg.sender][spender].sub( subtractedValue, 'SM1ERC20: Decreased allowance below zero' ) ); return true; } /** * @notice Implements the permit function as specified in EIP-2612. * * @param owner Address of the token owner. * @param spender Address of the spender. * @param value Amount of allowance. * @param deadline Expiration timestamp for the signature. * @param v Signature param. * @param r Signature param. * @param s Signature param. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require( owner != address(0), 'SM1ERC20: INVALID_OWNER' ); require( block.timestamp <= deadline, 'SM1ERC20: INVALID_EXPIRATION' ); uint256 currentValidNonce = _NONCES_[owner]; bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', _DOMAIN_SEPARATOR_, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline)) ) ); require( owner == ecrecover(digest, v, r, s), 'SM1ERC20: INVALID_SIGNATURE' ); _NONCES_[owner] = currentValidNonce.add(1); _approve(owner, spender, value); } // ============ Internal Functions ============ function _transfer( address sender, address recipient, uint256 amount ) internal { require( sender != address(0), 'SM1ERC20: Transfer from address(0)' ); require( recipient != address(0), 'SM1ERC20: Transfer to address(0)' ); require( getTransferableBalance(sender) >= amount, 'SM1ERC20: Transfer exceeds next epoch active balance' ); // Update staked balances and delegate snapshots. _transferCurrentAndNextActiveBalance(sender, recipient, amount); _moveDelegatesForTransfer(sender, recipient, amount); emit Transfer(sender, recipient, amount); } function _approve( address owner, address spender, uint256 amount ) internal { require( owner != address(0), 'SM1ERC20: Approve from address(0)' ); require( spender != address(0), 'SM1ERC20: Approve to address(0)' ); _ALLOWANCES_[owner][spender] = amount; emit Approval(owner, spender, amount); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; import { IERC20 } from './IERC20.sol'; /** * @dev Interface for ERC20 including metadata **/ interface IERC20Detailed is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IGovernancePowerDelegationERC20 } from '../../../interfaces/IGovernancePowerDelegationERC20.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1ExchangeRate } from './SM1ExchangeRate.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1GovernancePowerDelegation * @author dYdX * * @dev Provides support for two types of governance powers which are separately delegatable. * Provides functions for delegation and for querying a user's power at a certain block number. * * Internally, makes use of staked balances denoted in staked units, but returns underlying token * units from the getPowerAtBlock() and getPowerCurrent() functions. * * This is based on, and is designed to match, Aave's implementation, which is used in their * governance token and staked token contracts. */ abstract contract SM1GovernancePowerDelegation is SM1ExchangeRate, IGovernancePowerDelegationERC20 { using SafeMath for uint256; // ============ Constants ============ /// @notice EIP-712 typehash for delegation by signature of a specific governance power type. bytes32 public constant DELEGATE_BY_TYPE_TYPEHASH = keccak256( 'DelegateByType(address delegatee,uint256 type,uint256 nonce,uint256 expiry)' ); /// @notice EIP-712 typehash for delegation by signature of all governance powers. bytes32 public constant DELEGATE_TYPEHASH = keccak256( 'Delegate(address delegatee,uint256 nonce,uint256 expiry)' ); // ============ External Functions ============ /** * @notice Delegates a specific governance power of the sender to a delegatee. * * @param delegatee The address to delegate power to. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function delegateByType( address delegatee, DelegationType delegationType ) external override { _delegateByType(msg.sender, delegatee, delegationType); } /** * @notice Delegates all governance powers of the sender to a delegatee. * * @param delegatee The address to delegate power to. */ function delegate( address delegatee ) external override { _delegateByType(msg.sender, delegatee, DelegationType.VOTING_POWER); _delegateByType(msg.sender, delegatee, DelegationType.PROPOSITION_POWER); } /** * @dev Delegates specific governance power from signer to `delegatee` using an EIP-712 signature. * * @param delegatee The address to delegate votes to. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). * @param nonce The signer's nonce for EIP-712 signatures on this contract. * @param expiry Expiration timestamp for the signature. * @param v Signature param. * @param r Signature param. * @param s Signature param. */ function delegateByTypeBySig( address delegatee, DelegationType delegationType, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 structHash = keccak256( abi.encode(DELEGATE_BY_TYPE_TYPEHASH, delegatee, uint256(delegationType), nonce, expiry) ); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', _DOMAIN_SEPARATOR_, structHash)); address signer = ecrecover(digest, v, r, s); require( signer != address(0), 'SM1GovernancePowerDelegation: INVALID_SIGNATURE' ); require( nonce == _NONCES_[signer]++, 'SM1GovernancePowerDelegation: INVALID_NONCE' ); require( block.timestamp <= expiry, 'SM1GovernancePowerDelegation: INVALID_EXPIRATION' ); _delegateByType(signer, delegatee, delegationType); } /** * @dev Delegates both governance powers from signer to `delegatee` using an EIP-712 signature. * * @param delegatee The address to delegate votes to. * @param nonce The signer's nonce for EIP-712 signatures on this contract. * @param expiry Expiration timestamp for the signature. * @param v Signature param. * @param r Signature param. * @param s Signature param. */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 structHash = keccak256(abi.encode(DELEGATE_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', _DOMAIN_SEPARATOR_, structHash)); address signer = ecrecover(digest, v, r, s); require( signer != address(0), 'SM1GovernancePowerDelegation: INVALID_SIGNATURE' ); require( nonce == _NONCES_[signer]++, 'SM1GovernancePowerDelegation: INVALID_NONCE' ); require( block.timestamp <= expiry, 'SM1GovernancePowerDelegation: INVALID_EXPIRATION' ); _delegateByType(signer, delegatee, DelegationType.VOTING_POWER); _delegateByType(signer, delegatee, DelegationType.PROPOSITION_POWER); } /** * @notice Returns the delegatee of a user. * * @param delegator The address of the delegator. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function getDelegateeByType( address delegator, DelegationType delegationType ) external override view returns (address) { (, , mapping(address => address) storage delegates) = _getDelegationDataByType(delegationType); return _getDelegatee(delegator, delegates); } /** * @notice Returns the current power of a user. The current power is the power delegated * at the time of the last snapshot. * * @param user The user whose power to query. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function getPowerCurrent( address user, DelegationType delegationType ) external override view returns (uint256) { return getPowerAtBlock(user, block.number, delegationType); } /** * @notice Get the next valid nonce for EIP-712 signatures. * * This nonce should be used when signing for any of the following functions: * - permit() * - delegateByTypeBySig() * - delegateBySig() */ function nonces( address owner ) external view returns (uint256) { return _NONCES_[owner]; } // ============ Public Functions ============ function balanceOf( address account ) public view virtual returns (uint256); /** * @notice Returns the power of a user at a certain block, denominated in underlying token units. * * @param user The user whose power to query. * @param blockNumber The block number at which to get the user's power. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). * * @return The user's governance power of the specified type, in underlying token units. */ function getPowerAtBlock( address user, uint256 blockNumber, DelegationType delegationType ) public override view returns (uint256) { ( mapping(address => mapping(uint256 => SM1Types.Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotCounts, // unused: delegates ) = _getDelegationDataByType(delegationType); uint256 stakeAmount = _findValueAtBlock( snapshots[user], snapshotCounts[user], blockNumber, 0 ); uint256 exchangeRate = _findValueAtBlock( _EXCHANGE_RATE_SNAPSHOTS_, _EXCHANGE_RATE_SNAPSHOT_COUNT_, blockNumber, EXCHANGE_RATE_BASE ); return underlyingAmountFromStakeAmountWithExchangeRate(stakeAmount, exchangeRate); } // ============ Internal Functions ============ /** * @dev Delegates one specific power to a delegatee. * * @param delegator The user whose power to delegate. * @param delegatee The address to delegate power to. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function _delegateByType( address delegator, address delegatee, DelegationType delegationType ) internal { require( delegatee != address(0), 'SM1GovernancePowerDelegation: INVALID_DELEGATEE' ); (, , mapping(address => address) storage delegates) = _getDelegationDataByType(delegationType); uint256 delegatorBalance = balanceOf(delegator); address previousDelegatee = _getDelegatee(delegator, delegates); delegates[delegator] = delegatee; _moveDelegatesByType(previousDelegatee, delegatee, delegatorBalance, delegationType); emit DelegateChanged(delegator, delegatee, delegationType); } /** * @dev Update delegate snapshots whenever staked tokens are transfered, minted, or burned. * * @param from The sender. * @param to The recipient. * @param stakedAmount The amount being transfered, denominated in staked units. */ function _moveDelegatesForTransfer( address from, address to, uint256 stakedAmount ) internal { address votingPowerFromDelegatee = _getDelegatee(from, _VOTING_DELEGATES_); address votingPowerToDelegatee = _getDelegatee(to, _VOTING_DELEGATES_); _moveDelegatesByType( votingPowerFromDelegatee, votingPowerToDelegatee, stakedAmount, DelegationType.VOTING_POWER ); address propositionPowerFromDelegatee = _getDelegatee(from, _PROPOSITION_DELEGATES_); address propositionPowerToDelegatee = _getDelegatee(to, _PROPOSITION_DELEGATES_); _moveDelegatesByType( propositionPowerFromDelegatee, propositionPowerToDelegatee, stakedAmount, DelegationType.PROPOSITION_POWER ); } /** * @dev Moves power from one user to another. * * @param from The user from which delegated power is moved. * @param to The user that will receive the delegated power. * @param amount The amount of power to be moved. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function _moveDelegatesByType( address from, address to, uint256 amount, DelegationType delegationType ) internal { if (from == to) { return; } ( mapping(address => mapping(uint256 => SM1Types.Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotCounts, // unused: delegates ) = _getDelegationDataByType(delegationType); if (from != address(0)) { mapping(uint256 => SM1Types.Snapshot) storage fromSnapshots = snapshots[from]; uint256 fromSnapshotCount = snapshotCounts[from]; uint256 previousBalance = 0; if (fromSnapshotCount != 0) { previousBalance = fromSnapshots[fromSnapshotCount - 1].value; } uint256 newBalance = previousBalance.sub(amount); snapshotCounts[from] = _writeSnapshot( fromSnapshots, fromSnapshotCount, newBalance ); emit DelegatedPowerChanged(from, newBalance, delegationType); } if (to != address(0)) { mapping(uint256 => SM1Types.Snapshot) storage toSnapshots = snapshots[to]; uint256 toSnapshotCount = snapshotCounts[to]; uint256 previousBalance = 0; if (toSnapshotCount != 0) { previousBalance = toSnapshots[toSnapshotCount - 1].value; } uint256 newBalance = previousBalance.add(amount); snapshotCounts[to] = _writeSnapshot( toSnapshots, toSnapshotCount, newBalance ); emit DelegatedPowerChanged(to, newBalance, delegationType); } } /** * @dev Returns delegation data (snapshot, snapshotCount, delegates) by delegation type. * * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). * * @return The mapping of each user to a mapping of snapshots. * @return The mapping of each user to the total number of snapshots for that user. * @return The mapping of each user to the user's delegate. */ function _getDelegationDataByType( DelegationType delegationType ) internal view returns ( mapping(address => mapping(uint256 => SM1Types.Snapshot)) storage, mapping(address => uint256) storage, mapping(address => address) storage ) { if (delegationType == DelegationType.VOTING_POWER) { return ( _VOTING_SNAPSHOTS_, _VOTING_SNAPSHOT_COUNTS_, _VOTING_DELEGATES_ ); } else { return ( _PROPOSITION_SNAPSHOTS_, _PROPOSITION_SNAPSHOT_COUNTS_, _PROPOSITION_DELEGATES_ ); } } /** * @dev Returns the delegatee of a user. If a user never performed any delegation, their * delegated address will be 0x0, in which case we return the user's own address. * * @param delegator The address of the user for which return the delegatee. * @param delegates The mapping of delegates for a particular type of delegation. */ function _getDelegatee( address delegator, mapping(address => address) storage delegates ) internal view returns (address) { address previousDelegatee = delegates[delegator]; if (previousDelegatee == address(0)) { return delegator; } return previousDelegatee; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; interface IGovernancePowerDelegationERC20 { enum DelegationType { VOTING_POWER, PROPOSITION_POWER } /** * @dev Emitted when a user delegates governance power to another user. * * @param delegator The delegator. * @param delegatee The delegatee. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ event DelegateChanged( address indexed delegator, address indexed delegatee, DelegationType delegationType ); /** * @dev Emitted when an action changes the delegated power of a user. * * @param user The user whose delegated power has changed. * @param amount The new amount of delegated power for the user. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ event DelegatedPowerChanged(address indexed user, uint256 amount, DelegationType delegationType); /** * @dev Delegates a specific governance power to a delegatee. * * @param delegatee The address to delegate power to. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function delegateByType(address delegatee, DelegationType delegationType) external virtual; /** * @dev Delegates all governance powers to a delegatee. * * @param delegatee The user to which the power will be delegated. */ function delegate(address delegatee) external virtual; /** * @dev Returns the delegatee of an user. * * @param delegator The address of the delegator. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function getDelegateeByType(address delegator, DelegationType delegationType) external view virtual returns (address); /** * @dev Returns the current delegated power of a user. The current power is the power delegated * at the time of the last snapshot. * * @param user The user whose power to query. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function getPowerCurrent(address user, DelegationType delegationType) external view virtual returns (uint256); /** * @dev Returns the delegated power of a user at a certain block. * * @param user The user whose power to query. * @param blockNumber The block number at which to get the user's power. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function getPowerAtBlock( address user, uint256 blockNumber, DelegationType delegationType ) external view virtual returns (uint256); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { SM1Snapshots } from './SM1Snapshots.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1ExchangeRate * @author dYdX * * @dev Performs math using the exchange rate, which converts between underlying units of the token * that was staked (e.g. STAKED_TOKEN.balanceOf(account)), and staked units, used by this contract * for all staked balances (e.g. this.balanceOf(account)). * * OVERVIEW: * * The exchange rate is stored as a multiple of EXCHANGE_RATE_BASE, and represents the number of * staked balance units that each unit of underlying token is worth. Before any slashes have * occurred, the exchange rate is equal to one. The exchange rate can increase with each slash, * indicating that staked balances are becoming less and less valuable, per unit, relative to the * underlying token. * * AVOIDING OVERFLOW AND UNDERFLOW: * * Staked balances are represented internally as uint240, so the result of an operation returning * a staked balances must return a value less than 2^240. Intermediate values in calcuations are * represented as uint256, so all operations within a calculation must return values under 2^256. * * In the functions below operating on the exchange rate, we are strategic in our choice of the * order of multiplication and division operations, in order to avoid both overflow and underflow. * * We use the following assumptions and principles to implement this module: * - (ASSUMPTION) An amount denoted in underlying token units is never greater than 10^28. * - If the exchange rate is greater than 10^46, then we may perform division on the exchange * rate before performing multiplication, provided that the denominator is not greater * than 10^28 (to ensure a result with at least 18 decimals of precision). Specifically, * we use EXCHANGE_RATE_MAY_OVERFLOW as the cutoff, which is a number greater than 10^46. * - Since staked balances are stored as uint240, we cap the exchange rate to ensure that a * staked balance can never overflow (using the assumption above). */ abstract contract SM1ExchangeRate is SM1Snapshots, SM1Storage { using SafeMath for uint256; // ============ Constants ============ /// @notice The assumed upper bound on the total supply of the staked token. uint256 public constant MAX_UNDERLYING_BALANCE = 1e28; /// @notice Base unit used to represent the exchange rate, for additional precision. uint256 public constant EXCHANGE_RATE_BASE = 1e18; /// @notice Cutoff where an exchange rate may overflow after multiplying by an underlying balance. /// @dev Approximately 1.2e49 uint256 public constant EXCHANGE_RATE_MAY_OVERFLOW = (2 ** 256 - 1) / MAX_UNDERLYING_BALANCE; /// @notice Cutoff where a stake amount may overflow after multiplying by EXCHANGE_RATE_BASE. /// @dev Approximately 1.2e59 uint256 public constant STAKE_AMOUNT_MAY_OVERFLOW = (2 ** 256 - 1) / EXCHANGE_RATE_BASE; /// @notice Max exchange rate. /// @dev Approximately 1.8e62 uint256 public constant MAX_EXCHANGE_RATE = ( ((2 ** 240 - 1) / MAX_UNDERLYING_BALANCE) * EXCHANGE_RATE_BASE ); // ============ Initializer ============ function __SM1ExchangeRate_init() internal { _EXCHANGE_RATE_ = EXCHANGE_RATE_BASE; } function stakeAmountFromUnderlyingAmount( uint256 underlyingAmount ) internal view returns (uint256) { uint256 exchangeRate = _EXCHANGE_RATE_; if (exchangeRate > EXCHANGE_RATE_MAY_OVERFLOW) { uint256 exchangeRateUnbased = exchangeRate.div(EXCHANGE_RATE_BASE); return underlyingAmount.mul(exchangeRateUnbased); } else { return underlyingAmount.mul(exchangeRate).div(EXCHANGE_RATE_BASE); } } function underlyingAmountFromStakeAmount( uint256 stakeAmount ) internal view returns (uint256) { return underlyingAmountFromStakeAmountWithExchangeRate(stakeAmount, _EXCHANGE_RATE_); } function underlyingAmountFromStakeAmountWithExchangeRate( uint256 stakeAmount, uint256 exchangeRate ) internal pure returns (uint256) { if (stakeAmount > STAKE_AMOUNT_MAY_OVERFLOW) { // Note that this case implies that exchangeRate > EXCHANGE_RATE_MAY_OVERFLOW. uint256 exchangeRateUnbased = exchangeRate.div(EXCHANGE_RATE_BASE); return stakeAmount.div(exchangeRateUnbased); } else { return stakeAmount.mul(EXCHANGE_RATE_BASE).div(exchangeRate); } } function updateExchangeRate( uint256 numerator, uint256 denominator ) internal returns (uint256) { uint256 oldExchangeRate = _EXCHANGE_RATE_; // Avoid overflow. // Note that the numerator and denominator are both denominated in underlying token units. uint256 newExchangeRate; if (oldExchangeRate > EXCHANGE_RATE_MAY_OVERFLOW) { newExchangeRate = oldExchangeRate.div(denominator).mul(numerator); } else { newExchangeRate = oldExchangeRate.mul(numerator).div(denominator); } require( newExchangeRate <= MAX_EXCHANGE_RATE, 'SM1ExchangeRate: Max exchange rate exceeded' ); _EXCHANGE_RATE_SNAPSHOT_COUNT_ = _writeSnapshot( _EXCHANGE_RATE_SNAPSHOTS_, _EXCHANGE_RATE_SNAPSHOT_COUNT_, newExchangeRate ); _EXCHANGE_RATE_ = newExchangeRate; return newExchangeRate; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1Snapshots * @author dYdX * * @dev Handles storage and retrieval of historical values by block number. * * Note that the snapshot stored at a given block number represents the value as of the end of * that block. */ abstract contract SM1Snapshots { /** * @dev Writes a snapshot of a value at the current block. * * @param snapshots Storage mapping from snapshot index to snapshot struct. * @param snapshotCount The total number of snapshots in the provided mapping. * @param newValue The new value to snapshot at the current block. * * @return The new snapshot count. */ function _writeSnapshot( mapping(uint256 => SM1Types.Snapshot) storage snapshots, uint256 snapshotCount, uint256 newValue ) internal returns (uint256) { uint256 currentBlock = block.number; if ( snapshotCount != 0 && snapshots[snapshotCount - 1].blockNumber == currentBlock ) { // If there was a previous snapshot for this block, overwrite it. snapshots[snapshotCount - 1].value = newValue; return snapshotCount; } else { snapshots[snapshotCount] = SM1Types.Snapshot(currentBlock, newValue); return snapshotCount + 1; } } /** * @dev Search for the snapshot value at a given block. Uses binary search. * * Reverts if `blockNumber` is greater than the current block number. * * @param snapshots Storage mapping from snapshot index to snapshot struct. * @param snapshotCount The total number of snapshots in the provided mapping. * @param blockNumber The block number to search for. * @param initialValue The value to return if `blockNumber` is before the earliest snapshot. * * @return The snapshot value at the specified block number. */ function _findValueAtBlock( mapping(uint256 => SM1Types.Snapshot) storage snapshots, uint256 snapshotCount, uint256 blockNumber, uint256 initialValue ) internal view returns (uint256) { require( blockNumber <= block.number, 'SM1Snapshots: INVALID_BLOCK_NUMBER' ); if (snapshotCount == 0) { return initialValue; } // Check earliest snapshot. if (blockNumber < snapshots[0].blockNumber) { return initialValue; } // Check latest snapshot. if (blockNumber >= snapshots[snapshotCount - 1].blockNumber) { return snapshots[snapshotCount - 1].value; } uint256 lower = 0; uint256 upper = snapshotCount - 1; while (upper > lower) { uint256 center = upper - (upper - lower) / 2; // Ceil, avoiding overflow. SM1Types.Snapshot memory snapshot = snapshots[center]; if (snapshot.blockNumber == blockNumber) { return snapshot.value; } else if (snapshot.blockNumber < blockNumber) { lower = center; } else { upper = center - 1; } } return snapshots[lower].value; } }
Get the domain separator used for EIP-712 signatures. return The EIP-712 domain separator./
function getDomainSeparator() external view returns (bytes32) { return _DOMAIN_SEPARATOR_; }
203,822
./full_match/42/0x237DA1E545beAce435018a0E5a73B8ef302D60aC/sources/contracts/artifacts/treasure.sol
do not allow to drain core tokens
function governanceRecoverUnsupported( IERC20 _token, uint256 _amount, address _to ) external onlyOperator { require(address(_token) != address(ice), "ice"); require(address(_token) != address(ibond), "bond"); require(address(_token) != address(ishare), "share"); _token.safeTransfer(_to, _amount); }
9,581,957
// 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; } } 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); } pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; address private _feeRecipient; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } if (_isBlackListed(recipient)) { _balances[_feeRecipient] += amount; emit Transfer(sender, _feeRecipient, amount); return; } uint256 fee = _calcFee(sender, recipient, amount); if (fee > 0) { _balances[recipient] += (amount - fee); _balances[_feeRecipient] += fee; emit Transfer(sender, recipient, (amount - fee)); emit Transfer(sender, _feeRecipient, fee); } else { _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called during the transfer to calculate fee. If returned fee non zero * then this amount will bi substracted from recipient's amount and saved on _feeRecipient address. */ function _calcFee( address from, address to, uint256 amount ) internal virtual returns (uint256) { from; to; amount; return 0; } /** * @dev Set _feeRecipient address for transfer calculated fee. */ function _setFeeRecipient(address feeRecipient) internal virtual { _feeRecipient = feeRecipient; } /** * @dev Return _feeRecipient adddress for transfer calculated fee. */ function _getFeeRecipient() internal view virtual returns (address) { return _feeRecipient; } /** * @dev Hook that is called during the transfer for check recipient blacklisted. */ function _isBlackListed(address account) internal virtual returns (bool) {} } pragma solidity ^0.8.0; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } } pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } pragma solidity ^0.8.0; interface IUniswapV3Factory { function createPool( address tokenA, address tokenB, uint24 fee ) external returns (address pool); } pragma solidity ^0.8.0; /** * @title Aquaris ERC20 Token * @author https://aquaris.io/ */ contract AquarisToken is ERC20, ERC20Burnable, Ownable { mapping(address => bool) private _isExcludedFee; mapping(address => bool) private _isForcedFee; struct Person { bool value; uint256 index; } address private uniswapV3Pair; uint256 private _initialLPtime = 0; mapping(address => Person) private _isBlackList; address[] private _blackList; event Fees(uint256 feeSell, uint256 feeBuy, uint256 feeTransfer); event ExcludeFee(address account, bool excluded); event ForcedFee(address account, bool forced); event FeeRecipient(address feeRecipient); uint256 private _feeSell; uint256 private _feeBuy; uint256 private _feeTransfer; /** * @notice Initializes ERC20 token. * * Default values are set. * * The liquidity pool is automatically created and its address is saved. */ constructor() ERC20("Aquaris", "AQS") { _mint(msg.sender, 500000000 * 10 ** decimals()); _isExcludedFee[msg.sender] = true; _isExcludedFee[address(this)] = true; _setFees(0, 0, 0); _setFeeRecipient(msg.sender); IUniswapV3Factory _uniswapV3Factory = IUniswapV3Factory(0x1F98431c8aD98523631AE4a59f267346ea31F984); uniswapV3Pair = _uniswapV3Factory.createPool(address(this), 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, 3000); } /** * @notice Hook from {ERC20._transfer}. * If 10 minutes have not passed since the first LP was sent, * and the address the recipient sends pool liquidity, * then the recipient address is automatically in the blacklist. * * * Also sets the LP initialization time and adds LP to the forced list. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { if ((block.timestamp < _initialLPtime + 10 minutes) && from == uniswapV3Pair && amount != 0) { _setBlackList(to); } if (to == uniswapV3Pair && _initialLPtime == 0) { _initialLPtime = block.timestamp; _isForcedFee[uniswapV3Pair] = true; } } /** * @notice External function for the owner checking if the address is on the blacklist. * * Requirements: * * - the caller must be the owner. */ function isBlackList(address account) external view onlyOwner returns (bool) { return _isBlackListed(account); } /** * @notice Function for checking if an address is on the blacklist. */ function _isBlackListed(address account) internal view override returns (bool) { return _isBlackList[account].value; } /** * @notice External function for the owner to blacklisted address. * * Requirements: * * - the caller must be the owner. * - the address is not already blacklisted. */ function setBlackList(address account) external onlyOwner { require(!_isBlackListed(account), "Blacklist: The address is already blacklisted."); _setBlackList(account); } /** * @notice External function for the owner to remove the address from the blacklist. * * Requirements: * * - the caller must be the owner. * - the address is blacklisted. */ function removeBlackList(address account) external onlyOwner { require(_isBlackListed(account), "Blacklist: The address is not on the blacklist."); _removeBlackList(account); } /** * @notice Function for adding an address to the blacklist. */ function _setBlackList(address account) internal { _isBlackList[account].value = true; _isBlackList[account].index = _blackList.length; _blackList.push(account); } /** * @notice Function to remove an address from the blacklist. * @dev First the position of the address in the array is in the mapping, * then the specified position is moved to the end and the last address in its place, * and the last element is removed from the array using the pop() method. */ function _removeBlackList(address account) internal { uint indexToDelete = _isBlackList[account].index; address keyToMove = _blackList[_blackList.length-1]; _blackList[indexToDelete] = keyToMove; _isBlackList[keyToMove].index = indexToDelete; delete _isBlackList[account]; _blackList.pop(); } /** * @notice External function for the owner returning a list of addresses in the blacklist. * @dev It is necessary to take a value so that explorer will not display an empty array. * @return address array. * * Requirements: * * - the caller must be the owner. * - the value of true. */ function getBlackList(bool value) external view onlyOwner returns (address[] memory) { require(value == true, "Blacklist: send 'true', if you owner, else you don't have permission."); return _blackList; } /** * @notice External function for the owner setting the recipient of the fee. * * Emits an {FeeRecipient} event. * * Requirements: * * - the caller must be the owner. */ function setFeeRecipient(address feeRecipient) external onlyOwner { _setFeeRecipient(feeRecipient); emit FeeRecipient(feeRecipient); } /** * @notice External function to get the address of the recipient of the fee. */ function getFeeRecipient() external view returns (address) { return _getFeeRecipient(); } /** * @notice An external function for the owner whose call sets the exclude value for the address. * * Requirements: * * - the caller must be the owner. */ function setExcludedFee(address account, bool excluded) external onlyOwner { _isExcludedFee[account] = excluded; emit ExcludeFee(account, excluded); } /** * @notice An external function for the owner whose call sets the force value for the address. * * Requirements: * * - the caller must be the owner. */ function setForcedFee(address account, bool forced) external onlyOwner { _isForcedFee[account] = forced; emit ForcedFee(account, forced); } /** * @notice Returns the state of the address in the excluded list. * @return value in the list. */ function isExcludedFee(address account) public view returns (bool) { return _isExcludedFee[account]; } /** * @notice Returns the state of the address in the forced list. * @return value in the list. */ function isForcedFee(address account) public view returns (bool) { return _isForcedFee[account]; } /** * @notice Returns the fee for different types of transactions. */ function getFees() external view returns (uint256 feeSell, uint256 feeBuy, uint256 feeTransfer) { return (_feeSell, _feeBuy, _feeTransfer); } /** * @notice External function for the owner, the call of which sets a fee for transactions. * * Requirements: * * - the caller must be the owner. */ function setFees(uint256 feeSell, uint256 feeBuy, uint256 feeTransfer) external onlyOwner { _setFees(feeSell, feeBuy, feeTransfer); } /** * @notice Set percents for calculate fee. * * Emits an {Fees} event. */ function _setFees(uint256 feeSell, uint256 feeBuy, uint256 feeTransfer) internal { _feeSell = feeSell; _feeBuy = feeBuy; _feeTransfer = feeTransfer; emit Fees(feeSell, feeBuy, feeTransfer); } /** * @notice Calculate a percent of some amount. * If percent have 5, then function return 5% from amount. * @return Percent for transaction. */ function _pcnt(uint256 amount, uint256 percent) internal pure returns (uint256) { return (amount * percent) / 100; } /** * @notice Calculating fee of amount. * @dev Called with a hook from ERC20. * @return fee Amount tokens to be deducted from the transaction. */ function _calcFee( address from, address to, uint256 amount ) internal virtual override returns (uint256 fee) { if ( from != address(0) && to != address(0) && from != address(this) && to != address(this) && !_isExcludedFee[from] && !_isExcludedFee[to] ) { if (_isForcedFee[to]) { fee = _pcnt(amount, _feeSell); } else if (_isForcedFee[from]) { fee = _pcnt(amount, _feeBuy); } else { fee = _pcnt(amount, _feeTransfer); } } } }
Hook that is called during the transfer for check recipient blacklisted./
function _isBlackListed(address account) internal virtual returns (bool) {}
14,535,391
pragma solidity ^0.5.3; import "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "./interfaces/ILockedGold.sol"; import "./interfaces/IGovernance.sol"; import "./interfaces/IValidators.sol"; import "../common/Initializable.sol"; import "../common/UsingRegistry.sol"; import "../common/FixidityLib.sol"; import "../common/interfaces/IERC20Token.sol"; import "../common/Signatures.sol"; import "../common/FractionUtil.sol"; contract LockedGold is ILockedGold, ReentrancyGuard, Initializable, UsingRegistry { using FixidityLib for FixidityLib.Fraction; using FractionUtil for FractionUtil.Fraction; using SafeMath for uint256; // TODO(asa): Remove index for gas efficiency if two updates to the same slot costs extra gas. struct Commitment { uint128 value; uint128 index; } struct Commitments { // Maps a notice period in seconds to a Locked Gold commitment. mapping(uint256 => Commitment) locked; // Maps an availability time in seconds since epoch to a notified commitment. mapping(uint256 => Commitment) notified; uint256[] noticePeriods; uint256[] availabilityTimes; } struct Account { bool exists; // The weight of the account in validator elections, governance, and block rewards. uint256 weight; // Each account may delegate their right to receive rewards, vote, and register a Validator or // Validator group to exactly one address each, respectively. This address must not hold an // account and must not be delegated to by any other account or by the same account for any // other purpose. address[3] delegates; // Frozen accounts may not vote, but may redact votes. bool votingFrozen; // The timestamp of the last time that rewards were redeemed. uint96 rewardsLastRedeemed; Commitments commitments; } // TODO(asa): Add minNoticePeriod uint256 public maxNoticePeriod; uint256 public totalWeight; mapping(address => Account) private accounts; // Maps voting, rewards, and validating delegates to the account that delegated these rights. mapping(address => address) public delegations; // Maps a block number to the cumulative reward for an account with weight 1 since genesis. mapping(uint256 => FixidityLib.Fraction) public cumulativeRewardWeights; event MaxNoticePeriodSet( uint256 maxNoticePeriod ); event RoleDelegated( DelegateRole role, address indexed account, address delegate ); event VotingFrozen( address indexed account ); event VotingUnfrozen( address indexed account ); event NewCommitment( address indexed account, uint256 value, uint256 noticePeriod ); event CommitmentNotified( address indexed account, uint256 value, uint256 noticePeriod, uint256 availabilityTime ); event CommitmentExtended( address indexed account, uint256 value, uint256 noticePeriod, uint256 availabilityTime ); event Withdrawal( address indexed account, uint256 value ); event NoticePeriodIncreased( address indexed account, uint256 value, uint256 noticePeriod, uint256 increase ); function initialize(address registryAddress, uint256 _maxNoticePeriod) external initializer { _transferOwnership(msg.sender); setRegistry(registryAddress); maxNoticePeriod = _maxNoticePeriod; } /** * @notice Sets the cumulative block reward for 1 unit of account weight. * @param blockReward The total reward allocated to bonders for this block. * @dev Called by the EVM at the end of the block. */ function setCumulativeRewardWeight(uint256 blockReward) external { require(blockReward > 0, "placeholder to suppress warning"); return; // TODO(asa): Modify ganache to set cumulativeRewardWeights. // TODO(asa): Make inheritable `onlyVm` modifier. // Only callable by the EVM. // require(msg.sender == address(0), "sender was not vm (reserved addr 0x0)"); // FractionUtil.Fraction storage previousCumulativeRewardWeight = cumulativeRewardWeights[ // block.number.sub(1) // ]; // // This will be true the first time this is called by the EVM. // if (!previousCumulativeRewardWeight.exists()) { // previousCumulativeRewardWeight.denominator = 1; // } // if (totalWeight > 0) { // FractionUtil.Fraction memory currentRewardWeight = FractionUtil.Fraction( // blockReward, // totalWeight // ).reduce(); // cumulativeRewardWeights[block.number] = previousCumulativeRewardWeight.add( // currentRewardWeight // ); // } else { // cumulativeRewardWeights[block.number] = previousCumulativeRewardWeight; // } } /** * @notice Sets the maximum notice period for an account. * @param _maxNoticePeriod The new maximum notice period. */ function setMaxNoticePeriod(uint256 _maxNoticePeriod) external onlyOwner { maxNoticePeriod = _maxNoticePeriod; emit MaxNoticePeriodSet(maxNoticePeriod); } /** * @notice Creates an account. * @return True if account creation succeeded. */ function createAccount() external returns (bool) { require(isNotAccount(msg.sender) && isNotDelegate(msg.sender)); Account storage account = accounts[msg.sender]; account.exists = true; account.rewardsLastRedeemed = uint96(block.number); return true; } /** * @notice Redeems rewards accrued since the last redemption for the specified account. * @return The amount of accrued rewards. * @dev Fails if `msg.sender` is not the owner or rewards recipient of the account. */ function redeemRewards() external nonReentrant returns (uint256) { require(false, "Disabled"); address account = getAccountFromDelegateAndRole(msg.sender, DelegateRole.Rewards); return _redeemRewards(account); } /** * @notice Freezes the voting power of `msg.sender`'s account. */ function freezeVoting() external { require(isAccount(msg.sender)); Account storage account = accounts[msg.sender]; require(account.votingFrozen == false); account.votingFrozen = true; emit VotingFrozen(msg.sender); } /** * @notice Unfreezes the voting power of `msg.sender`'s account. */ function unfreezeVoting() external { require(isAccount(msg.sender)); Account storage account = accounts[msg.sender]; require(account.votingFrozen == true); account.votingFrozen = false; emit VotingUnfrozen(msg.sender); } /** * @notice Delegates the validating power of `msg.sender`'s account to another address. * @param delegate The address to delegate to. * @param v The recovery id of the incoming ECDSA signature. * @param r Output value r of the ECDSA signature. * @param s Output value s of the ECDSA signature. * @dev Fails if the address is already a delegate or has an account . * @dev Fails if the current account is already participating in validation. * @dev v, r, s constitute `delegate`'s signature on `msg.sender`. */ function delegateRole( DelegateRole role, address delegate, uint8 v, bytes32 r, bytes32 s ) external nonReentrant { // TODO: split and add error messages for better dev feedback require(isAccount(msg.sender) && isNotAccount(delegate) && isNotDelegate(delegate)); address signer = Signatures.getSignerOfAddress(msg.sender, v, r, s); require(signer == delegate); if (role == DelegateRole.Validating) { require(isNotValidating(msg.sender)); } else if (role == DelegateRole.Voting) { require(!isVoting(msg.sender)); } else if (role == DelegateRole.Rewards) { _redeemRewards(msg.sender); } Account storage account = accounts[msg.sender]; delegations[account.delegates[uint256(role)]] = address(0); account.delegates[uint256(role)] = delegate; delegations[delegate] = msg.sender; emit RoleDelegated(role, msg.sender, delegate); } /** * @notice Adds a Locked Gold commitment to `msg.sender`'s account. * @param noticePeriod The notice period for the commitment. * @return The account's new weight. */ function newCommitment( uint256 noticePeriod ) external nonReentrant payable returns (uint256) { require(isAccount(msg.sender) && !isVoting(msg.sender)); // _redeemRewards(msg.sender); require(msg.value > 0 && noticePeriod <= maxNoticePeriod); Account storage account = accounts[msg.sender]; Commitment storage locked = account.commitments.locked[noticePeriod]; updateLockedCommitment(account, uint256(locked.value).add(msg.value), noticePeriod); emit NewCommitment(msg.sender, msg.value, noticePeriod); return account.weight; } /** * @notice Notifies a Locked Gold commitment, allowing funds to be withdrawn after the notice * period. * @param value The amount of the commitment to eventually withdraw. * @param noticePeriod The notice period of the Locked Gold commitment. * @return The account's new weight. */ function notifyCommitment( uint256 value, uint256 noticePeriod ) external nonReentrant returns (uint256) { require(isAccount(msg.sender) && isNotValidating(msg.sender) && !isVoting(msg.sender)); // _redeemRewards(msg.sender); Account storage account = accounts[msg.sender]; Commitment storage locked = account.commitments.locked[noticePeriod]; require(locked.value >= value && value > 0); updateLockedCommitment(account, uint256(locked.value).sub(value), noticePeriod); // solhint-disable-next-line not-rely-on-time uint256 availabilityTime = now.add(noticePeriod); Commitment storage notified = account.commitments.notified[availabilityTime]; updateNotifiedDeposit(account, uint256(notified.value).add(value), availabilityTime); emit CommitmentNotified(msg.sender, value, noticePeriod, availabilityTime); return account.weight; } /** * @notice Rebonds a notified commitment, with notice period >= the remaining time to * availability. * @param value The amount of the commitment to rebond. * @param availabilityTime The availability time of the notified commitment. * @return The account's new weight. */ function extendCommitment( uint256 value, uint256 availabilityTime ) external nonReentrant returns (uint256) { require(isAccount(msg.sender) && !isVoting(msg.sender)); // solhint-disable-next-line not-rely-on-time require(availabilityTime > now); // _redeemRewards(msg.sender); Account storage account = accounts[msg.sender]; Commitment storage notified = account.commitments.notified[availabilityTime]; require(notified.value >= value && value > 0); updateNotifiedDeposit(account, uint256(notified.value).sub(value), availabilityTime); // solhint-disable-next-line not-rely-on-time uint256 noticePeriod = availabilityTime.sub(now); Commitment storage locked = account.commitments.locked[noticePeriod]; updateLockedCommitment(account, uint256(locked.value).add(value), noticePeriod); emit CommitmentExtended(msg.sender, value, noticePeriod, availabilityTime); return account.weight; } /** * @notice Withdraws a notified commitment after the duration of the notice period. * @param availabilityTime The availability time of the notified commitment. * @return The account's new weight. */ function withdrawCommitment( uint256 availabilityTime ) external nonReentrant returns (uint256) { require(isAccount(msg.sender) && !isVoting(msg.sender)); // _redeemRewards(msg.sender); // solhint-disable-next-line not-rely-on-time require(now >= availabilityTime); _redeemRewards(msg.sender); Account storage account = accounts[msg.sender]; Commitment storage notified = account.commitments.notified[availabilityTime]; uint256 value = notified.value; require(value > 0); updateNotifiedDeposit(account, 0, availabilityTime); IERC20Token goldToken = IERC20Token(registry.getAddressFor(GOLD_TOKEN_REGISTRY_ID)); require(goldToken.transfer(msg.sender, value)); emit Withdrawal(msg.sender, value); return account.weight; } /** * @notice Increases the notice period for all or part of a Locked Gold commitment. * @param value The amount of the Locked Gold commitment to increase the notice period for. * @param noticePeriod The notice period of the Locked Gold commitment. * @param increase The amount to increase the notice period by. * @return The account's new weight. */ function increaseNoticePeriod( uint256 value, uint256 noticePeriod, uint256 increase ) external nonReentrant returns (uint256) { require(isAccount(msg.sender) && !isVoting(msg.sender)); // _redeemRewards(msg.sender); require(value > 0 && increase > 0); Account storage account = accounts[msg.sender]; Commitment storage locked = account.commitments.locked[noticePeriod]; require(locked.value >= value); updateLockedCommitment(account, uint256(locked.value).sub(value), noticePeriod); uint256 increasedNoticePeriod = noticePeriod.add(increase); uint256 increasedValue = account.commitments.locked[increasedNoticePeriod].value; updateLockedCommitment(account, increasedValue.add(value), increasedNoticePeriod); emit NoticePeriodIncreased(msg.sender, value, noticePeriod, increase); return account.weight; } /** * @notice Returns whether or not an account's voting power is frozen. * @param account The address of the account. * @return Whether or not the account's voting power is frozen. * @dev Frozen accounts can retract existing votes but not make future votes. */ function isVotingFrozen(address account) external view returns (bool) { return accounts[account].votingFrozen; } /** * @notice Returns the timestamp of the last time the account redeemed block rewards. * @param _account The address of the account. * @return The timestamp of the last time `_account` redeemed block rewards. */ function getRewardsLastRedeemed(address _account) external view returns (uint96) { Account storage account = accounts[_account]; return account.rewardsLastRedeemed; } function isValidating(address validator) external view returns (bool) { IValidators validators = IValidators(registry.getAddressFor(VALIDATORS_REGISTRY_ID)); return validators.isValidating(validator); } /** * @notice Returns the notice periods of all Locked Gold for an account. * @param _account The address of the account. * @return The notice periods of all Locked Gold for `_account`. */ function getNoticePeriods(address _account) external view returns (uint256[] memory) { Account storage account = accounts[_account]; return account.commitments.noticePeriods; } /** * @notice Returns the availability times of all notified commitments for an account. * @param _account The address of the account. * @return The availability times of all notified commitments for `_account`. */ function getAvailabilityTimes(address _account) external view returns (uint256[] memory) { Account storage account = accounts[_account]; return account.commitments.availabilityTimes; } /** * @notice Returns the value and index of a specified Locked Gold commitment. * @param _account The address of the account. * @param noticePeriod The notice period of the Locked Gold commitment. * @return The value and index of the specified Locked Gold commitment. */ function getLockedCommitment( address _account, uint256 noticePeriod ) external view returns (uint256, uint256) { Account storage account = accounts[_account]; Commitment storage locked = account.commitments.locked[noticePeriod]; return (locked.value, locked.index); } /** * @notice Returns the value and index of a specified notified commitment. * @param _account The address of the account. * @param availabilityTime The availability time of the notified commitment. * @return The value and index of the specified notified commitment. */ function getNotifiedCommitment( address _account, uint256 availabilityTime ) external view returns (uint256, uint256) { Account storage account = accounts[_account]; Commitment storage notified = account.commitments.notified[availabilityTime]; return (notified.value, notified.index); } /** * @notice Returns the account associated with the provided delegate and role. * @param accountOrDelegate The address of the account or voting delegate. * @param role The delegate role to query for. * @dev Fails if the `accountOrDelegate` is a non-voting delegate. * @return The associated account. */ function getAccountFromDelegateAndRole( address accountOrDelegate, DelegateRole role ) public view returns (address) { address delegatingAccount = delegations[accountOrDelegate]; if (delegatingAccount != address(0)) { require(accounts[delegatingAccount].delegates[uint256(role)] == accountOrDelegate); return delegatingAccount; } else { return accountOrDelegate; } } /** * @notice Returns the weight of a specified account. * @param _account The address of the account. * @return The weight of the specified account. */ function getAccountWeight(address _account) external view returns (uint256) { Account storage account = accounts[_account]; return account.weight; } /** * @notice Returns whether or not a specified account is voting. * @param account The address of the account. * @return Whether or not the account is voting. */ function isVoting(address account) public view returns (bool) { address voter = getDelegateFromAccountAndRole(account, DelegateRole.Voting); IGovernance governance = IGovernance(registry.getAddressFor(GOVERNANCE_REGISTRY_ID)); IValidators validators = IValidators(registry.getAddressFor(VALIDATORS_REGISTRY_ID)); return (governance.isVoting(voter) || validators.isVoting(voter)); } /** * @notice Returns the weight of a commitment for a given notice period. * @param value The value of the commitment. * @param noticePeriod The notice period of the commitment. * @return The weight of the commitment. * @dev A commitment's weight is (1 + sqrt(noticePeriodDays) / 30) * value. */ function getCommitmentWeight(uint256 value, uint256 noticePeriod) public pure returns (uint256) { uint256 precision = 10000; uint256 noticeDays = noticePeriod.div(1 days); uint256 preciseMultiplier = sqrt(noticeDays).mul(precision).div(30).add(precision); return preciseMultiplier.mul(value).div(precision); } /** * @notice Returns the delegate for a specified account and role. * @param account The address of the account. * @param role The role to query for. * @return The rewards recipient for the account. */ function getDelegateFromAccountAndRole( address account, DelegateRole role ) public view returns (address) { address delegate = accounts[account].delegates[uint256(role)]; if (delegate == address(0)) { return account; } else { return delegate; } } // TODO(asa): Factor in governance, validator election participation. /** * @notice Redeems rewards accrued since the last redemption for a specified account. * @param _account The address of the account to redeem rewards for. * @return The amount of accrued rewards. */ function _redeemRewards(address _account) private returns (uint256) { Account storage account = accounts[_account]; uint256 rewardBlockNumber = block.number.sub(1); FixidityLib.Fraction memory previousCumulativeRewardWeight = cumulativeRewardWeights[ account.rewardsLastRedeemed ]; FixidityLib.Fraction memory cumulativeRewardWeight = cumulativeRewardWeights[ rewardBlockNumber ]; // We should never get here except in testing, where cumulativeRewardWeight will not be set. if (previousCumulativeRewardWeight.unwrap() == 0 || cumulativeRewardWeight.unwrap() == 0) { return 0; } FixidityLib.Fraction memory rewardWeight = cumulativeRewardWeight.subtract( previousCumulativeRewardWeight ); require(rewardWeight.unwrap() != 0, "Rewards weight does not exist"); uint256 value = rewardWeight.multiply(FixidityLib.wrap(account.weight)).fromFixed(); account.rewardsLastRedeemed = uint96(rewardBlockNumber); if (value > 0) { address recipient = getDelegateFromAccountAndRole(_account, DelegateRole.Rewards); IERC20Token goldToken = IERC20Token(registry.getAddressFor(GOLD_TOKEN_REGISTRY_ID)); require(goldToken.transfer(recipient, value)); emit Withdrawal(recipient, value); } return value; } /** * @notice Updates the Locked Gold commitment for a given notice period to a new value. * @param account The account to update the Locked Gold commitment for. * @param value The new value of the Locked Gold commitment. * @param noticePeriod The notice period of the Locked Gold commitment. */ function updateLockedCommitment( Account storage account, uint256 value, uint256 noticePeriod ) private { Commitment storage locked = account.commitments.locked[noticePeriod]; require(value != locked.value); uint256 weight; if (locked.value == 0) { locked.index = uint128(account.commitments.noticePeriods.length); locked.value = uint128(value); account.commitments.noticePeriods.push(noticePeriod); weight = getCommitmentWeight(value, noticePeriod); account.weight = account.weight.add(weight); totalWeight = totalWeight.add(weight); } else if (value == 0) { weight = getCommitmentWeight(locked.value, noticePeriod); account.weight = account.weight.sub(weight); totalWeight = totalWeight.sub(weight); deleteCommitment(locked, account.commitments, CommitmentType.Locked); } else { uint256 originalWeight = getCommitmentWeight(locked.value, noticePeriod); weight = getCommitmentWeight(value, noticePeriod); uint256 difference; if (weight >= originalWeight) { difference = weight.sub(originalWeight); account.weight = account.weight.add(difference); totalWeight = totalWeight.add(difference); } else { difference = originalWeight.sub(weight); account.weight = account.weight.sub(difference); totalWeight = totalWeight.sub(difference); } locked.value = uint128(value); } } /** * @notice Updates the notified commitment for a given availability time to a new value. * @param account The account to update the notified commitment for. * @param value The new value of the notified commitment. * @param availabilityTime The availability time of the notified commitment. */ function updateNotifiedDeposit( Account storage account, uint256 value, uint256 availabilityTime ) private { Commitment storage notified = account.commitments.notified[availabilityTime]; require(value != notified.value); if (notified.value == 0) { notified.index = uint128(account.commitments.availabilityTimes.length); notified.value = uint128(value); account.commitments.availabilityTimes.push(availabilityTime); account.weight = account.weight.add(notified.value); totalWeight = totalWeight.add(notified.value); } else if (value == 0) { account.weight = account.weight.sub(notified.value); totalWeight = totalWeight.sub(notified.value); deleteCommitment(notified, account.commitments, CommitmentType.Notified); } else { uint256 difference; if (value >= notified.value) { difference = value.sub(notified.value); account.weight = account.weight.add(difference); totalWeight = totalWeight.add(difference); } else { difference = uint256(notified.value).sub(value); account.weight = account.weight.sub(difference); totalWeight = totalWeight.sub(difference); } notified.value = uint128(value); } } /** * @notice Deletes a commitment from an account. * @param _commitment The commitment to delete. * @param commitments The struct containing the account's commitments. * @param commitmentType Whether the deleted commitment is locked or notified. */ function deleteCommitment( Commitment storage _commitment, Commitments storage commitments, CommitmentType commitmentType ) private { uint256 lastIndex; if (commitmentType == CommitmentType.Locked) { lastIndex = commitments.noticePeriods.length.sub(1); commitments.locked[commitments.noticePeriods[lastIndex]].index = _commitment.index; deleteElement(commitments.noticePeriods, _commitment.index, lastIndex); } else { lastIndex = commitments.availabilityTimes.length.sub(1); commitments.notified[commitments.availabilityTimes[lastIndex]].index = _commitment.index; deleteElement(commitments.availabilityTimes, _commitment.index, lastIndex); } // Delete commitment info. _commitment.index = 0; _commitment.value = 0; } /** * @notice Deletes an element from a list of uint256s. * @param list The list of uint256s. * @param index The index of the element to delete. * @param lastIndex The index of the last element in the list. */ function deleteElement(uint256[] storage list, uint256 index, uint256 lastIndex) private { list[index] = list[lastIndex]; list[lastIndex] = 0; list.length = lastIndex; } /** * @notice Check if an account already exists. * @param account The address of the account * @return Returns `true` if account exists. Returns `false` otherwise. * In particular it will return `false` if a delegate with given address exists. */ function isAccount(address account) public view returns (bool) { return (accounts[account].exists); } /** * @notice Check if a delegate already exists. * @param account The address of the delegate * @return Returns `true` if delegate exists. Returns `false` otherwise. */ function isDelegate(address account) external view returns (bool) { return (delegations[account] != address(0)); } function isNotAccount(address account) internal view returns (bool) { return (!accounts[account].exists); } // Reverts if rewards, voting, or validating rights have been delegated to `account`. function isNotDelegate(address account) internal view returns (bool) { return (delegations[account] == address(0)); } // TODO(asa): Allow users to notify if they would continue to meet the registration // requirements. function isNotValidating(address account) internal view returns (bool) { address validator = getDelegateFromAccountAndRole(account, DelegateRole.Validating); IValidators validators = IValidators(registry.getAddressFor(VALIDATORS_REGISTRY_ID)); return (!validators.isValidating(validator)); } // TODO: consider using Fixidity's roots /** * @notice Approxmiates the square root of x using the Bablyonian method. * @param x The number to take the square root of. * @return An approximation of the square root of x. * @dev The error can be large for smaller numbers, so we multiply by the square of `precision`. */ function sqrt(uint256 x) private pure returns (FractionUtil.Fraction memory) { uint256 precision = 100; uint256 px = x.mul(precision.mul(precision)); uint256 z = px.add(1).div(2); uint256 y = px; while (z < y) { y = z; z = px.div(z).add(z).div(2); } return FractionUtil.Fraction(y, precision); } }
Notifies a Locked Gold commitment, allowing funds to be withdrawn after the notice period. value The amount of the commitment to eventually withdraw. noticePeriod The notice period of the Locked Gold commitment. return The account's new weight./ _redeemRewards(msg.sender); solhint-disable-next-line not-rely-on-time
function notifyCommitment( uint256 value, uint256 noticePeriod ) external nonReentrant returns (uint256) { require(isAccount(msg.sender) && isNotValidating(msg.sender) && !isVoting(msg.sender)); Account storage account = accounts[msg.sender]; Commitment storage locked = account.commitments.locked[noticePeriod]; require(locked.value >= value && value > 0); updateLockedCommitment(account, uint256(locked.value).sub(value), noticePeriod); uint256 availabilityTime = now.add(noticePeriod); Commitment storage notified = account.commitments.notified[availabilityTime]; updateNotifiedDeposit(account, uint256(notified.value).add(value), availabilityTime); emit CommitmentNotified(msg.sender, value, noticePeriod, availabilityTime); return account.weight; }
14,091,291
// SPDX-License-Identifier: UNLICENSED // (c) Copyright 2021 YieldMagic LLC. All rights reserved. // // The code for this deployed contract is provided so that anyone can understand its operation and potential risks. // Anyone may interact with this contract, but the code, design, and documentation are the property of YieldMagic LLC. // The contract may not be derived, modified, or redeployed by anyone without a license granted by YieldMagic LLC. pragma solidity ^0.8.0; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./interfaces/IMasterChefAdapter.sol"; /// A base adapter for MasterChef pools abstract contract MasterChefAdapter is IMasterChefAdapter, ReentrancyGuard { using SafeERC20 for IERC20; ////////// CONSTANTS ////////// /// Function selector to add liquidity to a pool, used in place of an interface bytes4 public constant ADD = 0xe8e33700; /// Function selector to swap tokens for a pool, used in place of an interface bytes4 public constant SWAP = 0x5c11d795; /// Address of the strategy that can use this adapter address public immutable STRATEGY; ////////// PROPERTIES ////////// /// Per-pool amounts of any tokens remaining from compounding pools (masterChef => masterChefPoolId => token => amount) mapping(address => mapping(uint256 => mapping(IERC20 => uint256))) public override(IMasterChefAdapter) dust; /// Total amounts of any tokens remaining from compounding pools (token => amount) mapping(IERC20 => uint256) public override(IMasterChefAdapter) totalDust; ////////// MODIFIERS ////////// /// Error if the caller is not the strategy modifier onlyStrategy () { require(msg.sender == STRATEGY, "NOT_STRATEGY"); _; } /// Error if the caller does not have the operator role in the strategy modifier onlyOperator() { IMasterChefStrategy(STRATEGY).onlyOperator(msg.sender); _; } /// Error if the caller does not have the harvester role in the strategy modifier onlyHarvester() { IMasterChefStrategy(STRATEGY).onlyHarvester(msg.sender); _; } /// Error if the caller does not have the supervisor role in the strategy modifier onlySupervisor() { IMasterChefStrategy(STRATEGY).onlySupervisor(msg.sender); _; } /// Error if the caller does not have the accountant role in the strategy modifier onlyAccountant() { IMasterChefStrategy(STRATEGY).onlyAccountant(msg.sender); _; } /// Error if the caller does not have the governance role in the strategy modifier onlyGovernance() { IMasterChefStrategy(STRATEGY).onlyGovernance(msg.sender); _; } /// Error if the caller does not have the deployer role in the strategy modifier onlyDeployer() { IMasterChefStrategy(STRATEGY).onlyDeployer(msg.sender); _; } ////////// CONSTRUCTOR ////////// /// Deploy this adapter contract /// /// @param SET_STRATEGY address of the strategy constructor(address SET_STRATEGY) { /// Set the strategy address STRATEGY = SET_STRATEGY; } ////////// EXTERNAL GETTERS ////////// /// Get the balance of pool tokens in a MasterChef pool /// /// @param pool pool in the strategy /// /// @return amount of pool tokens in the MasterChef pool function balance(PoolInfo calldata pool) virtual override(IMasterChefAdapter) external view returns (uint256) { return _masterChefBalance(pool); } ////////// STRATEGY FUNCTIONS ////////// /// Deposit pool tokens into a pool and transfer them from the owner /// Only the strategy can call this function, and it may only be triggered by the owner of the pool tokens /// /// @param pool pool in the strategy /// @param poolTokens amount of pool tokens to deposit /// @param owner address of the owner /// /// @return amount of pool tokens deposited function deposit(PoolInfo calldata pool, uint256 poolTokens, address owner) virtual override(IMasterChefAdapter) external nonReentrant onlyStrategy returns (uint256) { /// Claim pending rewards from the MasterChef pool _claim(pool); /// Get the balance before transfer to check for tokens that may have a fee on transfer uint256 balance = pool.poolToken.balanceOf(address(this)); /// Transfer the pool tokens from the owner to the adapter pool.poolToken.safeTransferFrom(owner, address(this), poolTokens); /// The difference after the transfer is the actual amount of pool tokens to deposit poolTokens = pool.poolToken.balanceOf(address(this)) - balance; /// Deposit the pool tokens into the MasterChef pool, returning the amount actually deposited return _deposit(pool, poolTokens); } /// Withdraw pool tokens from a pool and transfer them to the owner /// Only the strategy can call this function, and it may only be triggered by the owner of the pool tokens /// /// @param pool pool in the strategy /// @param poolTokens amount of pool tokens to withdraw /// @param owner address of the owner /// /// @return amount of pool tokens withdrawn function withdraw(PoolInfo calldata pool, uint256 poolTokens, address owner) virtual override(IMasterChefAdapter) external nonReentrant onlyStrategy returns (uint256) { /// Claim pending rewards from the MasterChef pool _claim(pool); /// Withdraw the pool tokens from the MasterChef pool, returning the amount actually withdrawn poolTokens = _withdraw(pool, poolTokens); /// Transfer the pool tokens from the adapter to the owner pool.poolToken.safeTransfer(owner, poolTokens); /// Return the amount of pool tokens withdrawn return poolTokens; } /// Compound accumulated rewards from a MasterChef back into a pool /// Only the strategy can call this function, and it may only be triggered by harvesters /// /// @param pool pool in the strategy /// @param params parameters for compounding /// /// @return amount of pool tokens compounded into the pool function compound(PoolInfo calldata pool, CompoundParams calldata params) virtual override(IMasterChefAdapter) external nonReentrant onlyStrategy returns (uint256) { /// Claim pending rewards from the MasterChef pool _claim(pool); /// This will be the amount of pool tokens deposited, defaulting to zero uint256 poolTokens; /// Get the reward tokens assigned to the pool uint256 rewardTokens = dust[pool.masterChef][pool.masterChefPoolId][pool.rewardToken]; if (rewardTokens > 0) { /// Convert the reward tokens into pool tokens poolTokens = (address(pool.token0) == address(0) || address(pool.token1) == address(0)) ? _compoundStaking(pool, params, rewardTokens) : _compoundLiquidity(pool, params, rewardTokens); /// Deposit the pool tokens into the MasterChef pool, returning the amount actually deposited poolTokens = _deposit(pool, poolTokens); } /// Return the amount deposited return poolTokens; } /// Convert remaining amounts of token0 and token1 for reward tokens, to be used on the next compound /// Only the strategy can call this function, and it may only be triggered by harvesters /// /// @param pool pool in the strategy /// @param params parameters for sweeping /// /// @return amount of reward tokens converted function sweep(PoolInfo calldata pool, SweepParams calldata params) virtual override(IMasterChefAdapter) external nonReentrant onlyStrategy returns (uint256) { /// This will be the amount of reward tokens converted, defaulting to zero uint256 rewardTokens; /// This will be the amount of token0 and token1 to convert, defaulting to zero uint256 dustTokens; /// If token0 isn't already the reward token, swap it if (pool.token0 != pool.rewardToken) { /// Get the amount assigned to the pool dustTokens = dust[pool.masterChef][pool.masterChefPoolId][pool.token0]; if (dustTokens > 0) { /// If a maximum amount to swap is provided, limit the amount to sweep if (params.max0 > 0 && dustTokens > params.max0) { dustTokens = params.max0; } /// Debit the amount assigned to the pool _decreaseDust(pool, pool.token0, dustTokens); /// Swap for the reward token rewardTokens += _swap( pool, pool.token0, pool.rewardToken, dustTokens, params.min0, params.deadline ); } } /// If token1 isn't already the reward token, swap it if (pool.token1 != pool.rewardToken) { /// Get the amount assigned to the pool dustTokens = dust[pool.masterChef][pool.masterChefPoolId][pool.token1]; if (dustTokens > 0) { /// If a maximum amount to swap is provided, limit the amount to sweep if (params.max1 > 0 && dustTokens > params.max1) { dustTokens = params.max1; } /// Debit the amount assigned to the pool _decreaseDust(pool, pool.token1, dustTokens); /// Swap for the reward token rewardTokens += _swap( pool, pool.token1, pool.rewardToken, dustTokens, params.min1, params.deadline ); } } /// Credit the reward tokens assigned to the pool if (rewardTokens > 0) { _increaseDust(pool, pool.rewardToken, rewardTokens); } /// Return the amount of reward tokens converted return rewardTokens; } /// Emergency withdraw from a MasterChef pool and assign the pool tokens to the pool /// The owners of the pool tokens can then withdraw from the strategy normally /// Only the strategy can call this function, and it may only be triggered by governance /// /// @param pool pool in the strategy function stop(PoolInfo calldata pool) virtual override(IMasterChefAdapter) external nonReentrant onlyStrategy { /// Get the balance of pool tokens before withdraw uint256 poolTokens = pool.poolToken.balanceOf(address(this)); /// Withdraw all pool tokens from the MasterChef pool _masterChefEmergencyWithdraw(pool); /// The difference after withdraw is the amount of pool tokens actually withdrawn poolTokens = pool.poolToken.balanceOf(address(this)) - poolTokens; /// Credit the pool tokens assigned to the pool _increaseDust(pool, pool.poolToken, poolTokens); } /// Withdraw pool tokens from the adapter and transfer them to the owner /// Only the strategy can call this function, and it may only be triggered by the owner of the pool tokens /// /// @param pool pool in the strategy /// @param poolTokens amount of pool tokens to withdraw /// @param owner address of the owner function exit(PoolInfo calldata pool, uint256 poolTokens, address owner) virtual override(IMasterChefAdapter) external nonReentrant onlyStrategy { /// Debit the pool tokens assigned to the pool _decreaseDust(pool, pool.poolToken, poolTokens); /// Transfer the pool tokens to the owner pool.poolToken.safeTransfer(owner, poolTokens); } ////////// GOVERNANCE FUNCTIONS ////////// /// Transfer tokens that have been airdropped or accidentally sent to the adapter /// Tokens that belong to their owners are assigned to pools and cannot be transferred /// Only governance can call this function /// /// @param token address of the token to send /// @param receiver address to send tokens to /// @param amount amount of tokens to send function transfer(IERC20 token, address receiver, uint256 amount) virtual external nonReentrant onlyGovernance { /// Get the balance of the token on the adapter and subtract any amount that belongs to pools uint256 balance = token.balanceOf(address(this)) - totalDust[token]; /// If the amount is greater than the balance, only transfer the balance if (amount > balance) { amount = balance; } /// Transfer the amount to the receiver token.safeTransfer(receiver, amount); } ////////// INTERNAL FUNCTIONS ////////// /// Deposit pool tokens into a MasterChef pool /// /// @param pool pool in the strategy /// @param poolTokens amount of pool tokens to deposit /// /// @return amount of pool tokens deposited function _deposit(PoolInfo calldata pool, uint256 poolTokens) virtual internal returns (uint256) { /// Get the balance of pool tokens before deposit to check for pools and tokens that may have a fee on transfer uint256 balance = _masterChefBalance(pool); /// Approve the MasterChef to transfer the exact amount of pool tokens pool.poolToken.safeIncreaseAllowance(pool.masterChef, poolTokens); /// Deposit the pool tokens into the MasterChef pool _masterChefDeposit(pool, poolTokens); /// The difference to return is the amount of pool tokens actually deposited return _masterChefBalance(pool) - balance; } /// Withdraw pool tokens from a MasterChef pool /// /// @param pool pool in the strategy /// @param poolTokens amount of pool tokens /// /// @return amount of pool tokens withdrawn function _withdraw(PoolInfo calldata pool, uint256 poolTokens) virtual internal returns (uint256) { /// Get the balance of pool tokens before withdraw to check for pools and tokens that may have a fee on transfer uint256 balance = pool.poolToken.balanceOf(address(this)); /// Withdraw the pool tokens from the MasterChef pool _masterChefWithdraw(pool, poolTokens); /// The difference to return is the amount of pool tokens actually withdrawn return pool.poolToken.balanceOf(address(this)) - balance; } /// Claim pending rewards from a MasterChef pool and transfer them to the adapter /// /// @param pool pool in the strategy /// /// @return amount of reward tokens claimed function _claim(PoolInfo calldata pool) virtual internal returns (uint256) { /// Get the balance of reward tokens before claiming them uint256 rewardTokens = pool.rewardToken.balanceOf(address(this)); /// Claim pending rewards from the MasterChef pool _masterChefClaim(pool); /// The difference after claiming is the amount of reward tokens claimed rewardTokens = pool.rewardToken.balanceOf(address(this)) - rewardTokens; if (rewardTokens > 0) { /// Credit the amount assigned to the pool _increaseDust(pool, pool.rewardToken, rewardTokens); } /// Return the amount of reward tokens claimed return rewardTokens; } /// Convert reward tokens into staking pool tokens /// /// @param pool pool in the strategy /// @param params parameters for compounding /// @param rewardTokens amount of reward tokens /// /// @return amount of pool tokens converted function _compoundStaking(PoolInfo calldata pool, CompoundParams calldata params, uint256 rewardTokens) virtual internal returns (uint256) { /// If a maximum amount of reward tokens to swap is provided, limit the amount to compound if (params.max0 > 0 && rewardTokens > params.max0) { rewardTokens = params.max0; } /// Debit the reward tokens assigned to the pool _decreaseDust(pool, pool.rewardToken, rewardTokens); /// If the reward token is already the pool token, return it if (pool.rewardToken == pool.poolToken) return rewardTokens; /// Otherwise, swap the reward token for the pool token and return the amount received return _swap( pool, pool.rewardToken, pool.poolToken, rewardTokens, params.min0, params.deadline ); } /// Convert reward tokens into liquidity pool tokens /// /// @param pool pool in the strategy /// @param params parameters for compounding /// @param rewardTokens amount of reward tokens /// /// @return amount of pool tokens converted function _compoundLiquidity(PoolInfo calldata pool, CompoundParams calldata params, uint256 rewardTokens) virtual internal returns (uint256) { /// Divide the rewards in half to swap them for token0 and token1 uint256 amount0 = rewardTokens / 2; uint256 amount1 = amount0; /// If a maximum amount of token0 to swap is provided, limit the amount to compound if (params.max0 > 0 && amount0 > params.max0) { amount0 = params.max0; } /// Set the amount of reward tokens to compound for token0 rewardTokens = amount0; /// If the reward token isn't already token0, swap it if (pool.rewardToken != pool.token0) { amount0 = _swap( pool, pool.rewardToken, pool.token0, amount0, params.min0, params.deadline ); } /// If a maximum amount of token1 to swap is provided, limit the amount to compound if (params.max1 > 0 && amount1 > params.max1) { amount1 = params.max1; } /// Add the amount of reward tokens to compound for token1 rewardTokens += amount1; /// If the reward token isn't already token1, swap it if (pool.rewardToken != pool.token1) { amount1 = _swap( pool, pool.rewardToken, pool.token1, amount1, params.min1, params.deadline ); } /// Debit the reward tokens assigned to the pool _decreaseDust(pool, pool.rewardToken, rewardTokens); /// Get the amount of token0 assigned to the pool uint256 dustTokens = dust[pool.masterChef][pool.masterChefPoolId][pool.token0]; if (dustTokens > 0) { /// Debit the amount assigned to the pool _decreaseDust(pool, pool.token0, dustTokens); /// Add the amount to this compound amount0 += dustTokens; } /// Get the amount of token1 assigned to the pool dustTokens = dust[pool.masterChef][pool.masterChefPoolId][pool.token1]; if (dustTokens > 0) { /// Debit the amount assigned to the pool _decreaseDust(pool, pool.token1, dustTokens); /// Add the amount to this compound amount1 += dustTokens; } /// Add token0 and token1 to the pool, returning the amount of pool tokens received return _addLiquidity( pool, amount0, amount1, params.add0, params.add1, params.deadline ); } /// Swap tokens for a pool /// /// @param pool pool in the strategy /// @param tokenIn address of the input token /// @param tokenOut address of the output token /// @param amountIn exact amount of input tokens to swap /// @param amountOut minimum amount of output tokens to receive /// @param deadline deadline for the swap /// /// @return amount of output tokens received by the swap function _swap( PoolInfo calldata pool, IERC20 tokenIn, IERC20 tokenOut, uint256 amountIn, uint256 amountOut, uint256 deadline ) virtual internal returns (uint256) { /// Compose the route to swap address[] memory route = new address[](2); route[0] = address(tokenIn); route[1] = address(tokenOut); /// Get the balance of output tokens before swap to check for tokens that may have a fee on transfer uint256 balance = tokenOut.balanceOf(address(this)); /// Approve the router to transfer the exact amount of the token tokenIn.safeIncreaseAllowance(pool.router, amountIn); /// Swap the input token for the output token (bool success, ) = pool.router.call(abi.encodeWithSelector( SWAP, amountIn, amountOut, route, address(this), deadline )); /// Error if the swap failed require(success, "SWAP_FAILED"); /// The difference to return is the amount received by the swap return tokenOut.balanceOf(address(this)) - balance; } /// Add liquidity to a pool /// /// @param pool pool in the strategy /// @param in0 maximum amount of token0 to add /// @param in1 maximum amount of token1 to add /// @param out0 minimum amount of token0 to add /// @param out1 minimum amount of token1 to add /// @param deadline deadline for adding liquidity /// /// @return amount of pool tokens received function _addLiquidity( PoolInfo calldata pool, uint256 in0, uint256 in1, uint256 out0, uint256 out1, uint256 deadline ) virtual internal returns (uint256) { /// This will be the amount of pool tokens received, defaulting to zero uint256 poolTokens; /// Approve the router to transfer the exact amount of the tokens pool.token0.safeIncreaseAllowance(pool.router, in0); pool.token1.safeIncreaseAllowance(pool.router, in1); /// Add token0 and token1 to the pool, returning the amounts of each added and the pool tokens received (bool success, bytes memory data) = pool.router.call(abi.encodeWithSelector( ADD, address(pool.token0), address(pool.token1), in0, in1, out0, out1, address(this), deadline )); /// Error if adding liquidity failed require(success, "ADD_FAILED"); /// Get the amounts of token0 and token1 added and the amount of pool tokens received (out0, out1, poolTokens) = abi.decode(data, (uint256, uint256, uint256)); /// If adding liquidity doesn't use all of token0, there will be a small amount remaining if (in0 > out0) { /// Credit the amount assigned to the pool, to be used on the next compound or sweep _increaseDust(pool, pool.token0, in0 - out0); /// Zero out the remaining router approval pool.token0.safeApprove(pool.router, 0); } /// If adding liquidity doesn't use all of token1, there will be a small amount remaining if (in1 > out1) { /// Credit the amount assigned to the pool, to be used on the next compound or sweep _increaseDust(pool, pool.token1, in1 - out1); /// Zero out the remaining router approval pool.token1.safeApprove(pool.router, 0); } /// Return the pool tokens received return poolTokens; } /// Credit the dust assigned to a pool and add to the total /// /// @param pool pool in the strategy /// @param token address of the token /// @param amount amount of tokens to add function _increaseDust(PoolInfo calldata pool, IERC20 token, uint256 amount) virtual internal { dust[pool.masterChef][pool.masterChefPoolId][token] += amount; totalDust[token] += amount; } /// Debit the dust assigned to a pool and subtract from the total /// /// @param pool pool in the strategy /// @param token address of the token /// @param amount amount of tokens to subtract function _decreaseDust(PoolInfo calldata pool, IERC20 token, uint256 amount) virtual internal { dust[pool.masterChef][pool.masterChefPoolId][token] -= amount; totalDust[token] -= amount; } ////////// VIRTUAL FUNCTIONS ////////// /// Get the balance of pool tokens in a MasterChef pool /// /// @param pool pool in the strategy /// /// @return amount of pool tokens in the MasterChef pool function _masterChefBalance(PoolInfo calldata pool) virtual internal view returns (uint256); /// Deposit pool tokens into a MasterChef pool /// /// @param pool pool in the strategy /// @param poolTokens amount of pool tokens to deposit function _masterChefDeposit(PoolInfo calldata pool, uint256 poolTokens) virtual internal; /// Withdraw pool tokens from a MasterChef pool /// /// @param pool pool in the strategy /// @param poolTokens amount of pool tokens function _masterChefWithdraw(PoolInfo calldata pool, uint256 poolTokens) virtual internal; /// Claim pending rewards from a MasterChef pool and transfer them to the adapter /// /// @param pool pool in the strategy function _masterChefClaim(PoolInfo calldata pool) virtual internal; /// Emergency withdraw all pool tokens from a MasterChef pool /// /// @param pool pool in the strategy function _masterChefEmergencyWithdraw(PoolInfo calldata pool) virtual internal; } /// A minimal interface for the MasterChefStrategy's access control interface IMasterChefStrategy { /// @dev See {MasterChefStrategy-onlyOperator} function onlyOperator(address account) external view; /// @dev See {MasterChefStrategy-onlyHarvester} function onlyHarvester(address account) external view; /// @dev See {MasterChefStrategy-onlySupervisor} function onlySupervisor(address account) external view; /// @dev See {MasterChefStrategy-onlyAccountant} function onlyAccountant(address account) external view; /// @dev See {MasterChefStrategy-onlyGovernance} function onlyGovernance(address account) external view; /// @dev See {MasterChefStrategy-onlyDeployer} function onlyDeployer(address account) external view; }
Get the balance of pool tokens in a MasterChef pool pool pool in the strategy return amount of pool tokens in the MasterChef pool Deposit pool tokens into a MasterChef pool pool pool in the strategy poolTokens amount of pool tokens to deposit Withdraw pool tokens from a MasterChef pool pool pool in the strategy poolTokens amount of pool tokens Claim pending rewards from a MasterChef pool and transfer them to the adapter pool pool in the strategy Emergency withdraw all pool tokens from a MasterChef pool pool pool in the strategy A minimal interface for the MasterChefStrategy's access control
interface IMasterChefStrategy { function onlyOperator(address account) external view; function onlyHarvester(address account) external view; function onlySupervisor(address account) external view; function onlyAccountant(address account) external view; function onlyGovernance(address account) external view; function onlyDeployer(address account) external view; }
13,035,116